Secure MCP Server Design: Auth, Permissions & Runtime
Secure MCP (Model Context Protocol) server design requires explicit authentication, granular permission controls, and strict runtime isolation to prevent unauthorized access and data breaches. This article explains how to implement these three layers, what common pitfalls to avoid, and how to choose the right approach for your use case.
Background: Why MCP Servers Need Special Security
MCP servers act as a bridge between AI models (like Claude or custom LLMs) and external tools, databases, or APIs. They receive natural-language requests, translate them into structured actions, and return results. Because the model may be instructed by a user to perform arbitrary actions, the server must enforce security boundaries that normal human-driven applications don’t need. A compromised MCP server could let an attacker read sensitive files, execute commands, or exfiltrate data through the connected tools.
The protocol itself does not mandate a specific security model; it leaves authentication, authorization, and runtime enforcement to the implementer. That flexibility is why many early MCP servers are insecure by default, often relying on the assumption that the client is trusted. This article focuses on practical, defense-in-depth measures you can apply today.
Authentication: Verifying Who Is Calling
Authentication confirms the identity of the client (the AI application or user) before any request is processed. For MCP servers, the common approaches are:
- API keys or bearer tokens: The client presents a secret in the Authorization header. Simple to implement, but you must store keys securely and rotate them regularly.
- OAuth 2.0 / OpenID Connect: For user-facing applications, this allows delegated authorization. The server validates JWT tokens and checks scopes. More complex but supports fine-grained user identity.
- Mutual TLS (mTLS): Both client and server present certificates. Strongest for machine-to-machine communication, preventing impersonation and man-in-the-middle attacks.
Regardless of method, always use HTTPS/TLS in production. Never accept plain HTTP for authentication. Additionally, implement rate limiting to mitigate brute-force attacks on token endpoints.
Permission Controls: Least Privilege in Practice
Authentication only tells you who is calling; permissions decide what that caller can do. The principle of least privilege means granting only the minimum access required for the task. For MCP servers, this translates to:
- Per-tool permissions: Each tool exposed via MCP should have a defined set of allowed operations. For example, a database tool might allow SELECT but not DROP TABLE.
- Per-resource scoping: If the server accesses files, restrict paths. If it accesses APIs, restrict endpoints and methods.
- User/role mapping: Map authenticated users to roles (e.g., admin, read-only, analyst) and enforce role-based access control (RBAC) on every request.
Implement an authorization layer that checks each incoming request against a policy. Avoid embedding permissions in the tool’s code; instead, use a centralized policy engine (e.g., OPA, Casbin) that can be updated without redeploying the server.
Runtime Controls: Sandboxing and Resource Limits
Even with strong auth and permissions, a malicious or buggy tool invocation could cause harm. Runtime controls limit what the server process can do and how much it can consume:
- Containerization: Run the MCP server in a Docker container with no unnecessary capabilities. Use read-only root filesystem, drop all Linux capabilities, and set a non-root user.
- Network egress filtering: Block outbound network connections except to allowlisted endpoints. This prevents data exfiltration if the server is compromised.
- Resource quotas: Set CPU, memory, and file descriptor limits. Use cgroups or container runtime flags to prevent denial-of-service.
- Timeouts: Enforce maximum execution time for each tool call. A runaway query should be killed, not allowed to hang.
For extra isolation, consider running each tool invocation in a separate subprocess with a fresh environment. This is heavier but contains any exploit to a single call.
Common Mistakes and How to Avoid Them
Developers often overlook several critical aspects when designing MCP servers:
- Trusting the client to send the correct user ID: Never rely on a client-supplied header like
X-User-IDfor authorization. Always derive identity from the authenticated session. - Ignoring path traversal: When handling file paths, sanitize inputs and use a library that resolves paths safely. A simple
..can escape the intended directory. - Logging sensitive data: Logging tool inputs and outputs can leak API keys, personal data, or secrets. Redact or hash sensitive fields.
- Not validating tool arguments: The AI model may produce malformed or malicious arguments. Validate types, ranges, and formats before acting.
Mitigate these by using a security linter, doing regular code reviews, and running penetration tests on the server.
How to Choose the Right Security Level
Not every MCP server needs the same level of protection. Consider these factors:
- Data sensitivity: If the server accesses personal, financial, or health data, you need the highest security (mTLS, RBAC, full sandboxing).
- Deployment environment: A server on a localhost for personal use can be simpler, but still use at least a token and local firewall.
- User base: Public-facing servers require robust auth and rate limiting; internal tools might rely on network segmentation.
- Compliance requirements: Regulations like GDPR or HIPAA impose specific controls. Ensure your design meets them.
Start with the minimum that meets your risk tolerance, then add layers as needed. Document your security decisions for auditors.
Comparison: DIY vs. Managed MCP Gateways
You can build security into your MCP server from scratch, or use a managed gateway that sits between the AI and your tools. DIY gives you full control and avoids vendor lock-in, but requires security expertise and ongoing maintenance. Managed gateways (e.g., from cloud providers or specialized security firms) offer pre-built authentication, policy enforcement, and audit logging, but may add latency and cost.
For most production use cases, a hybrid approach works well: use a lightweight gateway for auth and rate limiting, and implement tool-specific permissions in your server code. This balances control with convenience.
Costs and Performance Trade-offs
Security features have real costs:
- Latency: Every auth check, policy evaluation, and sandbox setup adds milliseconds. For high-throughput systems, optimize by caching token validation results.
- Infrastructure: mTLS requires certificate management; containers require orchestration. These add operational overhead.
- Development time: Implementing RBAC and sandboxing correctly takes effort. Using libraries and frameworks can reduce this.
Measure the impact on your specific workload. Often the security overhead is negligible compared to the cost of a data breach.
Alternatives to Traditional Runtime Sandboxing
If full container isolation is too heavy, consider lighter alternatives:
- WebAssembly (Wasm): Run tool code in a Wasm sandbox with strict memory limits. Fast startup and fine-grained control.
- Language-level sandboxes: For interpreted languages, use restricted environments (e.g., Python’s
restrictedmode) but be aware they are not foolproof. - OS-level permissions: Run the server as a dedicated user with minimal file access and no shell. This is simpler than containers but less isolated.
Choose based on your threat model and the trust level of the tool code. Always assume the worst-case scenario and design accordingly.
Frequently Asked Questions
What is the difference between authentication and authorization in MCP?
Authentication verifies who is making the request (e.g., via token or certificate). Authorization determines what that identity is allowed to do (e.g., which tools, which resources). Both are required; authentication without authorization leaves the server open to privilege escalation.
Can I use a simple API key for a public MCP server?
Yes, but it is not recommended. API keys are easy to leak and hard to rotate. For public access, use OAuth 2.0 with short-lived tokens and refresh flows. If you must use API keys, store them hashed, allow revocation, and implement rate limiting.
How do I prevent an AI model from calling dangerous tools?
Implement a deny-list or allow-list of tool names and arguments. For example, a tool that executes shell commands should be disabled entirely unless absolutely necessary. If required, restrict it to a whitelist of commands and use argument validation. Also, consider a human-in-the-loop approval step for high-risk actions.
What is the best way to log MCP server activity without leaking secrets?
Log metadata (tool name, user ID, timestamp, result status) but not the full payload. If you must log arguments, redact fields that look like secrets (e.g., using regex for password, token). Store logs in a secure location with access controls.
Is it safe to run MCP server in a Docker container?
Containers are not a security boundary by themselves, but they help. Use them with a read-only root filesystem, drop all capabilities, run as a non-root user, and limit network access. Combine with a seccomp profile for stronger isolation.
How often should I rotate credentials for MCP servers?
For API keys, rotate at least every 90 days, or immediately if a leak is suspected. For OAuth tokens, use short-lived access tokens (e.g., 15 minutes) and refresh tokens with longer expiry. For mTLS certificates, rotate annually or when compromised.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.