MCP security: threats, authentication, and controls for MCP servers
MCP security is the set of threat models, authentication rules, and runtime controls that keep an agent connected to Model Context Protocol servers from acting for an attacker instead of its user. The risk comes with the design, because every connected server can put text in front of the model and every tool the model can call reaches a real system.
This guide assumes you know what MCP is and have seen how to build an MCP server. It covers the threat model with documented incidents, what the current specification requires for MCP authentication and OAuth, the controls that limit damage, where a gateway fits, and a checklist of where each control is enforced.
MCP security vs API security#
MCP security differs from ordinary API security because the component deciding which tool to call is a language model that reads every tool description and tool result as text. It cannot reliably tell data from instructions, so any server, document, or issue that reaches its context can try to steer it, and the protocol cannot prevent that.
The specification says so directly. It lists user consent, data privacy, and tool safety as principles, states that "MCP itself cannot enforce these security principles at the protocol level," and assigns them to implementers. That leaves three trust boundaries:
- Model and context. Every tool description, schema, and result arrives as a JSON-RPC message and lands in the model's context, where tool poisoning and prompt injection work.
- Client and server. A remote MCP server is a network service that accepts tokens, so OAuth, audience, and scopes apply.
- Server and machine. A local server runs with the user's privileges, so supply chain attacks and sandboxing apply.
The MCP threat model#
The MCP threat model has eight recurring attack classes: tool poisoning, rug pulls, prompt injection through tool results, data exfiltration across servers, confused deputy and token passthrough, over-broad OAuth scopes, session or state handle hijacking, and compromised local servers. Most have a published demonstration or advisory, and the official Security Best Practices page describes the protocol-level ones.
Tool poisoning and rug pulls#
Tool poisoning hides instructions for the model in tool metadata that the user rarely sees in full. Invariant Labs disclosed the attack on April 1, 2025, with an add tool whose description told the agent to read ~/.ssh/id_rsa and ~/.cursor/mcp.json and pass them in a sidenote argument without telling the user. Hosts typically load tool definitions into context before any call, so a poisoned tool works even if it is never invoked.
A rug pull is the same attack delivered late. The user approves a harmless definition, and the server changes it afterward. In Invariant Labs' WhatsApp experiment of April 7, 2025, a "sleeper" server advertised a trivia tool, switched its description on a later launch, and told the agent to send the user's chat history through a separate, legitimate WhatsApp server. Tool lists change in normal operation, announced with notifications/tools/list_changed, so a client that never compares new definitions with approved ones has no defense.
Prompt injection through tool results#
Prompt injection through tool results needs no malicious server. In May 2025, Invariant Labs showed an attacker filing an issue in a public repository. When the owner asked an agent in Claude Desktop, connected to the official GitHub MCP server, about open issues, the agent followed the issue's instructions and published details from the owner's private repositories in a pull request on the public one. The researchers called the flaw architectural rather than a server bug, and no output filter makes attacker-written text safe to read.
Data exfiltration across servers#
Cross-server exfiltration happens when one agent holds three capabilities at once. Simon Willison named this the lethal trifecta in June 2025: access to private data, exposure to untrusted content, and the ability to communicate externally. MCP makes the combination easy, because users connect servers from different sources to one host, and each server's tools are open to instructions arriving from any other.
In the WhatsApp attack the malicious server was never called, and Invariant Labs noted that sandboxing it would not have helped, because the attack relies only on the agent following instructions. Effective controls break one leg of the trifecta per agent or session.
Confused deputy and token passthrough#
A confused deputy attack abuses an MCP server that proxies a third-party API with one static OAuth client ID. The user's first approval leaves a consent cookie at the third-party authorization server. An attacker then dynamically registers a client with its own redirect URI and sends the user a crafted link. The cookie skips the consent screen, and the authorization code is redirected to the attacker. Proxy servers must keep per-client consent and match redirect URIs and state exactly.
Token passthrough means accepting a token issued for another resource, or forwarding the client's token to a downstream API. It bypasses downstream rate limits and monitoring, puts the wrong identity in audit logs, and lets a stolen token move between services, so the authorization specification says servers "MUST NOT accept or transit any other tokens."
Over-broad scopes and state handle hijacking#
Over-broad scopes turn one leaked token into access to everything a server offers. The Security Best Practices page describes tokens carrying files:* or admin:* because the server listed every scope in scopes_supported and the client requested them all, and it names wildcard scopes and trusting token scopes without server-side checks as common mistakes.
Session hijacking applied to revision 2025-11-25 and earlier, where a stolen Mcp-Session-Id could inject events or impersonate a user. Revision 2026-07-28 removed protocol-level sessions, so the risk moved to state handles, the cart or workflow IDs a server mints and the model passes back as arguments. Servers must not treat a handle as authentication and should bind each one to the authenticated user, for example as <user_id>:<handle>.
Local server supply chain and command injection#
Local servers are a direct path to code execution, because the host launches them as the user. The Security Best Practices page lists malicious startup commands in one-click configurations, malicious payloads inside a server, and DNS rebinding against servers listening on localhost. Published advisories show how these risks play out:
- Malicious package. Postmark reported on September 25, 2025, that
postmark-mcp, an npm package it did not publish, built trust over 15 versions before version 1.0.16 began blind-copying sent emails to an external server. - Client command injection. JFrog's CVE-2025-6514 (CVSS 9.6) showed that
mcp-remote0.0.5 through 0.1.15 opened a malicious server's craftedauthorization_endpointin a way that allowed arbitrary command execution on Windows. Version 0.1.16 fixed it. - Unauthenticated local proxy. Oligo Security's CVE-2025-49596 (CVSS 9.4) showed that MCP Inspector before 0.14.1 let a web page reach its local proxy and spawn stdio commands.
- Path validation. Cymulate reported a prefix-match directory bypass (CVE-2025-53110) and a symlink bypass (CVE-2025-53109) in the reference Filesystem MCP server, fixed in version 2025.7.1.
OAuth discovery is an attack surface too. A malicious server controls the metadata URLs a client fetches, so it can point them at internal addresses such as the 169.254.169.254 cloud metadata endpoint. Clients should require HTTPS and block private IP ranges, and must accept only http and https authorization URLs and never open them through a shell.
OWASP's MCP Top 10, still in beta, gives most of these threats an ID, including MCP02 Privilege Escalation via Scope Creep, MCP03 Tool Poisoning, MCP04 Software Supply Chain Attacks & Dependency Tampering, MCP05 Command Injection & Execution, and MCP06 Prompt Injection via Contextual Payloads. On the model side, the 2025 Top 10 for LLM Applications lists Prompt Injection as LLM01 and Excessive Agency as LLM06.
MCP authentication and authorization: what the specification requires#
MCP authentication for remote servers is OAuth 2.1. Under the authorization specification in revision 2026-07-28, the current revision as of November 2026, a protected server is an OAuth resource server, the MCP client is an OAuth client, and a separate authorization server issues tokens. Authorization is optional, but HTTP implementations that support it should conform.
The flow applies to HTTP-based transports; stdio servers should not use it and should read credentials from the environment instead. It builds on the OAuth 2.1 draft, Protected Resource Metadata (RFC 9728), Authorization Server Metadata (RFC 8414) and OpenID Connect Discovery, Resource Indicators (RFC 8707), Issuer Identification (RFC 9207), and the OAuth Client ID Metadata Document draft.
The MCP OAuth flow step by step#
The MCP OAuth flow starts with a request that fails. The server answers 401 with a pointer to its metadata, the client discovers the authorization server, identifies itself, runs an authorization code flow with PKCE and a resource indicator, and retries with a token bound to that one server. Every later request carries the token.
- The server answers an unauthenticated request with
401and aWWW-Authenticateheader carryingresource_metadataand, ideally, the requiredscope. - The client reads
authorization_serversfrom the Protected Resource Metadata and fetches that server's metadata. Ifcode_challenge_methods_supportedis absent, the client must stop. - The client identifies itself, preferably with a Client ID Metadata Document, and authorizes with an S256 PKCE challenge and a
resourceparameter naming the server. - Before redeeming the code, the client compares any returned
isswith the issuer it recorded, which blocks mix-up attacks (RFC 9207). - The client sends the token in the
Authorization: Bearerheader on every request, never in a query string, and the server checks audience, expiry, and scopes.
Protected Resource Metadata and discovery#
Protected Resource Metadata is how an MCP server tells clients where to get tokens. Servers must implement RFC 9728 and list at least one authorization server. Clients use the resource_metadata URL from the WWW-Authenticate header when present and otherwise probe well-known URIs, first at the MCP endpoint's path and then at the root.
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp",
scope="tickets:read"{
"resource": "https://mcp.example.com/mcp",
"authorization_servers": ["https://auth.example.com"],
"scopes_supported": ["tickets:read", "tickets:write"],
"bearer_methods_supported": ["header"]
}Clients must support both RFC 8414 metadata and OpenID Connect Discovery and try their well-known URLs in a fixed order. The issuer in the returned document must match the issuer used to build the URL exactly, or the client must discard it.
Client registration: CIMD, pre-registration, and DCR#
Clients must obtain a client ID before the flow starts, and the specification defines three ways to get one. Client ID Metadata Documents (CIMD) cover the common MCP case in which client and server have never met. Dynamic Client Registration (DCR) was deprecated in revision 2026-07-28 and remains only for authorization servers without CIMD support.
| Mechanism | How the client identifies itself | Status in 2026-07-28 |
|---|---|---|
| Pre-registration | A client ID issued ahead of time | Supported; first in priority when available |
| Client ID Metadata Document | An HTTPS URL as client_id, pointing to JSON with client_name and redirect_uris |
Recommended |
| Dynamic Client Registration (RFC 7591) | A POST to the registration endpoint |
Deprecated; kept for compatibility |
The client registration page sets the order: pre-registered credentials, then CIMD when the authorization server advertises client_id_metadata_document_supported, then DCR, then asking the user. A metadata document proves control of a domain, not which local process listens on a localhost redirect URI, so authorization servers must display the redirect hostname and should warn about localhost-only redirects.
Resource indicators, PKCE, and scopes#
Resource indicators bind each token to one MCP server. Clients must send the resource parameter, set to the server's canonical URI such as https://mcp.example.com/mcp, in both the authorization and token requests, and servers must validate that each token names them as its audience. Clients must also use PKCE with S256 when technically capable.
The security considerations add HTTPS for authorization endpoints, localhost or HTTPS redirect URIs, short-lived access tokens, and refresh token rotation for public clients. Scopes start small, since scopes_supported is meant as the minimal set, and a call that needs more gets 403 with error="insufficient_scope". The client then requests the union of its earlier and challenged scopes, retrying a limited number of times.
Calling upstream APIs without token passthrough#
An MCP server that calls a third-party API for the user needs its own credential for that API, because the client's token is valid for the MCP server only. The server acts as an OAuth client to the upstream service and stores the resulting token bound to the user's verified identity, never forwarding the token it received.
URL-mode elicitation, added in revision 2025-11-25, is the standard way to start that flow. The client shows the server's URL in full and asks for consent, and the user authorizes the third party in the browser. Third-party credentials must not transit the MCP client, and the server must verify that the user completing the flow is the one who started it.
STDIO servers and credentials from the environment#
Stdio servers do not use the OAuth flow. The specification says they should retrieve credentials from the environment, so the host's configuration supplies a token in the server's env block, and the security boundary is the process the host launched. The credential's own scope becomes the main control, so give a local server a fine-grained, read-only, or short-lived token.
Local servers that listen over HTTP need more. They should require an authorization token or use a Unix domain socket, must validate the Origin header and answer 403 to an invalid one, and should bind to 127.0.0.1 rather than all interfaces. MCP Inspector's fix for CVE-2025-49596 added two of these controls, a session token and origin checks.
Controls that reduce MCP risk#
The controls that matter most limit what any single agent can reach, make every tool definition and call visible to a person or a policy, and contain local code. No single control stops prompt injection, so the goal is that an injected instruction finds no broad token, no unapproved write, and no outbound channel.
Least privilege and tool allowlists#
Least privilege starts at the authorization server: publish a minimal scopes_supported, split read and write scopes, challenge for write scopes only when a write tool is called, and back read-only tools with read-only upstream credentials. Enforce ownership rules in server code on every call, because a valid scope says nothing about which records a user may touch.
A tool the model never sees cannot be abused through injection. Approve servers individually, expose only the tools each role needs, and filter tools/list per caller, which the specification allows because the list may vary with the authorization on the request. An MCP gateway is one way to hold that allowlist in one place.
Human approval for consequential tools#
The tools specification says there should always be a human in the loop who can deny tool invocations, and that clients should show tool inputs before calling a server. Approval works only if the dialog shows full argument values; Invariant's poisoned call hid an SSH key in an argument the confirmation did not display. Require approval for writes, deletes, payments, and messages, and treat readOnlyHint and destructiveHint annotations from unknown servers as untrusted claims.
Sandboxing local servers in containers#
A sandbox limits what a compromised local server can do on the user's machine. The Security Best Practices page tells clients to run local servers with minimal privileges and restricted file system and network access. A container launched as a stdio server keeps the protocol unchanged, because the host talks to docker run -i over standard input and output:
{
"mcpServers": {
"notes": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"--read-only", "--network", "none",
"--cap-drop", "ALL",
"--security-opt", "no-new-privileges=true",
"--memory", "512m", "--pids-limit", "100",
"-v", "/Users/me/notes:/data:ro",
"ghcr.io/example/notes-mcp@sha256:<digest>"
]
}
}
}The image is pinned by digest, the file system is read-only, and --network none leaves only a loopback interface. A server that calls an API needs network access and a token. Add -e NAME so Docker forwards the value from the host's env block, and route egress through an allowlisting proxy. The agent sandbox entry covers stronger isolation, such as gVisor and microVMs.
Pinning versions and verifying tool definitions#
Pinning stops a server from changing without review. Pin package versions or image digests rather than latest or an unpinned npx -y. Then pin the definitions: hash each approved tool's name, description, and schemas, compare the hash on every tools/list, and block a changed tool until a user approves it again, as Invariant Labs recommended. Scanners such as Snyk Agent Scan check configured MCP servers for prompt injection, and the guardrails and AI security directory lists more tools.
Separating untrusted content from private data#
Separation means no agent session holds private data, untrusted content, and an outbound channel at once. A triage agent that reads public issues or inbound email gets read-only tools, and the agent with private access never reads attacker-controllable text; Invariant's suggested policy for the GitHub attack limited each session to one repository. Within a session, label third-party text and apply guardrails to tool arguments, for example to flag a private key in an outgoing message.
Rate limits, logging, and audit#
The tools specification requires servers to rate limit tool invocations and recommends that clients set timeouts and log tool usage for audit. Rate limiting per token and per tool, plus result size caps, also limits damage from an agent looping on an injected instruction. Log the tool, server, caller, redacted arguments, status, latency, and triggering model request, and send them to your LLM observability stack; revision 2026-07-28 documents OpenTelemetry trace context keys in _meta.
The official MCP Registry and its trust model#
The official MCP Registry authenticates publishers, not code. It is a metadata catalog, in preview as of November 2026, in which server names use reverse-DNS namespaces such as io.github.username/server, and only the owner of that GitHub account or domain can publish under them, verified through GitHub, DNS, or HTTP challenges.
The registry documentation delegates security scanning to package registries such as npm and PyPI and to downstream aggregators, which hosts are expected to consume instead of the registry itself. A listing tells you who published a server, not whether it is safe; the MCP platforms directory lists catalogs that add curation on top.
The gateway as a policy enforcement point#
An MCP gateway puts many of these controls in one place. Hosts connect to a single endpoint, and the gateway authenticates each caller, filters the tool list, holds upstream credentials, applies approval rules, and logs every call. The trade-off is concentration, because the gateway holds every server's credentials and must follow the same no-passthrough rules as any MCP server.
Bifrost, the open source AI gateway from Maxim AI, shows how these controls map onto configuration:
- Tool filtering per virtual key. Each virtual key carries an MCP allowlist per connected server. The filtering docs describe it as deny-by-default: a key with no MCP configuration gets no tools, and request headers can narrow the list but never widen it.
- Upstream OAuth 2.0 and per-user OAuth. Bifrost supports an admin OAuth 2.0 token shared by all callers or per-user OAuth, which stores one upstream token per identity; a call without a valid user token is not executed, and the caller gets a sign-in URL.
- Agent mode with configurable auto-approval. By default, Bifrost returns tool calls to the application. Agent mode runs only the tools in
tools_to_auto_execute, returns the rest for approval, and caps the loop withmax_agent_depth. - Tool logs and audit logs. Bifrost records each tool execution with its arguments, result, latency, and virtual key in its MCP logs. Bifrost Enterprise adds audit logs of administrative changes, each row signed with HMAC-SHA256.
A virtual key that can run only check-status from a billing server, plus every tool from a support server, looks like this in Bifrost's config.json:
{
"governance": {
"virtual_keys": [
{
"id": "vk-billing-support-only",
"name": "VK for Billing and Support",
"mcp_configs": [
{ "mcp_client_name": "billing-client", "tools_to_execute": ["check-status"] },
{ "mcp_client_name": "support-client", "tools_to_execute": ["*"] }
]
}
]
}
}Other MCP gateways cover overlapping ground. Docker MCP Gateway runs each server in an isolated container with restricted privileges and network access and injects the credentials each server needs, Stacklok's ToolHive also runs servers in containers with per-request access policy, and IBM's ContextForge, Microsoft MCP Gateway, and agentgateway proxy and govern MCP traffic. What an AI gateway is covers the model-traffic side that several of them also handle.
MCP security checklist#
The checklist maps each risk to its main control and to where that control is enforced. Client means the MCP host and its clients, server means the MCP server and its authorization server, and gateway means an MCP gateway or proxy between them. Most risks need more than one enforcement point, so treat each row as a minimum.
| Risk | Control | Enforced at |
|---|---|---|
| Tool poisoning, rug pulls | Show full descriptions; hash approved definitions; re-approve on change | Client, gateway |
| Prompt injection via results | Label third-party text; guardrails on results; least privilege | Server, client, gateway |
| Cross-server exfiltration | Keep private data, untrusted content, and outbound tools in separate sessions | Client, gateway |
| Token passthrough | Validate audience; use a separate upstream credential | Server, gateway |
| Confused deputy | Per-client consent; exact redirect URI match; single-use state |
Server |
| Over-broad scopes | Minimal scopes_supported; step-up challenges; no wildcards |
Server |
| Stolen tokens | PKCE S256; short-lived tokens; refresh rotation; header-only bearer tokens | Client, server |
| State handle hijacking | Random handles bound to the verified user ID | Server |
| Malicious local server | Show the full command; pin digests; run in a container | Client |
| DNS rebinding | Validate Origin; bind to 127.0.0.1; require a token |
Server |
| SSRF during discovery | HTTPS only; block private IP ranges; egress proxy | Client |
| Unapproved actions | Human approval for writes; auto-approve read-only tools only | Client, gateway |
| Abuse and audit gaps | Rate limits, timeouts, and logs for every tool call | Server, gateway |
Where to go next#
Agents that call other agents raise their own trust questions, and A2A vs MCP compares how the two protocols handle identity and authorization. For the protocol architecture, server tutorials, and gateway guides that this checklist builds on, the MCP hub collects every guide in the cluster.
Frequently asked questions
Does MCP use OAuth?
- Yes, for remote servers. The MCP authorization specification is based on OAuth 2.1: a protected MCP server acts as an OAuth resource server, publishes Protected Resource Metadata (RFC 9728) that points to its authorization server, and accepts only tokens issued for it. Clients must use PKCE and send a resource indicator (RFC 8707). Authorization is optional, and stdio servers take credentials from the environment instead.
How does MCP server authentication work?
- A client calls the server without a token and receives a 401 response whose WWW-Authenticate header points to the server's metadata. The client discovers the authorization server, identifies itself with a Client ID Metadata Document or a pre-registered client ID, runs an authorization code flow with PKCE, and retries with a bearer token. The server validates the token's audience, expiry, and scopes on every request.
What is token passthrough in MCP?
- Token passthrough is an anti-pattern in which an MCP server accepts a token that was not issued for it, or forwards the client's token to a downstream API. It bypasses the downstream service's controls, breaks audit trails, and lets a stolen token move between services. The MCP authorization specification forbids it. Servers accept only their own tokens and use a separate credential for upstream APIs.
What is the confused deputy problem in MCP?
- It is an attack on MCP proxy servers that use one static OAuth client ID with a third-party API. After a user consents once, the third-party authorization server sets a consent cookie. An attacker registers a new client with its own redirect URI and sends the user a link; the cookie skips consent, and the authorization code reaches the attacker. Per-client consent and exact redirect URI checks prevent it.
How do you prevent tool poisoning in MCP?
- Allowlist the servers you connect, show users full tool descriptions and full call arguments, and pin approved tool definitions by hash so a changed description is blocked until someone approves it again. Give each server the least privilege that works, keep untrusted content away from agents that hold private data, and route servers through a gateway that enforces the allowlist and logs every call.
Do local MCP servers need authentication?
- Local servers on stdio do not use the MCP OAuth flow; the host launches them as a subprocess and passes credentials through environment variables. A local server that listens over HTTP is different. It should require an authorization token or use a Unix domain socket, validate the Origin header, and bind to 127.0.0.1, because web pages can otherwise reach it through DNS rebinding.
Terms in this guide
Cite this guide
The AI Engineering Editors. "MCP security: threats, authentication, and controls for MCP servers." The AI Engineering, updated Nov 17, 2026. https://theaiengineering.com/articles/mcp-security
- Title
- MCP security: threats, authentication, and controls for MCP servers
- Author
- The AI Engineering Editors
- Publisher
- The AI Engineering
- Published
- Updated