Build and Deploy MCP Integrations
Build a Model Context Protocol client and server, then verify the integration with a compatible host.
Protected resource metadata, PKCE, audiences and scope challenges.
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.
Client supplies an access token
Server verifies expiry, audience and required scope
Server accepts the matching request or returns an authorization error
Client supplies an access token
Server verifies expiry, audience and required scope
Server accepts the matching request or returns an authorization error
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.
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.
Client supplies an access token. Check that your implementation produces the result shown above.
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?
The write is forbidden because the verified token lacks notes:write. The same token can still support a read allowed by policy.
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?
Check authorization for the particular resource. A correctly shaped and confirmed operation still requires the caller to have permission on that campaign.
Check this when debugging. Running OAuth for local stdio servers (use environment credentials).
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.
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.
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.
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:
Local stdio servers don't use any of this. They get credentials from environment variables.
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.
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.
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.
Every URL, header and body of the flow. The token is the thing that moves; step to the last request and try the replay.
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.
Write a sentence or two, then compare it with a good answer in the lesson.
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.
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))
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.
import hashlib, base64 verifier = "abc" challenge = base64.urlsafe_b64encode( hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=") print(challenge == verifier)
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.
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.
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"))
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.
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?
Failures have specific answers:
| problem | answer |
|---|---|
| no token, bad token, expired token, wrong audience | 401, with WWW-Authenticate: Bearer ... including resource_metadata (and error="invalid_token" for a bad one) |
| valid token without the needed scope | 403, 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.
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))
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.
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))
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.
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.
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"))
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.
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.
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.
/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)
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.
Write a sentence or two, then compare it with a good answer in the lesson.
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.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
In MCP's use of OAuth, what role does the MCP server play?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
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