MCP server · Token · /api/docs-store · stage 2 of 2
Token exchange (RFC 8693)
When an MCP host asks for the resource list, the MCP server reads the files from the document store, GET /api/docs-store/files, a separate API with its own audience. The MCP server never forwards the token it was given, whose audience is /mcp/demo. It exchanges that token at /oauth/token with the token-exchange grant type, authenticating as its own confidential client, mcp-demo-server. It gets a token issued for the store, with scope documents:read, for the same user and valid for at most five minutes.
Explained in Ep 3: No token passthrough: token exchange (RFC 8693) for the document store From MCP deep dive, Ep 3: MCP Authorization Deep Dive: Scopes, Step-Up and Token Exchange
demo/src/token-exchange.ts234 / 234 lines on this page explainedevery line of the file
functions/api/docs-store/[[path]].ts10 / 10 lines on this page explainedevery line of the file
demo/src/oauth.ts17 / 17 lines on this page explainedlines 117-124,157-162,166-168 of 391; the rest are on other stage pages
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own
/** * OAuth 2.0 Token Exchange (RFC 8693) for the demo's MCP server (README.md, "The MCP server"; docs/mcp-oauth-flow.md). * * The MCP server must not pass the token it was given on to another API: that token's audience is the MCP server * (`<origin>/mcp/demo`), and an API that accepted it would be trusting a token that was never issued for it. So when * the MCP server needs the document store, it trades the caller's token for a new one, issued for the store, at the * authorization server's token endpoint, and calls the store with that. Three parts, in the order a request meets them: * * 1. THE EXCHANGE, at `POST <origin>/oauth/token` with grant_type token-exchange. The OAuth library answers every * other grant at that endpoint; this one is caught before it (oauth.ts) because the library's own exchange can * only re-issue a token for the same resource and the same scopes, and the store is another resource with its own. * 2. THE DOCUMENT STORE, `GET <origin>/api/docs-store/files`: a downstream API with its own audience. It accepts only * a token the exchange issued for it. * 3. THE MCP SERVER AS A CLIENT, `filesFromStore`: exchange, then call the store as the same user. The MCP server's * resource list (mcp.ts) is built from it. * * Exchanged tokens live in the KV namespace OAUTH_KV beside the library's, under `exchanged:<SHA-256 of the token>`, * and KV deletes each one when it expires. The token itself is never stored. * * The MCP server's client secret is a Worker secret, `DOCS_STORE_CLIENT_SECRET` (`npx wrangler secret put * DOCS_STORE_CLIENT_SECRET`), read from the environment and never written in the code. Without it no exchange succeeds. */
Why the token is exchanged, in three parts Never runs
WhatThe module's doc comment. The MCP server must not forward the token it was given, because that token's audience is <origin>/mcp/demo. When the MCP server needs the document store, it exchanges the token at the authorization server's token endpoint for one issued for the store, and calls the store with the new token. The comment lists the module's three parts in the order a request meets them: the exchange, the store, and the MCP server acting as a client. Exchanged tokens are kept in OAUTH_KV under exchanged:<SHA-256 of the token>, and the client secret is the Worker secret DOCS_STORE_CLIENT_SECRET.
WhyAn access token is issued for one audience. A downstream API that accepted a token issued for another audience would let any holder of an MCP token call it, and would let the MCP server act with the user's token anywhere. The MCP specification forbids this token passthrough. Token exchange is the standard way to get a token for the right audience on behalf of the same user.
Whatjson, sha256 and the Env type from app.ts; validateMcpToken from oauth.ts, which checks a token exactly as the MCP endpoint does; READ, the docs:read scope, from mcp.ts.
WhyEach import comes from the module that defines it, so the exchange checks the subject token with the same validator and the same scope name as the MCP server. app.ts, oauth.ts, mcp.ts and this module import each other in a cycle. This module uses its imports only inside functions, which run after every module has loaded.
/** The Worker's bindings, plus the client secret of `mcp-demo-server` (a Worker secret, set with wrangler, never in the code). */exporttypeExchangeEnv = Env & { DOCS_STORE_CLIENT_SECRET?: string }
ExchangeEnv: the bindings plus the client secret Type only
WhatExchangeEnv is the Worker's Env plus one optional field, DOCS_STORE_CLIENT_SECRET, the client secret of mcp-demo-server.
WhyDeclaring the secret in the only module that reads it leaves app.ts's Env unchanged. The field is optional because a Worker without the secret must still start; every exchange is then refused (see Authenticate the client). oauth.ts and mcp.ts pass their plain Env, which the compiler accepts because the field is optional, and at run time the deployed env carries the secret.
The two URNs from RFC 8693 that this exchange uses.
/** The grant type and token type RFC 8693 defines (sections 2.1 and 3). */exportconstTOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange'exportconstACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'
The grant type and the token type Module load
WhatTOKEN_EXCHANGE is urn:ietf:params:oauth:grant-type:token-exchange, the grant_type that requests an exchange. ACCESS_TOKEN_TYPE is urn:ietf:params:oauth:token-type:access_token, the type of both the subject token and the issued token.
WhyRFC 8693 defines the grant type in section 2.1 and the token type identifiers in section 3. The token endpoint compares grant_type with the exact string to tell an exchange from the code and refresh grants the library answers.
grant_type = urn:ietf:params:oauth:grant-type:token-exchangetoken type = urn:ietf:params:oauth:token-type:access_token
Who may exchange, for what scope, and for how long.
/** The one client allowed to exchange: the MCP server itself, a confidential client with a secret. */exportconstEXCHANGE_CLIENT = 'mcp-demo-server'
The one client: mcp-demo-server Module load
WhatEXCHANGE_CLIENT is 'mcp-demo-server', the client id the MCP server authenticates as when it requests an exchange.
WhyOnly the MCP server may exchange, whatever kind of client a connected app is. The MCP server is a confidential client, which holds a secret; an MCP host on someone's laptop could not keep one. Claude Code, for example, registers as a public client (token_endpoint_auth_method none).
/** The one scope the store knows: reading the list of the user's files. */exportconstSTORE_SCOPE = 'documents:read'
The store's one scope: documents:read Module load
WhatSTORE_SCOPE is 'documents:read', the only scope the document store knows: reading the list of the user's files.
WhyThe store has its own scope, separate from the MCP server's docs:read and docs:write. A token for the store states what the store may be asked and says nothing about the MCP server's tools.
/** How long an exchanged token lasts, in seconds: long enough for one call, never longer than the token it came from. */exportconstEXCHANGED_LIFETIME = 300
Five minutes at most Module load
WhatEXCHANGED_LIFETIME is 300: an exchanged token lasts at most 300 seconds.
WhyThe token is made for one call to the store, a moment after it is issued, so a short lifetime limits what a leaked token could do. The issue step also caps it at the subject token's remaining lifetime (Issue the token).
/** The store's address, which is also its audience: the `resource` an exchange must name. */exportconststoreResource = (origin: string) => `${origin}/api/docs-store`
The store's address is its audience MCP request
WhatstoreResource(origin) returns <origin>/api/docs-store, the resource an exchange must name and the audience written into every exchanged token.
WhyOne function supplies the value a client must request, the value stored in the token and the value the store checks, so the three cannot drift apart. The value depends on the origin, so the site refuses a token issued on a local run, and a local run refuses the site's.
/** Where exchanged tokens are kept, by the hash of the token. */constkvKey = (hash: string) => `exchanged:${hash}`
Where an exchanged token is kept MCP request
WhatkvKey(hash) returns exchanged:<hash>, the OAUTH_KV key of an exchanged token's record, where hash is the token's SHA-256.
WhyThe prefix keeps these records apart from the library's own keys (grant:, token:, client:) in the same namespace. Because the key is the hash, the token itself is never stored, and a copy of the namespace holds nothing that can be presented as a token.
/** What is stored for an exchanged token. `sub` is the user: the demo whose files the token may read. */interfaceExchanged {sub: stringclient_id: string/** The app the person connected, whose token was exchanged; kept so a record shows who acted for whom. */subject_client_id: stringaud: stringscope: stringexp: number}
The record of an exchanged token Type only
Whatsub is the user, the demo account whose files the token may read. client_id is mcp-demo-server, and subject_client_id is the connected app whose token was exchanged. aud is the store's address, scope is documents:read, and exp is the expiry in seconds since the epoch.
Whysub, aud, exp, scope and client_id are the claim names RFC 9068 uses for a JWT access token (RFC 8693 sections 4.2 and 4.3 define scope and client_id). Here they are kept server-side instead of signed into a JWT, and the store looks the record up by the token's hash and checks aud, exp and scope on it. subject_client_id is the demo app's own field and records which connected app's token was exchanged. It is not a registered claim, because RFC 8693's claim for an acting party, act, requires an actor token.
/** An error from the token endpoint in RFC 6749 section 5.2's shape. Never cached. */functionoauthError(status: number, error: string, description: string, extra: Record<string, string> = {}): Response {returnjson(status, { error, error_description: description }, { 'Cache-Control': 'no-store', Pragma: 'no-cache', ...extra })}
RFC 6749's error shape, never cached MCP request
WhatoauthError(status, error, description, extra) returns JSON { error, error_description } with Cache-Control: no-store, Pragma: no-cache and any extra headers.
WhyRFC 6749 section 5.2 defines the error body. Section 5.1 requires no-store and Pragma: no-cache on token responses, and sending them on errors too keeps any error from being cached. RFC 8693 section 2.2.2 says an exchange's errors use the same shape, so a client reads a refused exchange's error body as it reads any refused token request's.
/** Whether two strings are equal, in time that does not depend on where they differ. Both are hashed first, so the lengths match. */asyncfunctionsameSecret(given: string, expected: string): Promise<boolean> {const [a, b] = awaitPromise.all([given, expected].map((text) => crypto.subtle.digest('SHA-256', newTextEncoder().encode(text))))return crypto.subtle.timingSafeEqual(a, b)}
A constant-time comparison MCP request
WhatHashes both strings with SHA-256 and compares the two 32-byte digests with crypto.subtle.timingSafeEqual, the Workers runtime's constant-time comparison.
WhyAn ordinary === stops at the first differing byte, so its timing tells an attacker how much of a guess was right. timingSafeEqual takes the same time wherever the bytes differ, but it requires inputs of equal length. Hashing first makes the lengths equal and also hides the secret's length.
/** * Who the client says it is, from HTTP Basic or from the form (client_secret_basic or client_secret_post, * RFC 6749 section 2.3.1). Using both at once is refused, as that section requires. */functionclientCredentials(request: Request, form: URLSearchParams): { id: string; secret: string } | 'both' | null {const header = request.headers.get('Authorization') ?? ''const posted = form.has('client_secret')
Basic or the form, never both MCP request
WhatReads the Authorization header and checks whether the form contains client_secret. Returns the id and secret, 'both' when the client used both methods, or null when it used neither.
WhyRFC 6749 section 2.3.1 defines HTTP Basic and the form parameters (client_secret_basic and client_secret_post), and section 2.3 forbids a client to use more than one method in a request. The 'both' result lets the caller refuse that case with invalid_request.
WhatWith Authorization: Basic and no client_secret in the form, the rest of the header is base64-decoded and split at the first colon, and each part is form-decoded ('+' becomes a space, then percent-decoding). A header that is not valid base64, has no colon or fails to decode gives null.
WhyRFC 6749 section 2.3.1 says the id and secret are form-encoded before they are joined and base64-encoded, so they are decoded the same way. filesFromStore sends them without form-encoding. That decodes to the same text only while the secret contains no '%' or '+', which holds for a secret of letters and digits, as the README asks for.
WhatWith client_secret in the form and no Basic header, client_id and client_secret come from the form (client_id is an empty string when missing). With neither method, the result is null.
WhyA null result and an unknown id both get the same 401 invalid_client, so a caller learns nothing about which part was wrong.
/** Whether a token request asks for token exchange. Read from a copy, so the library still gets the whole body otherwise. */exportasyncfunctionisTokenExchange(request: Request): Promise<boolean> {returnnewURLSearchParams(await request.clone().text()).get('grant_type') === TOKEN_EXCHANGE}
Read from a copy of the body MCP request
WhatParses a clone of the request's body as a form and compares grant_type with TOKEN_EXCHANGE.
WhyA request body can be read only once. Reading a clone leaves the original unread, so when the grant is anything else (authorization_code, refresh_token), oauthRoute can still pass the whole request to the library.
The token endpoint for the token-exchange grant. It authenticates the client, checks the parameters and the subject token, and issues a token for the store.
/** * `POST /oauth/token` with grant_type token-exchange. In order: authenticate the client, check the request's * parameters, validate the subject token as the library would for the MCP server, then issue a short-lived token * for the store, for the same user, and answer as RFC 8693 section 2.2.1 says. */exportasyncfunctiontokenExchange(request: Request, env: ExchangeEnv, origin: string): Promise<Response> {// The token endpoint takes a form body (RFC 6749 section 3.2).const form = newURLSearchParams(await request.text())
The order of the checks, and the form body MCP request
WhatThe doc comment gives the order of the steps: authenticate the client, check the parameters, validate the subject token as the library would for the MCP server, then issue a short-lived token for the store and answer as RFC 8693 section 2.2.1 specifies. The body is parsed as application/x-www-form-urlencoded.
WhyRFC 6749 section 3.2 requires a form body at the token endpoint. The client is authenticated first, so an unauthenticated caller learns nothing about whether a subject token is valid.
// 1. The client: only the MCP server, with its secret (a Worker secret, never in the code).const client = clientCredentials(request, form)if (client === 'both') returnoauthError(400, 'invalid_request', 'Use one client authentication method, not two.')const expected = env.DOCS_STORE_CLIENT_SECRET ?? ''if (client === null || client.id !== EXCHANGE_CLIENT || expected === '' || !(awaitsameSecret(client.secret, expected))) {// 401 with a Basic challenge, as RFC 6749 section 5.2 asks of invalid_client.returnoauthError(401, 'invalid_client', 'Client authentication failed.', { 'WWW-Authenticate': 'Basic realm="joelstevick.com"' }) }
Authenticate the client MCP request
WhatA request that uses both authentication methods gets 400 invalid_request. Otherwise the client must be mcp-demo-server, the Worker must have DOCS_STORE_CLIENT_SECRET set, and the presented secret must match it (sameSecret). Any failure gets 401 invalid_client with WWW-Authenticate: Basic realm="joelstevick.com".
WhyOnly the MCP server may exchange. An empty expected secret counts as a failure, so a Worker deployed without the secret refuses every exchange instead of accepting an empty secret. RFC 6749 section 5.2 asks for 401 and a challenge when a client that authenticated through the Authorization header fails.
// 2. The parameters RFC 8693 section 2.1 defines, as far as this server supports them.const subjectToken = form.get('subject_token') ?? ''if (subjectToken === '') returnoauthError(400, 'invalid_request', 'subject_token is required.')if (form.get('subject_token_type') !== ACCESS_TOKEN_TYPE) returnoauthError(400, 'invalid_request', `subject_token_type must be ${ACCESS_TOKEN_TYPE}.`)if (form.has('actor_token')) returnoauthError(400, 'invalid_request', 'actor_token is not supported.')const requested = form.get('requested_token_type')if (requested !== null && requested !== ACCESS_TOKEN_TYPE) returnoauthError(400, 'invalid_request', `requested_token_type must be ${ACCESS_TOKEN_TYPE}.`)
The request's parameters MCP request
Whatsubject_token is required, and subject_token_type must be the access token type. An actor_token is refused, because delegation with an actor is not supported. requested_token_type, when present, must be the access token type. Each failure gets 400 invalid_request with a description that names the parameter.
WhyRFC 8693 section 2.1 defines these parameters. tokenExchange() supports one kind of exchange, an access token for an access token on the user's behalf, and its error says exactly which parameter asked for something else.
// The target: the store, named by `resource` (RFC 8707) or `audience`. Any other target is refused.const store = storeResource(origin)const targets = [...form.getAll('resource'), ...form.getAll('audience')]if (targets.length === 0) returnoauthError(400, 'invalid_request', `resource is required: ${store}.`)if (targets.some((target) => target !== store)) returnoauthError(400, 'invalid_target', `Tokens are exchanged only for ${store}.`)
The target: the store only MCP request
WhatCollects every resource (RFC 8707) and audience parameter. At least one is required (400 invalid_request), and each must be the store's address (400 invalid_target).
WhyThe target sets the audience of the issued token. Because every other target is refused, the exchange cannot mint a token for the MCP server itself or for any other API. RFC 8693 section 2.2.2 defines invalid_target for this case.
// The scope: the store's one scope, which is also what is issued when none is asked for.const scope = (form.get('scope') ?? STORE_SCOPE).split(' ').filter(Boolean)if (scope.length === 0 || scope.some((one) => one !== STORE_SCOPE)) returnoauthError(400, 'invalid_scope', `The only scope for ${store} is ${STORE_SCOPE}.`)
The scope: documents:read MCP request
Whatscope defaults to documents:read when absent. Split on spaces, it must be non-empty and contain only documents:read; otherwise the request gets 400 invalid_scope.
WhyThe store has one scope, so any other value asks for access that does not exist. The default lets a client omit scope, as RFC 6749 allows, and still get the one scope there is.
// 3. The subject token: a live access token the library issued for the MCP server, with permission to read. RFC 8693// section 2.2.2 says an invalid or unacceptable subject token is answered with invalid_request.const subject = awaitvalidateMcpToken(env, origin, subjectToken)if (subject === null) returnoauthError(400, 'invalid_request', 'subject_token is not a valid access token for the MCP server.')if (!subject.scope.includes(READ)) returnoauthError(400, 'invalid_request', `subject_token does not carry ${READ}.`)
Validate the subject token MCP request
WhatvalidateMcpToken checks the subject token exactly as the MCP endpoint does: issued by this authorization server, for <origin>/mcp/demo, not expired and not revoked. A token that fails the check, or that lacks docs:read, gets 400 invalid_request.
WhyThe exchange issues a token for the same user, so it must start from a live token the user actually granted. Requiring docs:read means a token narrowed to offline_access alone cannot be turned into read access at the store. RFC 8693 section 2.2.2 says an invalid subject token gets invalid_request.
// 4. Issue: 32 random bytes, kept only as their hash, for the same user and never past the subject's own expiry.const now = Math.floor(Date.now() / 1000)const expiresIn = Math.min(EXCHANGED_LIFETIME, subject.expiresAt - now)if (expiresIn < 1) returnoauthError(400, 'invalid_request', 'subject_token has expired.')const accessToken = base64url(crypto.getRandomValues(newUint8Array(32)))constrecord: Exchanged = { sub: subject.userId, client_id: EXCHANGE_CLIENT, subject_client_id: subject.clientId, aud: store, scope: STORE_SCOPE, exp: now + expiresIn }// KV keeps a value at least 60 seconds; the expiry above is what the store checks.await env.OAUTH_KV!.put(kvKey(awaitsha256(accessToken)), JSON.stringify(record), { expirationTtl: Math.max(60, expiresIn) })
Issue the token MCP request
Whatexpires_in is the smaller of 300 seconds and the subject token's remaining lifetime; below one second the request gets 400 invalid_request. The token is 32 random bytes from crypto.getRandomValues, encoded as base64url. Its record (sub, client_id, subject_client_id, aud, scope, exp) is written to OAUTH_KV under the token's SHA-256, with a KV expiration TTL of at least 60 seconds.
WhyCapping by the subject token's expiry means an exchange can never extend a grant's life. 32 random bytes cannot be guessed. Because only the hash is stored, the KV namespace never holds a usable token. KV's minimum TTL is 60 seconds, so the record of a shorter-lived token stays in KV briefly after its exp. The store checks exp itself and refuses the token all the same.
What200 with access_token, issued_token_type (the access token type), token_type Bearer, expires_in and scope documents:read, plus Cache-Control: no-store and Pragma: no-cache.
WhyRFC 8693 section 2.2.1 requires access_token, issued_token_type and token_type, recommends expires_in, and makes scope optional when it equals the requested scope. issued_token_type is the field an exchange adds to an ordinary token response. No refresh token is issued, because the MCP server exchanges again whenever it needs the store again.
/** A refusal with the Bearer challenge of RFC 6750 section 3; no error code when no token was sent at all. */functionchallenge(status: number, error?: string, description?: string): Response {const parts = ['realm="docs-store"', ...(error === undefined ? [] : [`error="${error}"`, `error_description="${description}"`]), ...(error === 'insufficient_scope' ? [`scope="${STORE_SCOPE}"`] : [])]returnjson(status, error === undefined ? { error: 'unauthorized' } : { error, error_description: description }, { 'WWW-Authenticate': `Bearer ${parts.join(', ')}`, 'Cache-Control': 'no-store' })}
RFC 6750's Bearer challenge MCP request
Whatchallenge(status, error, description) returns JSON with WWW-Authenticate: Bearer realm="docs-store". When there is an error code, the challenge adds error and error_description, plus scope="documents:read" for insufficient_scope. Without an error code the body is { error: 'unauthorized' } and the challenge carries the realm alone. Cache-Control is no-store.
WhyRFC 6750 section 3 defines the challenge, and section 3.1 says a request that sent no credentials should get no error code. Naming the scope on insufficient_scope tells a client exactly which scope to request.
/** * `GET <origin>/api/docs-store/files`: the calling user's files. The token is looked up by its hash among the tokens * the exchange issued; an MCP access token forwarded unchanged is not among them, so it is refused like any token * not issued for this audience. Then the audience, the expiry and the scope are checked on what was found. */exportasyncfunctiondocsStoreRoute(request: Request, env: ExchangeEnv, origin: string): Promise<Response> {const { pathname } = newURL(request.url)if (pathname !== '/api/docs-store/files') returnjson(404, { error: 'not found' })if (request.method !== 'GET') returnjson(405, { error: 'method not allowed' }, { Allow: 'GET' })
One route, GET only MCP request
WhatAny path other than /api/docs-store/files gets 404, and any method other than GET gets 405 with Allow: GET. The doc comment describes the token check that follows: the store looks the token up by its hash among the tokens the exchange issued, so it does not find an MCP access token forwarded unchanged.
WhyThe store is reached two ways. filesFromStore calls it in process when the MCP server lists its resources, and any caller can reach it over HTTP through the site (functions/api/docs-store/[[path]].ts, then oauthRoute).
WhatThe Authorization header must be Bearer followed by one token, with the scheme matched case-insensitively; otherwise the store answers 401 with the bare challenge.
WhyRFC 6750 section 2.1 defines sending a bearer token in the Authorization header. A request with no token gets no error code, as section 3.1 says.
// Only a token issued for this audience, still live, with the store's scope.const found = await env.OAUTH_KV!.get<Exchanged>(kvKey(awaitsha256(token)), 'json')if (found === null || found.aud !== storeResource(origin)) returnchallenge(401, 'invalid_token', 'The token was not issued for this API.')if (found.exp <= Math.floor(Date.now() / 1000)) returnchallenge(401, 'invalid_token', 'The token has expired.')if (!found.scope.split(' ').includes(STORE_SCOPE)) returnchallenge(403, 'insufficient_scope', `The token does not carry ${STORE_SCOPE}.`)
Audience, expiry, scope MCP request
WhatReads the record from OAUTH_KV under exchanged:<SHA-256 of the token>. A missing record, or one whose aud is not this origin's store, gets 401 invalid_token "The token was not issued for this API.". A passed exp gets 401 invalid_token, and a scope without documents:read gets 403 insufficient_scope.
WhyThis is where token passthrough fails. An MCP access token has no exchanged: record, so the store refuses it exactly like a token for any other audience. The store checks the expiry itself because KV may keep a record up to 60 seconds past it.
// The user's files and nothing else: the user is the token's, never anything in the request.const rows = await env.DB.prepare('SELECT rowid AS id, name, pages FROM files WHERE demo_id = ? ORDER BY rowid').bind(found.sub).all<StoredFile>()returnjson(200, { files: rows.results }, { 'Cache-Control': 'no-store' })}
That user's files, and nobody else's MCP request
WhatRuns SELECT rowid AS id, name, pages FROM files WHERE demo_id = ? ORDER BY rowid, bound to the record's sub, and answers 200 { files: [...] } with Cache-Control: no-store.
WhyThe user comes from the token and never from the request, so no parameter can name another demo account. filesOf in mcp.ts runs the same query, so the list is identical whichever way it is read.
/** * The caller's files, read the way a separate service would be: exchange the caller's MCP token for a store token, * then call the store with it. Both requests are the real HTTP requests, handed to the two handlers above in this * Worker without a network hop, so they cost one KV write and two KV reads, and nothing else. */exportasyncfunctionfilesFromStore(env: ExchangeEnv, origin: string, mcpToken: string): Promise<StoredFile[]> {
Read the files the way a separate service would MCP request
WhatfilesFromStore(env, origin, mcpToken) returns the caller's files. The doc comment says both requests are real HTTP requests, passed to tokenExchange and docsStoreRoute in this Worker without a network hop. Together the exchange and the store's token check cost one KV write and two KV reads, on top of the D1 query that lists the files.
WhyCalling the handlers in process keeps the protocol and its checks exactly as they would be across a network, even though the store runs in the same Worker. If the store moved to another service, only the transport would change.
WhatA POST to <origin>/oauth/token with Content-Type application/x-www-form-urlencoded and Authorization: Basic base64(mcp-demo-server:secret). The form carries grant_type token-exchange, subject_token (the caller's MCP access token), subject_token_type access_token, resource <origin>/api/docs-store and scope documents:read. A refusal throws an error with the status and body; otherwise the function reads access_token from the JSON.
WhyThis is the complete RFC 8693 request. The subject token is the token the MCP host sent, so the exchanged token is for the same user and can grant no more than that user granted. Throwing makes resources/list fail with an error instead of returning an empty list.
// The store, called as the same user with the new token.const listed = awaitdocsStoreRoute(newRequest(`${storeResource(origin)}/files`, { headers: { Authorization: `Bearer ${access_token}` } }), env, origin)if (!listed.ok) thrownewError(`document store refused: ${listed.status}`)return ((await listed.json()) as { files: StoredFile[] }).files}
The store, with the new token MCP request
WhatGET <origin>/api/docs-store/files with Authorization: Bearer <the exchanged token>. A refusal throws an error with the status; otherwise the function returns the files array.
WhyThe visitor's MCP token never reaches the store. Only the token issued for the store's audience does, which is the purpose of the exchange.
/** * An MCP access token checked exactly as the MCP endpoint checks it: issued by this server, for `<origin>/mcp/demo`, * not expired, not revoked. What comes back is the user (the demo), the scopes, the client and the expiry; null for * anything else. The token exchange uses it on the subject token (token-exchange.ts). */exportconstvalidateMcpToken = (env: Env, origin: string, token: string) =>serversFor(origin).authorization.validateToken<Props>(`${origin}/mcp/demo`, token, env)
The same check as the MCP endpoint MCP request
WhatvalidateMcpToken(env, origin, token) calls the authorization server's validateToken for the resource <origin>/mcp/demo. The library loads the token's KV record by the token's hash, checks that its audience is that resource and that it has not expired, and decrypts the grant's props. It returns the user id (the demo account's id), the scopes, the client id and the expiry, or null.
WhyThe exchange must accept exactly the tokens the MCP server accepts. Using the library's own validator for the same resource guarantees that, revocation included: revoking a grant deletes its tokens from KV, so they validate as null.
// The document store, a downstream API with its own audience (token-exchange.ts); open to anyone, so limited by address.if (pathname.startsWith('/api/docs-store')) {if (!(awaitanonymousAllowed(request, env))) returntooMany()returndocsStoreRoute(request, env, origin) }
Route the store, limited by address MCP request
WhatanonymousAllowed counts a request under /api/docs-store against the caller's address (429 past 120 a minute), and docsStoreRoute then answers it.
WhyThe store is reachable from the internet through the site without an access key, so before the token is checked the address is the only identity, as on the other open endpoints. filesFromStore calls docsStoreRoute directly, so the MCP server's own reads are not counted here; the MCP request that caused them was already counted.
// Token exchange (RFC 8693) is answered here, before the library, which answers every other grant at this endpoint.if (pathname === '/oauth/token' && request.method === 'POST' && (awaitisTokenExchange(request))) returntokenExchange(request, env, origin)
Caught before the library MCP request
WhatA POST to /oauth/token whose grant_type is token-exchange (isTokenExchange reads a copy of the body) goes to tokenExchange, and every other grant falls through to the library. The check comes after the address count for POSTs, so exchanges are counted too.
WhyThe library answers the token endpoint, but its own token exchange only re-issues a token for the same resource, with the subject token's scopes or fewer. The store is another resource with its own scope. Catching the grant here adds it without changing how the library answers authorization_code and refresh_token.
// /api/docs-store/*: the document store, the downstream API the demo's MCP server calls with a token it got by// token exchange (RFC 8693), served by the demo Worker (demo/src/token-exchange.ts). It accepts only a token issued// for its own audience; no cookies go through.import { forwardToDemo, typeDemoMcpEnv } from"../../_lib/demo-mcp";
The store, through the site Module load
WhatThe comment says this route is the document store, served by the demo Worker, which accepts only a token issued for the store's audience and receives no cookies. The file imports forwardToDemo from functions/_lib/demo-mcp.ts.
WhyThe demo Worker has no public URL. The site forwards the store's requests to it with the request's own URL, so the audience the store checks is on the site's origin.
WhatonRequest calls forwardToDemo without the consent argument, so consent is false. The forwarder passes on the caller's headers except any X-Demo-* header, X-Client-Address and Cookie, sets X-Client-Address from CF-Connecting-IP and X-Demo-Keep (always '0' in this repository), and sends the request to the Worker through the DEMO service binding.
WhyThe Authorization header reaches the Worker unchanged, and nothing a caller sends can claim a demo account, because the store identifies the caller only by the token. oauthRoute counts requests by the address set here.