MCP Security and Permissions
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
An MCP server is code that does things, and a connected server's text goes straight into your model's context. That makes MCP useful and also makes it an attack surface. The official project publishes security best practices, and this lesson turns them into things you can build: an allow list with an audit trail, a wrapper for untrusted results, a guard against requests to private networks, and a token check for a remote server. All of it was tested.
What you'll learn
- Where the risks come from: servers you connect, text they return, tokens you hold.
- The attacks the MCP security guidance names, in plain terms.
- Code for allow lists, rate limits, audit logs and URL checks.
- A short checklist to run before connecting any server.
Before you start
Where the risk is
Think in three places:
- The server's code. A local stdio server runs with your privileges. A malicious or buggy one can read files or send data out.
- The server's words. Tool descriptions and tool results are text the model reads. Hostile text there can try to steer the model, which is prompt injection by another route. A third-party server's output is only as trustworthy as that third party, and anything it fetches from the internet is only as trustworthy as the internet.
- The credentials. Tokens that let a server act as a user are valuable, and the more powerful the token, the worse its theft.
The Claude Code documentation says it directly: verify you trust each server before connecting it, since servers that fetch external content can expose you to prompt injection.
The attacks, in plain terms
The security best-practices page names several. These are the ones you're most likely to meet:
- Local server compromise. An attacker gets a malicious start command into a client's configuration, or ships a poisoned server. Because stdio servers run with the client's privileges, the damage can be arbitrary code execution and data theft. Defences: show the exact command and ask before running a new one, sandbox servers with minimal privileges, and don't run things you haven't read.
- Token passthrough. A server accepts a token that wasn't issued for it and forwards it to another service. The guidance forbids this: an MCP server must not accept tokens it didn't issue for itself. It breaks audit trails and bypasses controls that depend on who the token was for.
- Confused deputy. An MCP server that proxies to a third-party API can be tricked into granting access without proper user consent, especially if it uses one fixed client ID with that third party. Defence: per-client consent that the MCP server owns, plus strict redirect URI checks.
- Server-side request forgery (SSRF). A malicious server can feed a client URLs that point at internal addresses, for example cloud metadata endpoints on
169.254.169.254 or services on localhost. Defences: require HTTPS, block private and reserved address ranges, validate redirects and, for servers, route outbound requests through an egress proxy.
- State handle hijacking. If a server hands out an ID for a cart or workflow and trusts whoever presents it, anyone who guesses it can use it. Defence: random, expiring handles, bound to the authenticated user and checked on every request.
- Over-broad scopes. Tokens that grant everything make theft catastrophic. Start with minimal scopes and ask for more only when needed.
Your own policy, in code
The guard below sits between the agent and every MCP tool. It checks an exact-match allow list, caps argument size, rate-limits each tool and writes an audit entry for every decision. The audit entries deliberately don't include the arguments, which may contain customer data:
"""Guardrails around MCP tool calls, decided by YOU rather than by the server."""
import ipaddress
import json
import re
import socket
import time
from collections import defaultdict, deque
from dataclasses import dataclass, field
from urllib.parse import urlparse
class Denied(Exception):
pass
@dataclass
class Guard:
allow: set[str] # tool names this agent may call (exact match)
max_calls_per_minute: int = 30
max_arg_chars: int = 2000
clock: callable = time.monotonic
audit: list = field(default_factory=list)
_recent: dict = field(default_factory=lambda: defaultdict(deque))
def check(self, tool: str, arguments: dict) -> None:
"""Raise Denied before the call is made. Every decision is written to the audit list."""
size = len(json.dumps(arguments, default=str))
if tool not in self.allow:
self._log(tool, "denied", "not on the allow-list")
raise Denied(f"The tool '{tool}' is not allowed for this agent.")
if size > self.max_arg_chars:
self._log(tool, "denied", f"arguments too large ({size})")
raise Denied("The arguments are too large for this tool.")
now = self.clock()
window = self._recent[tool]
while window and now - window[0] > 60:
window.popleft()
if len(window) >= self.max_calls_per_minute:
self._log(tool, "denied", "rate limit")
raise Denied(f"Too many calls to '{tool}' this minute. Wait and try again.")
window.append(now)
self._log(tool, "allowed", "")
def _log(self, tool: str, decision: str, why: str) -> None:
self.audit.append({"tool": tool, "decision": decision, "why": why}) # arguments are not logged: they may be private
TAG = re.compile(r"</?\s*tool_output[^>]*>", re.IGNORECASE)
def wrap_untrusted(server: str, tool: str, text: str) -> str:
"""Mark a tool result as data. Remove any look-alike tags from the text so it can't close our wrapper early.
This reduces confusion; it does not make hostile text safe. The real protections are least privilege and approvals."""
clean = TAG.sub("", text)
return f'<tool_output server="{server}" tool="{tool}">\n{clean}\n</tool_output>'
def check_server_url(url: str, allow_loopback: bool = False, resolver=socket.getaddrinfo) -> str:
"""Refuse server URLs that are not https or that point at private networks (SSRF protection).
Resolves the host and checks every address. A DNS answer can change later, so also restrict egress in the network."""
parts = urlparse(url)
host = parts.hostname or ""
if parts.scheme not in ("https", "http") or not host:
raise Denied("Only http and https server URLs are allowed.")
infos = resolver(host, parts.port or (443 if parts.scheme == "https" else 80), proto=socket.IPPROTO_TCP)
addresses = {ipaddress.ip_address(i[4][0]) for i in infos}
loop_only = all(a.is_loopback for a in addresses)
if loop_only and allow_loopback:
return url
if parts.scheme != "https":
raise Denied("Use https for remote MCP servers.")
for a in addresses:
if a.is_private or a.is_loopback or a.is_link_local or a.is_reserved or a.is_multicast or a.is_unspecified:
raise Denied(f"{host} resolves to a private or reserved address.")
return url
What each part does, and what it doesn't
Guard stops calls to tools you didn't allow, oversized arguments and floods. The test advances a fake clock to show the rate window resets after a minute.
wrap_untrusted puts a result inside <tool_output> tags and strips look-alike tags so the text can't "close" the wrapper and masquerade as your instructions. This reduces confusion for the model; it does not make hostile text safe. A clever message inside the wrapper can still be persuasive. The real protections are the ones above and below it: least privilege and a person approving risky actions.
check_server_url resolves a host and rejects the URL if any address it resolves to is private, loopback, link-local, reserved or multicast, and rejects non-HTTPS unless you opt in to loopback for development. Our tests cover 10.x, the cloud metadata address, a host that resolves to one public and one private address, plain HTTP to a public host, localhost, IPv6 ::1, and file: and javascript: URLs. The guidance warns not to hand-roll IP parsing, which is why this uses Python's ipaddress module on the addresses the resolver returns. DNS answers can change between the check and the request, so network-level egress limits remain the stronger defence.
Protecting a remote server
If you serve MCP over HTTP, authenticate every request. Lesson 7.6 showed the token check; here it is again from the client side. The SDK's HTTP transport takes a pre-configured HTTP client, so you add the header there:
import httpx2
from mcp.client import Client
from mcp.client.streamable_http import streamable_http_client
http = httpx2.AsyncClient(headers={"Authorization": f"Bearer {token}"})
async with Client(streamable_http_client("https://mcp.example.com/mcp", http_client=http)) as c:
tools = await c.list_tools()
That's the SDK's own HTTP library (installed with mcp), which is why the import isn't plain httpx. We ran this against a local server with the token check from 7.6: no token, a wrong token and a token missing "Bearer" all got a 401, and the right token worked. A single shared bearer token is fine for learning and internal use. For anything public, follow the MCP authorization specification's OAuth flow, with tokens issued for your server only and never passed through to other services.
A checklist before connecting a server
- Do I know who wrote it and can I read its source? Is the version pinned?
- What command does it run, with what privileges? Can it run in a container or with a restricted user?
- Which of its tools do I actually need? Allow only those.
- Which tools change something? Put those behind a person.
- What does it fetch from outside? Treat that content as untrusted.
- What credential does it hold, and how narrow is it? Can it be read-only?
- Where do its logs go, and could they contain customer data?
- What happens if it changes its tool list tomorrow? An allow list means a new tool stays invisible; the API connector's pinned tool list beta is another option.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A developer finds a community MCP server that "summarises web pages" and wants to add it to a support agent. Running the checklist: it fetches arbitrary URLs (so its output is untrusted and it can reach internal addresses if misused), it runs as a local process with the developer's privileges, and its source has no tests. They decide not to give it to the customer-facing agent. They try it in an isolated container with no credentials, allow-listing its one tool, and only for an internal research assistant whose actions can't change anything. The agent that talks to customers keeps only the shop server.
Mistakes to avoid
- Installing servers because they're popular, without reading what they run.
- Trusting annotations and descriptions from servers you don't control.
- Giving a server a token with broad scopes "to make setup easy".
- Passing a client's token through to a downstream API.
- Logging full tool arguments or results.
- Believing the wrapper tags make injected text harmless.
Security notes
None of this removes the risk; it limits the damage. Assume some tool result will eventually contain hostile text, then ask what the agent could do if it obeyed. If the answer is "something expensive or irreversible", add a person, or take the tool away.
Cost and speed
Guards add microseconds. The costs that matter are the ones they prevent: a rate limit stops a looping agent from hammering a paid API, and a size limit keeps a giant result out of every following request.
Key takeaways
- Risk lives in the server's code, its text and your credentials.
- Write the policy yourself: allow list, argument limits, rate limits and an audit log.
- Mark tool results as data, but rely on least privilege and approvals for safety.
- Check server URLs for private addresses and require HTTPS; authenticate remote servers.
- Never pass tokens through; keep scopes minimal.
Lesson recap: assume some result will be hostile and limit what the agent could do about it.
Quick quiz
- Why is a tool result a possible injection route?
- What is token passthrough, and why is it forbidden?
- Why does
check_server_url check every resolved address?
- Why doesn't the audit log record arguments?
- Does wrapping a result in tags make hostile text safe?
Answers and explanations
- The text goes into the model's context, and whoever controls it, including a third-party site the server fetched, can write instructions in it.
- A server accepts a token not issued for it and forwards it downstream. It bypasses controls and breaks audit trails, so the guidance forbids accepting tokens not issued for the server.
- A host can resolve to several addresses, and one private address is enough to reach an internal service.
- Arguments may contain customer data, and the log would become another place it can leak.
- No. It reduces confusion about what's data, but persuasive text can still influence the model. Least privilege and human approval are what limit harm.
Official references and further reading
Related tutorials