Skip to content
Index Ai Academy
Phase 9 · Production MCP

Securing remote servers with OAuth

Protected resource metadata, PKCE, audiences and scope challenges.

About 45 minutes · Versions and API rules checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers8

First principles

Why can a valid token still fail to authorize a request?

A server must establish which resource the token was intended for, whether it is still valid, and what actions it covers. Identity and permission answer separate questions about the same request.

  1. Starting point

    Client supplies an access token

  2. What changes

    Server verifies expiry, audience and required scope

  3. Result

    Server accepts the matching request or returns an authorization error

Compare all three steps
  1. Starting point

    Client supplies an access token

  2. What changes

    Server verifies expiry, audience and required scope

  3. Result

    Server accepts the matching request or returns an authorization error

Complete and reverse the trace

Given Client supplies an access token and Server accepts the matching request or returns an authorization error, write down the missing step that connects them.

Compare with the worked step

Server verifies expiry, audience and required scope

Now take Server verifies expiry, audience and required scope and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Client supplies an access token. Check that your implementation produces the result shown above.

Try it on a new case

A current token names the correct audience and includes reports:read. What should happen when the client asks to create a note requiring notes:write?

Show worked reasoning

The write is forbidden because the verified token lacks notes:write. The same token can still support a read allowed by policy.

Try a different case

An analyst can create a note, but the campaign is outside their assigned project. The tool arguments are valid and the user confirmed the action. What is the remaining decision?

Show reasoning for this case

Check authorization for the particular resource. A correctly shaped and confirmed operation still requires the caller to have permission on that campaign.

Run, change, and build

Check this when debugging. Running OAuth for local stdio servers (use environment credentials).

Trace the cause · MCP message and permission
  1. Mark which message crosses the client–server boundary and which check determines what the caller may do.
  2. Change the tool input or approved scope. Compare the returned message and stored state to distinguish a denial from an allowed change.
  3. Try the same reasoning on this case. A current token names the correct audience and includes reports:read. What should happen when the client asks to create a note requiring notes:write?

Why it matters

A remote MCP server usually acts for a person: it reads their CRM, their calendar, their files. It must know who that person is, and what they agreed to let this app do, without the app ever seeing their password. MCP uses OAuth for this, with a few extra rules that close real attacks. When an AI app says "connect your account" and a browser window opens, this is the flow behind it.

What you'll be able to do

  • Walk through MCP's authorization flow, from the first 401 to the first successful call
  • Explain protected resource metadata, client registration, PKCE and the resource parameter
  • Validate access tokens on the server: expiry, audience and scopes, with the right 401 and 403 answers
  • Explain why token passthrough is forbidden, and what to do instead
Quick check
A remote MCP server reads a person's calendar. How should it get permission?
  1. By using one shared admin key for every single user
  2. Through OAuth: the person approves, and the app gets a token
  3. By asking the person to type in their calendar password
  4. By reading the calendar without asking anyone first
Show the answer

Through OAuth: the person approves, and the app gets a token

OAuth lets the person approve exactly what the app may do and gives the app a token, not their password. The token can be limited, checked and revoked.

The idea: three roles and one token

This rests on Authentication and authorization, where a login produced a token with an expiry and an audience, and PKCE kept a stolen code useless. MCP asks the same of a remote server, and adds rules that close real attacks.

Who's who

Think of the hotel again. The front desk checks who you are and issues a key card. The room door only checks the card. You carry the card from one to the other. OAuth has the same three roles, and MCP maps onto them:

  • The MCP server is the resource server, the door: it holds the user's data and checks tokens.
  • The authorization server is the front desk. It logs the user in, asks for consent and issues tokens. It's often a separate service, such as the company's identity provider.
  • The MCP client (inside the host) is the OAuth client, the guest: it gets a token and sends it.

Local stdio servers don't use any of this. They get credentials from environment variables.

Quick check
In OAuth for MCP, which role logs the user in and issues tokens?
  1. The MCP server
  2. The authorization server
  3. The MCP client
Show the answer

The authorization server

The authorization server is the front desk: it checks who you are and issues the token. The MCP server only checks tokens, and the MCP client only carries them.

The flow, step by step

1. The first request is refused. The client calls the server with no token. The server answers 401 with a header pointing at its protected resource metadata, a document that says how to get in:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer scope="orders:read",
  resource_metadata="https://shop.example/.well-known/oauth-protected-resource/mcp"

2. Discovery. That metadata document (defined in RFC 9728) says which authorization servers this resource trusts:

{"resource": "https://shop.example/mcp",
 "authorization_servers": ["https://auth.shop.example"],
 "scopes_supported": ["orders:read", "orders:write"]}

The client then fetches the authorization server's own metadata from a well-known address (/.well-known/oauth-authorization-server or /.well-known/openid-configuration). That gives the login and token endpoints and the features it supports.

3. Client registration. The authorization server needs to know which app is asking. The preferred way in the 2026-07-28 revision is a Client ID Metadata Document: the client's id is an HTTPS URL, and at that URL sits a JSON document with the app's name and allowed redirect addresses. Pre-registered ids also work. Dynamic Client Registration, which was common earlier, is now deprecated.

Quick check
In the 2026-07-28 revision, what is the preferred way for a client to identify itself?
  1. A Client ID Metadata Document at an HTTPS URL
  2. The email address of the user
  3. A password shared by every client
  4. Dynamic Client Registration, as before
Show the answer

A Client ID Metadata Document at an HTTPS URL

The client's id is a URL, and the document at that URL gives the app's name and allowed redirect addresses.

4. Login with PKCE. The client opens the browser at the authorization endpoint with a PKCE code challenge, the resource parameter and the scopes it needs. The user logs in and approves.

5. The code comes back. The browser is redirected to the client with a short-lived code and an iss value. The client checks that iss names the authorization server it started with (RFC 9207). That defeats attacks that mix up two authorization servers.

6. Token exchange. The client swaps the code for an access token, sending the PKCE verifier and the resource again. Then every MCP request carries Authorization: Bearer <token>, never a token in the URL.

Try it now

Every URL, header and body of the flow. The token is the thing that moves; step to the last request and try the replay.

Quick check
How does an MCP client learn which authorization server to use for a remote MCP server?
  1. From the server's protected resource metadata, linked in the 401's WWW-Authenticate header (or a well-known URL)
  2. It's hard-coded into every MCP client, since there's one authorization server for all MCP servers
  3. From the server's tools/list, which names the authorization server for each tool
  4. The user types its address in when they first add the server to their client
Show the answer

From the server's protected resource metadata, linked in the 401's WWW-Authenticate header (or a well-known URL)

RFC 9728 metadata names the authorization servers the resource trusts. Clients must support both the header link and the well-known fallback.

In your own words
Who are the roles in MCP's OAuth flow, and how does a client find the authorization server?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: tokens, audiences and passthrough

This part recalls PKCE, then issues a token and checks it the way a server must, and ends on the proxy form of the confused deputy.

PKCE, recalled

Authentication and authorization taught PKCE; here is the same computation as MCP requires it. PKCE (proof key for code exchange, said "pixy") stops a stolen authorization code from being used. Picture tearing a raffle ticket in two: you hand in one half now, and only the person holding the other half can collect the prize. Before step 4, the client makes a random secret, the code verifier: 43 to 128 characters of letters, digits and -._~. It sends only its hash, the code challenge, in step 4:

import base64, hashlib, secrets

def challenge(verifier):
    digest = hashlib.sha256(verifier.encode("ascii")).digest()
    return base64.urlsafe_b64encode(digest).decode().rstrip("=")

# The worked example from the PKCE standard, RFC 7636:
print(challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"))

verifier = secrets.token_urlsafe(32)          # 43 characters from the allowed set
print(len(verifier), challenge(verifier))
It runs right here in your browser, with nothing to install.

The first line should print E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, the published answer. In step 6 the client sends the verifier itself, and the authorization server checks that its hash matches the challenge. Someone who intercepted the code in step 5 never saw the verifier, so the code is useless to them. MCP requires the S256 method shown here.

Quick check
What does this print?
import hashlib, base64
verifier = "abc"
challenge = base64.urlsafe_b64encode(
    hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")
print(challenge == verifier)
  1. None
  2. False
  3. True
  4. abc
Show the answer

False

The challenge is a long hash of the verifier, so it can't equal "abc", and == gives False. A thief who sees the challenge can't work backward to the verifier.

The resource parameter: tokens for one server

A key card coded for one hotel won't open a room in another, even if both belong to the same chain. The client must send resource=https://shop.example/mcp (the server's canonical URI) in both the authorization and token requests. The authorization server then puts that server in the token's audience (the aud claim). A token for the shop's MCP server won't work at the calendar's MCP server, even if both trust the same authorization server.

Drill

Was this token meant for us?

A token's aud claim names the server it was issued for, as a string or a list. Write audience_ok(aud, server_url): True if server_url is the audience or one of them, ignoring a trailing / on either side.

def audience_ok(aud, server_url):
    return True


print(audience_ok("https://mcp.shop.test/", "https://mcp.shop.test"),
      audience_ok("https://billing.shop.test", "https://mcp.shop.test"))
In the lesson, your code is checked as you write it.
Quick check
An attacker intercepts the authorization code on its way back to the client. Why can't they use it?
  1. Codes can only be used from the IP address that first requested them
  2. Exchanging it needs the PKCE code verifier, which never left the client
  3. The code is encrypted, and only the client holds the key to read it
  4. The attacker doesn't know the user's password, which the exchange needs
Show the answer

Exchanging it needs the PKCE code verifier, which never left the client

Only the hash went out with the login request. The token endpoint wants the original secret.

Checking tokens on the server

On every request, the MCP server validates the token, as you did with JWTs in Phase 8. A door guard asks the same four things about a pass: is it real, is it in date, is it for this building, and does it open this floor?

  • It must be genuine (a valid signature, or confirmed by asking the authorization server).
  • It must not be expired.
  • Its audience must be this server. The spec is firm: servers must accept only tokens issued for them.
  • It must carry the scopes the operation needs.

Failures have specific answers:

problemanswer
no token, bad token, expired token, wrong audience401, with WWW-Authenticate: Bearer ... including resource_metadata (and error="invalid_token" for a bad one)
valid token without the needed scope403, with WWW-Authenticate: Bearer error="insufficient_scope", scope="orders:write", resource_metadata="..."

The 403 lists the scopes needed, so the client can ask the user to approve more and retry. That's called step-up authorization.

Quick check
From the lesson on authentication: after the signature, check that a token hasn't expired and that it was issued for you. What does this print for three tokens that arrive at an MCP server?
def accept(claims, now, my_audience):
    return claims["exp"] > now and claims["aud"] == my_audience

now, me = 1_793_000_000, "https://mcp.shop.test"
print(accept({"exp": now + 600, "aud": me}, now, me),
      accept({"exp": now - 60, "aud": me}, now, me),
      accept({"exp": now + 600, "aud": "https://billing.shop.test"}, now, me))
  1. True True False
  2. True False False
  3. False False False
  4. True False True
Show the answer

True False False

The first token is in date and meant for this server. The second expired a minute ago. The third is perfectly valid, and it was issued for a different service, so this server must refuse it. The resource parameter in this lesson is how a client asks for a token that names one MCP server as its audience.

Worked example

Issue a token, check it, replay it

An authorization server signs a token; two MCP servers check it. A token can be genuine and still be wrong for this request. The checks run in order, and each failure gets its own answer.

import base64, hashlib, hmac, json

KEY = b"practice-auth-server-key"   # real servers use its public key


class AuthServer:
    def issue(self, user, resource, scope, exp):
        claims = {"sub": user, "aud": resource, "scope": scope, "exp": exp}
        body = base64.urlsafe_b64encode(json.dumps(claims).encode()).decode()
        return body + "." + hmac.new(KEY, body.encode(), hashlib.sha256).hexdigest()


class McpServer:
    def __init__(self, url):
        self.url = url

    def check(self, token, needed, now):
        body, _, sig = token.partition(".")
        good = hmac.new(KEY, body.encode(), hashlib.sha256).hexdigest()
        if not hmac.compare_digest(sig, good):
            return 401, "invalid token"
        claims = json.loads(base64.urlsafe_b64decode(body))
        if claims["exp"] <= now:
            return 401, "expired"
        if claims["aud"] != self.url:
            return 401, "wrong audience"
        if needed not in claims["scope"].split():
            return 403, f"needs scope {needed}"
        return 200, "ok"


auth = AuthServer()
shop = McpServer("https://shop.example/mcp")
calendar = McpServer("https://calendar.example/mcp")
token = auth.issue("ada", shop.url, "orders:read", exp=2000)
print(shop.check(token, "orders:read", now=1000))
print(shop.check(token, "orders:write", now=1000))
print(shop.check(token, "orders:read", now=3000))
print(calendar.check(token, "orders:read", now=1000))
forged = token[:-1] + ("0" if token[-1] != "0" else "1")
print(shop.check(forged, "orders:read", now=1000))
In the lesson you can change this and run it.

The replay at the calendar server fails on the audience, though the token is real and unexpired. A missing scope gets 403, not 401, because the caller is known but not allowed. A token with one changed character fails the signature before anything else is read.

No token passthrough

Your MCP server may call other APIs for the user, such as the shop's order system. It's tempting to forward the token the client sent. Don't. The spec forbids it, for two reasons.

Your server would then accept tokens meant for someone else, which skips the audience check. And downstream systems would see a request that seems to come straight from the client, with your server's checks bypassed. That's a confused deputy: a trusted helper tricked into using its authority for someone else.

Your server should get its own token for the downstream API, through a separate grant, and keep each token to the audience it was issued for.

In plain words: a token opens one door. If your server needs another door, it gets its own token for it.

Drill

Headers for the upstream call

An MCP server must never forward the user's token to the API behind it; it calls upstream with its own credentials. Write upstream_headers(incoming, upstream_token): copy only accept and user-agent from the incoming headers (lowercase names) if present, and set authorization to Bearer plus the server's own upstream_token.

def upstream_headers(incoming, upstream_token):
    return dict(incoming)


incoming = {"authorization": "Bearer user-token-123", "accept": "application/json",
            "cookie": "session=abc"}
print(upstream_headers(incoming, "srv-token-9"))
In the lesson, your code is checked as you write it.
Quick check
Why must an MCP server never forward the user's token to the upstream API it calls?
  1. Tokens expire too quickly to be reused for a second request to another service
  2. Forwarding the token is slower than asking the upstream API for a new token of its own
  3. The token was issued for the MCP server; passing it on breaks audience checks and creates a confused deputy
  4. Upstream APIs reject long headers, and a user's token is usually too long for them to accept
Show the answer

The token was issued for the MCP server; passing it on breaks audience checks and creates a confused deputy

Each service should get its own token for its own audience. That's why MCP forbids token passthrough.

The proxy form of the confused deputy

Passthrough is one confused deputy. A second shows up in MCP proxy servers: an MCP server that sits in front of a third-party service (a code host, say) and uses one static client id with that service's authorization server. Clients register with the proxy dynamically, and the third-party server remembers that this user already consented to the static id, so it skips the consent screen.

Now an attacker registers their own client with the proxy, using a redirect address they control, and sends the victim a link. The victim's browser still holds the earlier consent, so no consent screen appears, and the authorization code goes to the attacker. The proxy was the deputy: it let the attacker borrow a consent the user gave to something else.

The spec's rule is that a proxy using a static client id must get the user's consent for each client it registers dynamically, before it forwards the request to the third-party server. The consent page is the proxy's own, it names the client and its redirect address, and its cookie is bound to that one client.

Quick check
An MCP proxy uses one static client id at a third-party authorization server. A new client registers with the proxy. What must the proxy do before forwarding the login?
  1. Forward the user's existing token to the new client
  2. Nothing: the third-party server already remembers the user's consent
  3. Ask the user to consent to that specific client and its redirect address
  4. Reject every dynamically registered client for good
Show the answer

Ask the user to consent to that specific client and its redirect address

The third-party server's remembered consent belongs to the static id, not to the new client. The proxy must ask again, for this client and this redirect address.

Worked example

The whole flow against the practice server

/mcp-secure is the practice shop's server behind OAuth, with a practice authorization server beside it. It plays the person who logs in and says yes, and hands back the redirect as JSON where a real one would send the browser. Everything else is the real exchange.

import base64
import hashlib
import re
from urllib.parse import parse_qs, urlsplit

import requests

HOST = "https://api.gradient.test"
V = "2026-07-28"

def mcp(path, method, params=None, token=None):
    meta = {"io.modelcontextprotocol/protocolVersion": V,
            "io.modelcontextprotocol/clientCapabilities": {}}
    headers = {"MCP-Protocol-Version": V, "Mcp-Method": method}
    if method == "tools/call":
        headers["Mcp-Name"] = params["name"]
    if token:
        headers["Authorization"] = f"Bearer {token}"
    msg = {"jsonrpc": "2.0", "id": 1, "method": method,
           "params": {**(params or {}), "_meta": meta}}
    return requests.post(HOST + path, json=msg, headers=headers, timeout=10)

# 1. No token: 401, and the header says where the metadata is.
refused = mcp("/mcp-secure", "tools/list")
challenge_header = refused.headers["WWW-Authenticate"]
link = re.search(r'resource_metadata="([^"]+)"', challenge_header).group(1)
print(refused.status_code, link[len(HOST):])

# 2. Discovery: the resource's metadata, then the authorization server's.
resource = requests.get(link, timeout=10).json()
issuer = resource["authorization_servers"][0]
well_known = HOST + "/.well-known/oauth-authorization-server/oauth"
auth = requests.get(well_known, timeout=10).json()
print(resource["resource"][len(HOST):], "trusts", issuer[len(HOST):])

# 3. Authorize with PKCE: send the hash now, keep the verifier for later.
verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
digest = hashlib.sha256(verifier.encode()).digest()
challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
client = {"client_id": "https://app.example/client.json",
          "redirect_uri": "http://localhost:8765/callback"}
approved = requests.get(auth["authorization_endpoint"], params={
    **client, "response_type": "code", "code_challenge": challenge,
    "code_challenge_method": "S256", "resource": resource["resource"],
    "scope": "campaigns:read", "state": "s1"}, timeout=10).json()
back = parse_qs(urlsplit(approved["redirect_to"]).query)
print("state ok:", back["state"] == ["s1"], "| iss ok:", back["iss"] == [issuer])

# 4. Swap the code for a token: the verifier, and the resource again.
token = requests.post(auth["token_endpoint"], data={
    **client, "grant_type": "authorization_code", "code": back["code"][0],
    "code_verifier": verifier, "resource": resource["resource"]}, timeout=10).json()
print(token["token_type"], token["expires_in"], token["scope"])

# 5. The token opens this server, for what its scope allows, and no other.
access = token["access_token"]
pause = {"name": "pause_campaign", "arguments": {"id": "cmp_101"}}
print(mcp("/mcp-secure", "tools/list", token=access).status_code,
      mcp("/mcp-secure", "tools/call", pause, token=access).status_code,
      mcp("/mcp-secure-b", "tools/list", token=access).status_code)
In the lesson you can change this and run it.

The last line prints 200 403 401. The token lists the shop's tools. pause_campaign is 403 because the token's scope is campaigns:read and that tool needs campaigns:write: the 403's WWW-Authenticate header names the scopes to ask for, and the client starts the flow again for a wider token. And the same token replayed at /mcp-secure-b is 401, because its audience is the shop's server. Try the token endpoint with a different code_verifier: it answers invalid_grant, which is what stops someone who stole the code from the redirect.

In your own words
What must a server check on a token, and why no passthrough?

Write a sentence or two, then compare it with a good answer in the lesson.

In the SDK and a real host: the verifier hook and the identity provider

Purpose. See where your McpServer.check lives in the official SDK, and what you configure at the identity provider instead of writing.

In the Python SDK you don't write the 401 and 403 answers. You supply a token verifier, a class with one method that turns a token string into the token's claims or None, and settings that say who the authorization server is and which server this is.

At the identity provider (Okta, Auth0, Keycloak and the like) you set three things: the audience of the tokens it issues to this client, the scopes it may grant, and the redirect addresses it allows. A wrong audience setting is the most common cause of a server that returns 401 for a perfectly good login.

In an engineer's week. At a security review you are asked three questions: what is in the token's audience, which scopes does each tool need, and what does the server do with the token after the check. The answers should be one URL, a short list, and "nothing: it gets its own token for the billing API". What goes wrong is a server that logs the whole Authorization header, which puts live tokens in the logs.

Goes deeper in

In your own words
A user logs in fine but every call returns 401. What do you check first at the identity provider?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 3 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

In MCP's use of OAuth, what role does the MCP server play?

  1. The resource server, which checks tokens
  2. The authorization server, which logs users in
  3. The OAuth client
  4. None; MCP servers don't use OAuth

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 9 · about 13 hours of study

Model Context Protocol

Build MCP servers, clients and hosts, from the wire format to production 17 lessons 1 free
  1. JSON-RPC 2.0 in depth FreeRequests, notifications, errors and a dispatcher built from scratch.35 min
  2. Versions and stateless requestsRevisions by date, the legacy handshake, per-request _meta and version negotiation.30 min
  3. Discovery, capabilities and the two erasserver/discover, declared capabilities, and talking to legacy and modern software alike.30 min
  4. Transports I: stdioNewline-delimited JSON over a subprocess's standard streams.30 min
  5. Transports II: Streamable HTTPOne endpoint, required headers, JSON or event-stream replies.40 min
  6. Build a server: toolsTool definitions, schemas from type hints, results and two kinds of error.45 min
  7. Resources and promptsReadable data, URI templates and reusable prompt templates.40 min
  8. The same server with the official SDKsYour registry and dispatcher on the SDK's decorator shape, in Python and TypeScript.40 min
  9. Build a clientMetadata on every request, version fallback, paging and caching.40 min
  10. Hosts: connecting servers to a modelMany servers, one agent: namespacing, routing and approvals.40 min
  11. Progress, subscriptions and multi-round-trip requestsLong-running work, change notifications and asking the user mid-call.45 min
  12. Securing remote servers with OAuthProtected resource metadata, PKCE, audiences and scope challenges.45 min
  13. MCP securityTool poisoning, rug pulls, confused deputies and local-server risks.40 min
  14. Lab: attack and defend a hostPoisoned tools, injected results, token replay and the defenses that stop each.40 min
  15. Testing, designing and shipping serversConformance checks, tool design for models, SDKs and deployment.40 min
  16. MCP in production: gateways, limits and auditAn allowlist, per-user rate limits, header checks and an audit log in front of many servers.35 min
  17. Capstone: a production MCP serverA complete, tested server for the practice shop.45 min
Part of a free course 15 lessons

Build and Deploy MCP Integrations

Build a Model Context Protocol client and server, then verify the integration with a compatible host.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write