Over stdio, the person who starts Helpline is the only caller. Over Streamable HTTP, anyone who can reach the URL can send a request. This lesson makes Helpline an OAuth resource server: it accepts only tokens issued for it, by an issuer it trusts, with the scope each tool needs, and it never passes a caller's token on. It closes the token passthrough row of Lesson 1's checklist, and the confused-deputy row too: scopes limit what a caller may do, and a customers claim limits whose tickets it may do it to.
By the end of this lesson you will be able to:
- serve Helpline over Streamable HTTP and get a 401 that tells an MCP client where to find Helpline's protected resource metadata
- mint test tokens with a local test issuer, and say what it stands in for
- validate every token's signature, issuer, audience and expiry, and prove the bad cases are refused
- explain how audience binding stops a token minted for another service from working here
- require
tickets:readfor every request andtickets:escalateforescalate_ticket, with a 403 that names the missing scope - call the downstream ticketing API with Helpline's own credential, and prove the caller's token never reaches it
- trace one
escalate_ticketcall through these checks against the confused-deputy risk
Before you start. You need Lessons 1 to 3, and some familiarity with OAuth bearer tokens and JWTs. The companion folder is Lesson 3's code plus four new files in helpline/ (issuer.py, auth.py, backend.py, and an http_app function in server.py), a new HTTP main.py, issue_token.py, and two test files. It has 49 tests. Every listing and output below comes from that folder, run against mcp 2.3.0 and PyJWT on 2026-11-21.
1. Helpline's role in OAuth
OAuth has more roles than this lesson builds. The authorization server authenticates the user and issues access tokens. The MCP client, inside a host such as Claude Code, gets a token and sends it as Authorization: Bearer ... on every request. Helpline is the resource server: it receives the token and decides whether to honour the request. Helpline never sees a password and never issues tokens; this series doesn't run an authorization server.
An MCP client needs to find out where to get a token. Helpline tells it through protected resource metadata (RFC 9728), a small JSON document at a well-known path derived from Helpline's URL. For a server at http://127.0.0.1:8000/mcp it lives at /.well-known/oauth-protected-resource/mcp.
2. Audience binding: why a token minted for another service is useless here
Every JWT access token carries an aud (audience) claim naming the resource it was issued for (RFC 9068). When an MCP client asks the authorization server for a token, it can name Helpline's URL as the resource indicator (RFC 8707), and the server puts that into aud. The MCP spec requires a server to validate that a token was issued specifically for it as the intended audience.
Skipping that check is the first half of token passthrough. A token issued for, say, a billing service would be accepted by Helpline, so anyone holding any token from the same issuer gets in. The second half is forwarding the token downstream, which can make the downstream API trust it as if it came from Helpline. That is the confused deputy problem, and the spec forbids passthrough outright. Step 2 handles the first half, Step 5 the second.
3. Step 1: A local test issuer that signs tokens and nothing else
helpline/issuer.py holds an RSA key pair, publishes its public half as a JWKS (JSON Web Key Set), and mints tokens. It stands in for Auth0, Entra ID, Keycloak or Okta so the server's checks can run without one, and the server only ever sees its public keys:
TEST_ISSUER = "https://auth.helpline.test"
@dataclass
class TestIssuer:
__test__ = False # not a pytest test class
issuer: str = TEST_ISSUER
kid: str = field(default_factory=lambda: uuid.uuid4().hex[:8])
_key: rsa.RSAPrivateKey = field(
default_factory=lambda: rsa.generate_private_key(public_exponent=65537, key_size=2048)
)
def jwks(self) -> dict:
"""The public half, as the issuer would publish it at its jwks_uri."""
public = json.loads(RSAAlgorithm.to_jwk(self._key.public_key()))
return {"keys": [public | {"kid": self.kid, "use": "sig", "alg": "RS256"}]}
def mint(
self,
*,
subject: str = "agent-maria",
audience: str,
scopes: list[str],
client_id: str = "claude-code",
ttl_seconds: int = 300,
issuer: str | None = None,
**extra: object,
) -> str:
"""An RFC 9068-style JWT access token."""
now = int(time.time())
claims = {
"iss": issuer or self.issuer,
"sub": subject,
"aud": audience,
"client_id": client_id,
"scope": " ".join(scopes),
"iat": now,
"exp": now + ttl_seconds,
"jti": uuid.uuid4().hex,
} | extra
return jwt.encode(
claims, self._key, algorithm="RS256", headers={"kid": self.kid, "typ": "at+jwt"}
)mint() lets a test choose every claim, including a wrong audience, a foreign issuer or a past expiry. The class also has load_or_create(path), which keeps the dev key in .dev-issuer.pem so main.py and issue_token.py share it. Never commit that file; the folder's .gitignore lists it.
4. Step 2: A TokenVerifier that checks signature, issuer, audience and expiry
MCPServer calls a TokenVerifier on every HTTP request. The protocol has one method, verify_token, which returns an AccessToken or None. helpline/auth.py implements it with PyJWT:
class JwtTokenVerifier:
"""Verify RFC 9068 JWT access tokens against the issuer's published keys."""
def __init__(
self,
*,
issuer: str,
audience: str,
jwks: dict | None = None,
jwks_uri: str | None = None,
leeway_seconds: int = 30,
) -> None:
if (jwks is None) == (jwks_uri is None):
raise ValueError("pass exactly one of jwks or jwks_uri")
self.issuer = issuer
self.audience = audience
self.leeway = leeway_seconds
if jwks is not None:
keys = jwt.PyJWKSet.from_dict(jwks)
self._key_for: Callable[[str], object] = lambda token: _key_by_kid(keys, token)
else:
client = jwt.PyJWKClient(jwks_uri, cache_keys=True)
self._key_for = lambda token: client.get_signing_key_from_jwt(token).key
async def verify_token(self, token: str) -> AccessToken | None:
try:
claims = jwt.decode(
token,
self._key_for(token),
algorithms=["RS256", "ES256"], # never "none", never HS* with a public key
issuer=self.issuer,
audience=self.audience, # the token must be issued for this server
leeway=self.leeway,
options={"require": ["iss", "sub", "aud", "exp"]},
)
except (jwt.PyJWTError, KeyError) as exc:
log.info("rejected token: %s", exc) # the reason stays in our logs
return None
return AccessToken(
token=token,
client_id=str(claims.get("client_id") or claims.get("azp") or "unknown"),
scopes=str(claims.get("scope", "")).split(),
expires_at=int(claims["exp"]),
resource=self.audience,
subject=str(claims["sub"]),
)
def _key_by_kid(keys: jwt.PyJWKSet, token: str) -> object:
kid = jwt.get_unverified_header(token).get("kid")
return keys[kid].keyFour decisions are in that call. The algorithm list is fixed by the server; it never comes from the token's header, which is how "alg: none" and key-confusion attacks work. The key is chosen by kid from keys the issuer published, so a token signed by any other key fails the signature check. issuer and audience must match exactly. And exp is required, with 30 seconds of leeway for clock skew between the issuer and Helpline. The reason for a rejection goes to Helpline's log; the caller learns only that the token was refused. In production, jwks_uri points at the issuer's published key set, and PyJWKClient fetches and caches it.
5. Step 3: Put Helpline behind Streamable HTTP with AuthSettings
build_server() gains keyword arguments for auth. With a verifier it builds AuthSettings and passes both to MCPServer:
def build_server(
store: HelplineStore | None = None,
kb_delay_seconds: float = 0.05,
kb_timeout_seconds: float = KB_TIMEOUT_SECONDS,
*,
api: TicketingAPI | None = None,
token_verifier: TokenVerifier | None = None,
issuer_url: str | None = None,
resource_url: str | None = None,
) -> MCPServer:
"""Build the server.
Without a token verifier it is the stdio server of lesson 3. With one, every
HTTP request needs a valid bearer token for `resource_url` issued by `issuer_url`.
"""
store = store or HelplineStore()
api = api or TicketingAPI(store)
auth = None
if token_verifier is not None:
if not (issuer_url and resource_url):
raise ValueError("issuer_url and resource_url are required with a token verifier")
# Plain strings, not AnyHttpUrl(...): pydantic would add a trailing slash to
# "https://auth.helpline.test", and issuer comparison is exact.
auth = AuthSettings(
issuer_url=issuer_url,
resource_server_url=resource_url,
required_scopes=[READ_SCOPE],
validate_token_resource=True, # refuse tokens issued for another resource
)
server = MCPServer(
"helpline",
version="0.4.0",
token_verifier=token_verifier,
auth=auth,
# ... instructions as in Lesson 3
)
# ... resources and tools as in Lesson 3, then:
return serverThat's an excerpt: the elided lines are unchanged from Lesson 3.
required_scopes=[READ_SCOPE] makes tickets:read mandatory for every request. validate_token_resource=True makes the SDK refuse any token whose AccessToken.resource isn't resource_server_url. With this verifier it adds nothing, because JwtTokenVerifier has already checked aud and sets resource to that same configured audience. It's there as defence in depth: if someone later swaps in a verifier that forgets the audience check and fills resource from the token, the SDK still refuses tokens for other resources.
The comment about strings records a verified gotcha. Passing AnyHttpUrl("https://auth.helpline.test") instead makes pydantic normalise it to https://auth.helpline.test/, with a trailing slash, so the metadata advertises a different issuer from the iss in every token. Issuer identifiers are compared exactly, so an MCP client that checks them would reject the pair. AuthSettings keeps the exact form when given a plain string.
http_app() builds the HTTP app. stateless_http=True fits the 2026-07-28 protocol, which has no sessions, and json_response=True returns plain JSON instead of a stream:
def http_app(server: MCPServer, resource_url: str) -> Starlette:
"""The Streamable HTTP app, with per-tool scope checks in front of the MCP endpoint.
The SDK's app already serves the protected resource metadata and refuses
requests without a valid tickets:read token (401). ToolScopeMiddleware adds
the 403 insufficient_scope challenge for tools that need more.
"""
if server.settings.auth is None:
# Without a verifier every request would count as "no token", which the
# tools treat as stdio's trusted local caller. Never serve that over HTTP.
raise ValueError("http_app needs a server built with a token_verifier")
app = server.streamable_http_app(stateless_http=True, json_response=True)
metadata_url = str(build_resource_metadata_url(AnyHttpUrl(resource_url)))
for route in app.routes:
if isinstance(route, Route) and route.path == "/mcp":
route.app = ToolScopeMiddleware(route.app, metadata_url)
return appmain.py runs it with uvicorn. In production you set HELPLINE_ISSUER, HELPLINE_JWKS_URI and HELPLINE_RESOURCE_URL. Dev mode, which trusts the test issuer's key, must be asked for with HELPLINE_DEV=1. With neither, it refuses to start, because silently falling back to a key the server generated itself would be fail-open authentication:
def make_app():
if os.environ.get("HELPLINE_JWKS_URI"):
issuer = os.environ["HELPLINE_ISSUER"]
verifier = JwtTokenVerifier(
issuer=issuer, audience=RESOURCE_URL, jwks_uri=os.environ["HELPLINE_JWKS_URI"]
)
elif os.environ.get("HELPLINE_DEV") == "1":
dev = TestIssuer.load_or_create(HERE / ".dev-issuer.pem")
issuer = dev.issuer
verifier = JwtTokenVerifier(issuer=issuer, audience=RESOURCE_URL, jwks=dev.jwks())
else:
# Fail closed: never fall back to a key we generated ourselves.
raise SystemExit(
"Set HELPLINE_ISSUER and HELPLINE_JWKS_URI for a real authorization server, "
"or HELPLINE_DEV=1 to trust the local test issuer."
)
server = build_server(token_verifier=verifier, issuer_url=issuer, resource_url=RESOURCE_URL)
return http_app(server, RESOURCE_URL)PORT defaults to 8000 and RESOURCE_URL to http://127.0.0.1:{PORT}/mcp, both overridable through the environment:
HERE = Path(__file__).resolve().parent
PORT = int(os.environ.get("PORT", "8000"))
RESOURCE_URL = os.environ.get("HELPLINE_RESOURCE_URL", f"http://127.0.0.1:{PORT}/mcp")issue_token.py mints a dev token for that same RESOURCE_URL, signed with the shared dev key. By default the token covers every customer (helpline_customers: ["*"]); Step 6 explains the claim, and HELPLINE_CUSTOMERS=corvid narrows it:
import os
import sys
from pathlib import Path
from helpline.issuer import TestIssuer
from main import RESOURCE_URL
HERE = Path(__file__).resolve().parent
if __name__ == "__main__":
scopes = sys.argv[1:] or ["tickets:read"]
issuer = TestIssuer.load_or_create(HERE / ".dev-issuer.pem")
customers = os.environ.get("HELPLINE_CUSTOMERS", "*").split(",")
print(
issuer.mint(
audience=RESOURCE_URL,
scopes=scopes,
ttl_seconds=3600,
helpline_customers=customers,
)
)Now try it by hand. This run used port 8767, so both commands get PORT=8767. In one terminal, from the lesson folder:
HELPLINE_DEV=1 PORT=8767 uv run python main.pyIn a second terminal, the metadata:
curl -s http://127.0.0.1:8767/.well-known/oauth-protected-resource/mcp{"resource":"http://127.0.0.1:8767/mcp","authorization_servers":["https://auth.helpline.test"],"scopes_supported":["tickets:read"],"bearer_methods_supported":["header"]}An MCP request is a POST with the 2026-07-28 headers and a JSON-RPC body that carries its own _meta:
BODY='{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}'
H=(-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -H 'MCP-Protocol-Version: 2026-07-28')
curl -si -X POST http://127.0.0.1:8767/mcp "${H[@]}" -H 'Mcp-Method: tools/list' -d "$BODY"Without a token:
HTTP/1.1 401 Unauthorized
www-authenticate: Bearer error="invalid_token", error_description="Authentication required", resource_metadata="http://127.0.0.1:8767/.well-known/oauth-protected-resource/mcp"With a tickets:read token the same request gets HTTP/1.1 200 OK, and the result lists the five tools:
TOKEN=$(PORT=8767 uv run python issue_token.py tickets:read)
curl -si -X POST http://127.0.0.1:8767/mcp "${H[@]}" -H 'Mcp-Method: tools/list' \
-H "Authorization: Bearer $TOKEN" -d "$BODY"And the same token asking to escalate, which Step 4 explains:
CALL='{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"escalate_ticket","arguments":{"ticket_id":"HL-1006","severity":"high","reason":"Sync blocked nightly"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}'
curl -si -X POST http://127.0.0.1:8767/mcp "${H[@]}" -H 'Mcp-Method: tools/call' \
-H 'Mcp-Name: escalate_ticket' -H "Authorization: Bearer $TOKEN" -d "$CALL"HTTP/1.1 403 Forbidden
www-authenticate: Bearer error="insufficient_scope", scope="tickets:read tickets:escalate", resource_metadata="http://127.0.0.1:8767/.well-known/oauth-protected-resource/mcp"
{"error":"insufficient_scope"}One gap: the SDK lists only required_scopes in scopes_supported, so tickets:escalate doesn't appear in the metadata. An MCP client learns about it from the 403 in Step 4.
6. Step 4: tickets:read on every request, tickets:escalate on escalate_ticket
The SDK already refuses a request whose token lacks tickets:read. Escalation needs more, and the spec says how to say so: HTTP 403 with WWW-Authenticate: Bearer error="insufficient_scope", the scopes the operation needs, and the metadata URL. An MCP client acting for a user should then request a token with the extra scope, a step-up, and retry.
Returning a 403 needs to happen before the MCP layer, where the response is still an HTTP response. 2026-07-28 makes that possible: every Streamable HTTP POST carries Mcp-Method and Mcp-Name headers mirroring the body. ToolScopeMiddleware reads them:
TOOL_SCOPES: dict[str, list[str]] = {
"escalate_ticket": [READ_SCOPE, ESCALATE_SCOPE],
}
class ToolScopeMiddleware:
def __init__(self, app: ASGIApp, resource_metadata_url: str) -> None:
self.app = app
self.resource_metadata_url = resource_metadata_url
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "http":
headers = {k.decode().lower(): v.decode() for k, v in scope["headers"]}
needed = TOOL_SCOPES.get(headers.get("mcp-name", ""), [])
if headers.get("mcp-method") == "tools/call" and needed:
token = getattr(scope.get("user"), "access_token", None)
# No valid token: let the SDK answer 401. Valid but too narrow: 403 here.
if token is not None and not set(needed) <= set(token.scopes):
await self._challenge(send, needed)
return
await self.app(scope, receive, send)Can the headers be trusted? Three cases were tried against the companion server, and each became a test:
-
Header and body disagree. A
tickets:readtoken,Mcp-Name: get_ticketin the header andescalate_ticketin the body. The SDK refuses it with HTTP 400 and the 2026-07-28 header-mismatch error, and the ticketing service gets no request:json {"jsonrpc":"2.0","id":1,"error":{"code":-32020,"message":"mcp-name header does not match the request body's 'name' parameter"}} -
A modern request with no
Mcp-*headers. Also 400 with-32020, this time "mcp-method header does not match the request body's method". -
A legacy request. The SDK still serves MCP clients on the previous protocol revision, which doesn't send these headers at all. A
tools/callforescalate_ticketwithMCP-Protocol-Version: 2025-11-25passes the middleware, which can't see a tool name, and is stopped inside the tool byrequire_scopebelow: a tool-result error, "This action needs the tickets:escalate scope.", and no downstream request.
So the middleware's job is the HTTP 403 challenge for modern MCP clients, so they know to step up. The guarantee comes from require_scope in the tool.
_challenge writes the 403 itself, naming both needed scopes in one challenge, which is what the spec asks for so the MCP client can get everything in one step-up:
async def _challenge(self, send: Send, needed: list[str]) -> None:
www = (
f'Bearer error="insufficient_scope", scope="{" ".join(needed)}", '
f'resource_metadata="{self.resource_metadata_url}"'
)
body = b'{"error":"insufficient_scope"}'
await send(
{
"type": "http.response.start",
"status": 403,
"headers": [
(b"content-type", b"application/json"),
(b"www-authenticate", www.encode()),
(b"content-length", str(len(body)).encode()),
],
}
)
await send({"type": "http.response.body", "body": body})The curl walkthrough below shows the 403 a tickets:read token gets.
Both ToolScopeMiddleware and require_scope live in helpline/auth.py. Inside the tool, require_scope checks the same thing again. As the legacy case shows, this is the check that can't be skipped:
def require_scope(scope: str) -> AccessToken | None:
"""Inside a tool: refuse when the caller's token lacks `scope`.
Returns None on stdio, where there is no token (the process owner is the caller).
"""
token = get_access_token()
if token is not None and scope not in token.scopes:
raise ToolError(f"This action needs the {scope} scope.")
return tokenescalate_ticket starts with token = require_scope(ESCALATE_SCOPE), and draft_reply with require_scope(READ_SCOPE). That is a deliberate choice, and worth saying out loud: draft_reply does write. Step 5's save_draft stores the draft in the ticketing system with Helpline's credential, so any caller with tickets:read can leave drafts on its own customers' tickets. Helpline allows it because a draft is never sent: a person reviews it in the ticketing system first, and the draft records who asked through X-Acting-User. If your team treats any stored text as a write, add a tickets:write scope to TOOL_SCOPES for draft_reply. Callers then need a new token, which is why Lesson 5's contract gate counts a newly required scope as a breaking change.
A scope decides which tools a caller may use, not which tickets they may see. Per-customer access needs a check on the data itself; Step 6 adds it.
7. Step 5: Call the ticketing API with Helpline's own credential
The token a caller sends was issued for Helpline. Helpline must not forward it. helpline/backend.py calls the ticketing API over HTTP as Helpline, with its own service token, and names the acting user as data so the ticketing system can record who asked:
class TicketingAPI:
def __init__(self, store: HelplineStore, service_token: str | None = None) -> None:
self.store = store
self.service_token = service_token or os.environ.get(
"HELPLINE_SERVICE_TOKEN", "svc-dev-only"
)
self.requests: list[httpx2.Request] = []
self.http = httpx2.Client(
base_url=TICKETING_URL, transport=httpx2.MockTransport(self._fake_service)
)
def _headers(self, acting_user: str | None) -> dict[str, str]:
# Helpline's own credential, and who asked, as data. Never the caller's token.
return {
"Authorization": f"Bearer {self.service_token}",
"X-Acting-User": acting_user or "local",
}
def escalate(self, ticket_id: str, severity: str, reason: str, acting_user: str | None):
response = self.http.post(
f"/tickets/{ticket_id}/escalations",
json={"severity": severity, "reason": reason},
headers=self._headers(acting_user),
)
response.raise_for_status()
return response.json()
def save_draft(self, ticket_id: str, body: str, acting_user: str | None) -> int:
response = self.http.post(
f"/tickets/{ticket_id}/drafts", json={"body": body}, headers=self._headers(acting_user)
)
response.raise_for_status()
return response.json()["id"]escalate_ticket calls api.escalate(..., acting_user=token.subject if token else None). This is what Lesson 1 called using the server's own credential: the ticketing system trusts Helpline, and Helpline has already decided this caller may escalate.
There's no real ticketing service here, so httpx2.MockTransport stands in for it. The requests are real HTTP requests built by the same client a production service would use; they just never leave the process. The fake service keeps every request exactly as sent, refuses anything without Helpline's token, and applies the change to the store:
def _fake_service(self, request: httpx2.Request) -> httpx2.Response:
self.requests.append(request)
if request.headers.get("authorization") != f"Bearer {self.service_token}":
return httpx2.Response(401)
_, _, ticket_id, kind = request.url.path.split("/")
data = json.loads(request.content)
if kind == "escalations":
row = self.store.escalate(ticket_id, data["severity"], data["reason"])
return httpx2.Response(201, json=dict(row))
return httpx2.Response(201, json={"id": self.store.save_draft(ticket_id, data["body"])})httpx2 is the HTTP library mcp 2.3.0 itself depends on. This lesson is the first to use three of the series' dependencies directly: PyJWT with its crypto extra (which brings cryptography, used by issuer.py), uvicorn, and httpx2. All three are declared in the series' pyproject.toml.
8. Step 6: Limit each caller to its own customers' tickets
Scopes answer "may this caller escalate?". They don't answer "may this caller escalate this ticket?". With only Steps 1–5, an agent who works Corvid Analytics' queue and holds tickets:escalate could ask Helpline to escalate Acme's ticket, and Helpline would do it with its own service credential. That is the confused deputy again, one level down: Helpline has authority over every ticket, and a caller borrows it for tickets it was never meant to touch.
The fix is a second dimension in the token. The authorization server adds a helpline_customers claim listing the customer ids this caller acts for, or ["*"] for a supervisor. Helpline reads it when it verifies the token. The SDK's AccessToken has no field for it, so subclass it:
class HelplineAccessToken(AccessToken):
"""The SDK's AccessToken plus the customers this caller acts for."""
customers: list[str] = []In verify_token, a claim that isn't a list of strings grants nothing:
customers = claims.get(CUSTOMERS_CLAIM, [])
if not (isinstance(customers, list) and all(isinstance(c, str) for c in customers)):
customers = [] # a malformed claim grants nothing
return HelplineAccessToken(Two helpers turn the claim into a decision. On stdio there is no token, so nothing changes there; over HTTP, a token without the claim gets an empty set, so the default is deny:
def allowed_customers() -> set[str] | None:
"""Customer ids the caller may act for, or None for no restriction.
None on stdio (no token: the process owner is the caller) and for a token
with helpline_customers ["*"]. A token without the claim gets an empty set:
deny by default.
"""
token = get_access_token()
if token is None:
return None
customers = set(getattr(token, "customers", []))
return None if ALL_CUSTOMERS in customers else customers
def may_access(customer_id: str) -> bool:
allowed = allowed_customers()
return allowed is None or customer_id in allowedEvery ticket lookup goes through require_ticket, so one change covers get_ticket, draft_reply and escalate_ticket:
def require_ticket(ticket_id: str):
row = store.ticket(ticket_id)
# Another customer's ticket gets the same answer as a missing one, so a
# caller can't learn which ids exist outside its own customers.
if row is None or not may_access(row["customer"]):
raise ToolError(
f"No ticket with id {ticket_id!r}. Ticket ids look like HL-1003; "
"use search_tickets to look one up."
)
return rowAnother customer's ticket gets exactly the same reply as an id that doesn't exist. A different message, such as "forbidden", would let a caller enumerate which ticket ids exist across all customers. The ticket resource does the same with ResourceNotFoundError, and search_tickets filters before paging, so total and the cursors only ever count tickets the caller may see:
rows = [
r for r in store.search_tickets(query, status, customer) if may_access(r["customer"])
]None of this changes a tool's input or output schema, which matters in Lesson 5: the contract gate still passes. The rule lives in Helpline because Helpline is the deputy. The ticketing system can still enforce its own rules using the X-Acting-User header from Step 5, and defence in both places is better than either alone.
9. Verify it
The tests start a real uvicorn server on a random localhost port in a background thread, with a fresh test issuer, and talk to it two ways: raw HTTP for status codes and headers, and the SDK's Client over streamable_http_client for real MCP calls. The token cases:
def test_token_for_another_server_is_rejected(live):
stolen = live.token(audience="https://billing.example.com/mcp")
assert post_tools_list(live, stolen).status_code == 401
def test_token_from_another_issuer_is_rejected(live):
forged = live.token(issuer="https://evil.example")
assert post_tools_list(live, forged).status_code == 401
def test_token_signed_by_another_key_is_rejected(live):
other = TestIssuer(kid=live.issuer.kid) # same kid and issuer, different key
forged = other.mint(audience=live.resource, scopes=READ)
assert post_tools_list(live, forged).status_code == 401
def test_expired_token_is_rejected(live):
expired = live.token(ttl_seconds=-120) # beyond the 30s leeway
assert post_tools_list(live, expired).status_code == 401And the passthrough proof, which inspects the raw requests the fake service received:
async def test_escalate_with_scope_uses_the_servers_own_credential(live):
token = live.token(ESCALATE, subject="agent-maria")
async with live.client(token) as client:
result = await client.call_tool(
"escalate_ticket",
{"ticket_id": "HL-1006", "severity": "high", "reason": "Sync blocked nightly"},
)
assert result.is_error is False
sent = live.api.requests[-1] # the raw HTTP request Helpline sent downstream
assert (sent.method, sent.url.path) == ("POST", "/tickets/HL-1006/escalations")
assert sent.headers["authorization"] == "Bearer svc-helpline-7f3a"
assert sent.headers["x-acting-user"] == "agent-maria"
# No token passthrough: the caller's token is in no header and no body of any request.
for request in live.api.requests:
assert all(token not in value for value in request.headers.values())
assert token.encode() not in request.contentCan that test fail? Helpline's code builds the header from the service token, so passthrough would need someone to add it, for example a well-meant X-Forwarded-Authorization header. That bug was injected into a scratch copy of the folder, and the test failed with 1 failed. Its job is to keep that change from ever shipping.
One result is easy to misread. Through the SDK's Client, escalating with only tickets:read raises MCPError with code -32603 and the message "Server returned an error response". The 403 and its challenge reach the HTTP layer, but a Client with no OAuth provider attached can't do the step-up, so it reports a generic error. The challenge headers are for the MCP client's auth layer, not for the model. The test asserts that code and that the ticketing service received no request.
Run the suite:
uv run pytest -v teststests/test_http_auth.py::test_protected_resource_metadata PASSED
tests/test_http_auth.py::test_no_token_gets_401_pointing_at_the_metadata PASSED
tests/test_http_auth.py::test_valid_token_is_accepted PASSED
tests/test_http_auth.py::test_token_for_another_server_is_rejected PASSED
tests/test_http_auth.py::test_token_from_another_issuer_is_rejected PASSED
tests/test_http_auth.py::test_token_signed_by_another_key_is_rejected PASSED
tests/test_http_auth.py::test_expired_token_is_rejected PASSED
tests/test_http_auth.py::test_token_without_read_scope_gets_403 PASSED
tests/test_http_auth.py::test_read_tools_work_over_http PASSED
tests/test_http_auth.py::test_escalate_without_scope_fails_and_changes_nothing PASSED
tests/test_http_auth.py::test_escalate_challenge_names_the_scope PASSED
tests/test_http_auth.py::test_escalate_with_scope_uses_the_servers_own_credential PASSED
tests/test_http_auth.py::test_legacy_call_without_mcp_headers_is_still_refused PASSED
tests/test_http_auth.py::test_modern_call_without_mcp_headers_is_rejected PASSED
tests/test_http_auth.py::test_search_only_returns_the_callers_customers PASSED
tests/test_http_auth.py::test_supervisor_with_star_sees_every_customer PASSED
tests/test_http_auth.py::test_token_without_the_claim_sees_nothing PASSED
tests/test_http_auth.py::test_other_customers_ticket_looks_exactly_like_a_missing_one PASSED
tests/test_http_auth.py::test_cannot_escalate_another_customers_ticket PASSED
tests/test_http_auth.py::test_other_customers_resource_is_not_found PASSED
tests/test_scopes.py::test_no_token_means_stdio_and_is_allowed PASSED
tests/test_scopes.py::test_missing_scope_is_refused_inside_the_tool PASSED
tests/test_scopes.py::test_granted_scope_returns_the_token PASSED
tests/test_scopes.py::test_malformed_customers_claim_grants_nothing PASSED
tests/test_scopes.py::test_http_app_refuses_a_server_without_a_verifier PASSEDThose are the 25 new tests. The six per-customer tests are Step 6's: a Corvid-only token sees three tickets, a supervisor's ["*"] sees all eleven, a token without the claim sees none, Acme's HL-1001 answers exactly like a missing id, escalating it fails with no request reaching the ticketing API, and its resource is not found. With Lessons 2 and 3's suites carried forward, the run ends 49 passed. The last test in the list proves the guard at the top of http_app: a server built without a token verifier would treat every HTTP caller like stdio's trusted local user, so http_app refuses to wrap one.
10. One escalate_ticket call, traced through the confused-deputy defences
Follow a call from agent-maria to escalate HL-1006:
- Signature and issuer. The token was signed by a key the trusted issuer published. A forged token stops here with 401.
- Audience.
audis Helpline's URL. A token minted for the billing service stops here, so Helpline can't be used to spend a token meant for something else. - Expiry. A stolen token stops working within minutes.
- Scope. The middleware and
require_scopefindtickets:escalate. Without it, a 403 challenge (or a tool-result error on the legacy path). This narrows the confused deputy: Helpline can escalate, but only for callers granted the escalate scope. - Customer.
HL-1006belongs to Corvid Analytics, and Maria's token listscorvidinhelpline_customers. Asked for Acme'sHL-1001instead, Helpline answers as if the ticket didn't exist. - Downstream credential. The ticketing API sees Helpline's service token and
acting_user: agent-maria, never the caller's token.
Audience checks alone wouldn't have stopped the confused deputy; it took the scope check, the customers check and the service credential together. Each answers a different question: is this token for me, may this caller do this, to whose data, and as whom do I act downstream. These checks are only as good as the values your authorization server issues: grant tickets:escalate or ["*"] to the wrong people and every check here accepts the token. OAuth also does nothing against tool-description poisoning; Lesson 5's audit record adds a trail of who did what.
11. Common problems
Every request gets 401 even with a fresh token. Compare the token's aud with HELPLINE_RESOURCE_URL character by character: http versus https, the port, and a trailing slash all matter. issue_token.py mints for the RESOURCE_URL that main.py computes, so run both with the same PORT.
The metadata shows an issuer with a trailing slash. You passed an AnyHttpUrl to AuthSettings; pass a string.
search_tickets returns nothing and every get_ticket says "No ticket". The token has no helpline_customers claim, so Helpline denies by default. Configure the authorization server to add it; for local tests, HELPLINE_CUSTOMERS=corvid uv run python issue_token.py mints one for a single customer.
Expired-token tests pass when they shouldn't. The verifier allows 30 seconds of leeway. Test with an expiry well past it, as the test does with -120.
escalate_ticket fails in your own Client code with MCPError -32603. That's the 403 without a step-up flow. Mint a token with uv run python issue_token.py tickets:read tickets:escalate.
12. Exercise: refuse a token signed with the wrong algorithm
Add a test to tests/test_http_auth.py that sends a token signed with HS256 instead of RS256. This is the shape of a key-confusion attack, where an attacker signs with the public key as an HMAC secret.
Expected result. 401, and the server log shows rejected token: The specified alg value is not allowed. The verifier allows only RS256 and ES256, so PyJWT rejects the token before checking anything else.
Hints. Build the claims as mint() does, then use jwt.encode(claims, secret, algorithm="HS256", headers={"kid": live.issuer.kid}). Any byte string of 32 or more bytes works as the secret, because the algorithm check fails first. Send it with the post_tools_list helper.
Verify with uv run pytest tests -k algorithm.
13. What we learned, and what Lesson 5 builds on
Helpline is now a resource server: it publishes where tokens come from, accepts only tokens signed by its issuer, for its audience, unexpired and scoped, limits each caller to its own customers' tickets, and calls downstream as itself. Lesson 5 makes it shippable: contract tests that catch breaking changes, an audit record for every tool call, rate limits, a container image and host configuration.

