Authenticating a remote MCP server with OAuth 2.1
Skill packs and prompts are provided in English so they work best with the AI tools. Use them as-is.
Authenticating a remote MCP server with OAuth 2.1
Read this before the video (optional, partly obsolete). The embedded video (YouTube gl6U8s3zStI) is optional. It still gets one important thing right: the server validates the token's issuer, audience and scopes. Two parts are out of date. First, the client gets its ID through Dynamic Client Registration. That is deprecated as of revision 2026-07-28; new work should use Client ID Metadata Documents or pre-registration, both explained below. Second, it uses one vendor's hosted service. That is one option among many, not something MCP requires. This written lesson is the authoritative path. Where the two disagree, follow the lesson.
Where you are
You can build a Streamable HTTP server that checks Origin and binds to loopback (L07, L11). Once it is reachable over a network, you need to know who is calling. This lesson covers the current protocol (2026-07-28 Authorization), using a lab you run on your own machine.
What you will be able to do
- Explain the roles: the MCP server is an OAuth 2.1 resource server, the client is an OAuth 2.1 client, and the authorization server issues the tokens.
- Trace the flow: 401, metadata discovery, PKCE with
resource, a token, then the request. - Validate a token properly (signature, issuer, audience, expiry, scope) and refuse token passthrough.
- Use the negative tests to explain why each check exists.
- Say what changes between the local lab and a real deployment, and what CIMD is.
First: when does this apply?
Authorization is OPTIONAL in MCP. Servers using an HTTP transport SHOULD follow the authorization spec. Servers using stdio SHOULD NOT; they read credentials from the environment. So this lesson is about remote (HTTP) servers that need to know who is calling.
The flow, step by step
- The client calls the server without a token. The server answers 401 with
WWW-Authenticate: Bearer ... resource_metadata="<url>". - The client fetches that Protected Resource Metadata document (RFC 9728). MCP servers MUST publish it. It names the resource (this server's canonical URI) and its authorization server(s).
- The client reads the authorization server's metadata (RFC 8414 or OpenID Connect discovery). It records the
issuer. Ifcode_challenge_methods_supportedis missing, the client MUST refuse to continue. - The client needs a client ID. In priority order: pre-registered credentials; then Client ID Metadata Documents (CIMD), if the server advertises
client_id_metadata_document_supported; then Dynamic Client Registration as a deprecated fallback; and last, asking the user. - The client sends the user's browser to
/authorizewith a PKCE challenge (S256whenever it can) and theresourceparameter (RFC 8707). When the response comes back, the client checksstateand checksissagainst the issuer it recorded (RFC 9207). This defends against mix-up attacks. - The client exchanges the code at
/token, sending thecode_verifierandresourceagain. The spec saysresourceMUST be in both the authorization request and the token request. - The client calls the MCP server with
Authorization: Bearer <token>on every request, and never in the query string.
What the server must do with a token
The server validates every token, and in particular checks that it was issued for this server as the audience. Invalid or expired tokens get 401. A token with too little scope SHOULD get 403 with error="insufficient_scope"; the client can then ask for more scope (step-up). The spec also says: "MCP servers MUST NOT accept or transit any other tokens." If your tool calls another API, it uses its own credential for that API. It never forwards the client's token. Tokens need not be JWTs (opaque tokens with introspection are allowed); the lab uses JWTs.
Worked example: the lab's resource server
The lab uses the official Python SDK, pinned to mcp==2.3.0. Its server configures the SDK like this (copied from protected_server.py):
auth = AuthSettings(
issuer_url=ISSUER,
resource_server_url=RESOURCE_URL,
required_scopes=["notes:read"],
validate_token_resource=True, # default in 2.3.0 is None (warn only): turn it on explicitly
)
resource_server_url makes the SDK publish the RFC 9728 document at /.well-known/oauth-protected-resource/mcp and send the 401 with resource_metadata. SDK caveat: in mcp 2.3.0, validate_token_resource defaults to None, which only logs a warning and behaves as False. Leave it unset and the SDK's audience gate is off. Turn it on.
The lab does not rely on that setting alone. Its TokenVerifier checks the token itself:
claims = jwt.decode(
token,
key=key,
algorithms=["RS256"], # never accept "none" or HS* here
audience=self.audience, # RFC 8707 / spec: accept only tokens issued for this server
issuer=self.issuer,
options={"require": ["iss", "aud", "exp", "iat", "sub"]},
)
The add_note tool also needs notes:write. It checks that inside the tool with get_access_token(), so a read-only token gets back a tool result with isError, not an HTTP 403. That is an application-level check. The spec's 403 step-up challenge is something the SDK applies per endpoint (required_scopes).
The tool that calls the upstream API sends the server's own credential:
# NO TOKEN PASSTHROUGH: the upstream gets the server's own credential, never the client's token.
headers = {"Authorization": f"Bearer {UPSTREAM_SERVICE_TOKEN}"}
SDK gap on the authorization-server side: in mcp 2.3.0, the SDK's /token handler parses resource but does not pass it to the provider. The lab's test authorization server wraps that handler (TokenResourceCheck). The wrapper requires resource and requires it to match the value sent to /authorize. If you build on these handlers, add the same check.
Why the lab pre-registers its client (and what CIMD is)
With CIMD, the client_id is itself an HTTPS URL with a path, such as https://app.example.com/oauth/client-metadata.json. The authorization server fetches the JSON document at that URL, checks that its client_id matches the URL exactly, and checks the redirect_uris it lists. Client and server need no prior relationship and no registration call. The spec says clients and authorization servers SHOULD support CIMD.
The lab runs only on loopback and cannot host a public HTTPS document, so it uses the spec's first priority: a pre-registered client, with DCR off. The SDK client has a CIMD option, but the lab does not test it: you understand CIMD here, you have not run it.
Practice
Download the Lab files (ZIP) for L13 and open its folder. You need uv. Then run:
./run.sh verify
It installs the locked dependencies, starts a test-only authorization server (port 9000), the MCP server (8000) and a synthetic upstream API (8002), then runs 49 checks. To explore by hand, run ./run.sh serve and, in another terminal:
curl -i -X POST http://127.0.0.1:8000/mcp -H 'content-type: application/json' -d '{}'
curl http://127.0.0.1:8000/.well-known/oauth-protected-resource/mcp
Check your result
- The run ends with
ALL CHECKS PASSED (49). - Line A1 shows
HTTP 401withresource_metadata="http://127.0.0.1:8000/.well-known/oauth-protected-resource/mcp". - Line A5 shows
aud=http://127.0.0.1:8000/mcp, and A7 showsPASS A7 upstream NEVER received the client's token (no passthrough). - In section B, the SDK's own client requested
code_challenge_method=S256andresource=http://127.0.0.1:8000/mcp, andadd_notecame backis_error=Truebecause it held onlynotes:read. - Read section C as a list of attacks the server refused. A token for another audience gets 401 (C1). A missing scope gets 403
insufficient_scope(C2). The authorization server rejects no PKCE,plain, a wrong or missing verifier, a reused code, and a missing, unknown or mismatchedresource(C4, C5). Expired, forged, wrong-issuer andalg=nonetokens get 401 (C6, C7). A token in the query string is refused (C8). The SDK's warn-only default is detected (C9). A foreignOrigingets 403 even with a valid token (C10).
Try breaking it (in a copy of the lab): set validate_token_resource=False, remove audience= from jwt.decode and add "verify_aud": False to its options, then run again. The verifier stops at C1: your server now accepts a token issued for a different service. (If you only remove audience=, PyJWT rejects every token that carries an audience, including valid ones, so the first tool call fails instead. Tested on 26 November 2026.)
Local practice versus a real deployment
| In the lab (test-only) | In a real deployment |
|---|---|
| Plain HTTP on 127.0.0.1 | TLS everywhere. Authorization server endpoints MUST be HTTPS, and redirect URIs MUST be localhost or HTTPS |
Automatic consent for learner-001, no login | A real authorization server with user login, a consent screen and exact redirect_uri matching |
| Ephemeral signing key | Managed keys with rotation, published through JWKS |
| Pre-registered client in code | CIMD or pre-registration; avoid DCR |
resource_server_url is a loopback URL | The public HTTPS URL, with Origin/Host allow-lists for that hostname |
Never deploy test_auth_server.py. Keep tokens short-lived and never log them.
Check your understanding
-
Your server sets
resource_server_urlbut notvalidate_token_resource, and its verifier checks only signature and expiry. What goes wrong? In mcp 2.3.0 the audience gate then only warns, so a valid token issued for another service is accepted. The spec requires the server to accept only tokens issued for itself. Setvalidate_token_resource=True, checkaudin the verifier, or both. -
A tool needs to call a third-party API on the user's behalf. Can it forward the bearer token it received? No. That is token passthrough, and it is forbidden ("MUST NOT accept or transit any other tokens"). The server uses a separate credential issued for the upstream API, such as its own service credential or a token obtained for that API.
-
Why does the lab use a pre-registered client instead of CIMD, and why not DCR? A CIMD
client_idmust be an HTTPS URL that the authorization server can fetch, and a loopback-only lab cannot host one. Pre-registration comes first in the spec's priority order anyway. DCR is deprecated in 2026-07-28 and is kept only for backwards compatibility.
Sources
- https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization
- https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration
- https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/security-considerations
- https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices
- https://github.com/modelcontextprotocol/python-sdk
