Joel Stevick

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.

oauthRoute(): token exchange over HTTP: Sends an outside POST of this grant to tokenExchange(); the library answers every other grant (outside the flow)oauthRoute():token exchangeover HTTPSends an outsidePOST of this grant totokenExchange(); thelibrary answers everyother grantresources/list handler: Calls filesFromStore() with the caller's MCP tokenresources/listhandlerCallsfilesFromStore() withthe caller's MCPtokenExchange request: Authenticates as mcp-demo-server with HTTP Basic; filesFromStore() passes it in process to tokenExchange()ExchangerequestAuthenticates asmcp-demo-serverwith HTTP Basic;filesFromStore()passes it in processto tokenExchange()Client check: Compares the client secret in constant timeClient checkCompares the clientsecret in constanttimeSubject token check: Must be a live /mcp/demo token with docs:readSubject tokencheckMust be a live/mcp/demo tokenwith docs:readStore token issued: Lasts at most 300 s; KV keeps only its SHA-256 hashStore tokenissuedLasts at most 300 s;KV keeps only itsSHA-256 hashGET /api/docs-store/files: Checks the token's audience, expiry and scopeGET/api/docs-store/filesChecks the token'saudience, expiry andscopeThe user's files: Selects the files whose demo_id is the token's subThe user's filesSelects the fileswhose demo_id isthe token's subAn MCP access token sent directly to the store has no record under exchanged:<hash>, so the store refuses it with 401 invalid_token.An MCP access token sent directly to the store has no record under exchanged:<hash>, so the store refuses it with 401 invalid_token.
Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
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

Pinned to joelstevick-demo-rag-pipeline at 6a9c6c7.

demo/src/token-exchange.ts The exchange, the document store and the MCP server as a client.

Module scope

module · lines 1–33View on GitHub

The licence, what the module is for, its imports and the environment it reads.

// Copyright (c) 2026 Joel Stevick// SPDX-License-Identifier: MIT// Licensed under the MIT License: https://opensource.org/licenses/MIT

Licence Never runs

WhatThe MIT licence header, as on every file of the public repository.

WhyThe repository is published to be read and reused, and the header states the terms.

/** * 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.

import { json, sha256, type Env } from './app'import { validateMcpToken } from './oauth'import { READ } from './mcp'

Imports Module load

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). */export type ExchangeEnv = 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.

secret: DOCS_STORE_CLIENT_SECRET

TOKEN_EXCHANGE, ACCESS_TOKEN_TYPE

constants · lines 34–37View on GitHub

The two URNs from RFC 8693 that this exchange uses.

/** The grant type and token type RFC 8693 defines (sections 2.1 and 3). */export const TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange'export const ACCESS_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

EXCHANGE_CLIENT, STORE_SCOPE, EXCHANGED_LIFETIME

constants · lines 38–44View on GitHub

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. */export const EXCHANGE_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).

EXCHANGE_CLIENT = 'mcp-demo-server'

/** The one scope the store knows: reading the list of the user's files. */export const STORE_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.

STORE_SCOPE = 'documents:read'

/** How long an exchanged token lasts, in seconds: long enough for one call, never longer than the token it came from. */export const EXCHANGED_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).

EXCHANGED_LIFETIME = 300 s

storeResource(), kvKey()

functions · lines 45–49View on GitHub

The store's address, which is its audience, and the KV key of an exchanged token.

Called by docsStoreRoute() filesFromStore() tokenExchange()

/** The store's address, which is also its audience: the `resource` an exchange must name. */export const storeResource = (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.

https://joelstevick.com/api/docs-store

/** Where exchanged tokens are kept, by the hash of the token. */const kvKey = (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.

Exchanged

interface · lines 50–60View on GitHub

What is stored for an exchanged token.

/** What is stored for an exchanged token. `sub` is the user: the demo whose files the token may read. */interface Exchanged {  sub: string  client_id: string  /** The app the person connected, whose token was exchanged; kept so a record shows who acted for whom. */  subject_client_id: string  aud: string  scope: string  exp: 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.

oauthError()

function · lines 61–67View on GitHub

The token endpoint's error response.

Called by tokenExchange()Calls json() Shared helpers

// ─── 1. THE EXCHANGE ─────────────────────────────────────────────────────────────────────────────────────────────

1. The exchange Never runs

WhatA divider comment that opens the first of the module's three parts, the exchange at the token endpoint.

WhyThe module is laid out top to bottom in the order a request meets its three parts.

/** An error from the token endpoint in RFC 6749 section 5.2's shape. Never cached. */function oauthError(status: number, error: string, description: string, extra: Record<string, string> = {}): Response {  return json(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.

sameSecret()

async function · lines 68–73View on GitHub

Compares the presented client secret with the expected one in constant time.

Called by tokenExchange()

/** Whether two strings are equal, in time that does not depend on where they differ. Both are hashed first, so the lengths match. */async function sameSecret(given: string, expected: string): Promise<boolean> {  const [a, b] = await Promise.all([given, expected].map((text) => crypto.subtle.digest('SHA-256', new TextEncoder().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.

clientCredentials()

function · lines 74–97View on GitHub

Reads the client's id and secret from HTTP Basic or from the form.

Called by tokenExchange()

/** * 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. */function clientCredentials(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.

  if (header.startsWith('Basic ')) {    if (posted) return 'both'    // Basic is base64("id:secret"), each part form-urlencoded first (RFC 6749 section 2.3.1).    let decoded = ''    try { decoded = atob(header.slice(6).trim()) } catch { return null }    const colon = decoded.indexOf(':')    if (colon < 0) return null    try {      return { id: decodeURIComponent(decoded.slice(0, colon).replace(/\+/g, ' ')), secret: decodeURIComponent(decoded.slice(colon + 1).replace(/\+/g, ' ')) }    } catch { return null }  }

HTTP Basic MCP 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.

Authorization: Basic base64(id:secret)

  if (posted) return { id: form.get('client_id') ?? '', secret: form.get('client_secret') ?? '' }  return null}

Or the form MCP request

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.

isTokenExchange()

async function · lines 98–102View on GitHub

Whether a token request asks for token exchange.

Called by oauthRoute(): token exchange

/** Whether a token request asks for token exchange. Read from a copy, so the library still gets the whole body otherwise. */export async function isTokenExchange(request: Request): Promise<boolean> {  return new URLSearchParams(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.

tokenExchange()

async function · lines 103–163View on GitHub

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.

Called by filesFromStore() oauthRoute(): token exchangeCalls base64url() clientCredentials() oauthError() sameSecret() storeResource(), kvKey() validateMcpToken() json() Shared helpers sha256() Shared helpers

/** * `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. */export async function tokenExchange(request: Request, env: ExchangeEnv, origin: string): Promise<Response> {  // The token endpoint takes a form body (RFC 6749 section 3.2).  const form = new URLSearchParams(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') return oauthError(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 === '' || !(await sameSecret(client.secret, expected))) {    // 401 with a Basic challenge, as RFC 6749 section 5.2 asks of invalid_client.    return oauthError(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.

400 invalid_request401 invalid_clientWWW-Authenticate: Basic realm="joelstevick.com"

  // 2. The parameters RFC 8693 section 2.1 defines, as far as this server supports them.  const subjectToken = form.get('subject_token') ?? ''  if (subjectToken === '') return oauthError(400, 'invalid_request', 'subject_token is required.')  if (form.get('subject_token_type') !== ACCESS_TOKEN_TYPE) return oauthError(400, 'invalid_request', `subject_token_type must be ${ACCESS_TOKEN_TYPE}.`)  if (form.has('actor_token')) return oauthError(400, 'invalid_request', 'actor_token is not supported.')  const requested = form.get('requested_token_type')  if (requested !== null && requested !== ACCESS_TOKEN_TYPE) return oauthError(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.

subject_token_type = urn:ietf:params:oauth:token-type:access_token

  // 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) return oauthError(400, 'invalid_request', `resource is required: ${store}.`)  if (targets.some((target) => target !== store)) return oauthError(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.

resource = https://joelstevick.com/api/docs-store400 invalid_target

  // 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)) return oauthError(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 = await validateMcpToken(env, origin, subjectToken)  if (subject === null) return oauthError(400, 'invalid_request', 'subject_token is not a valid access token for the MCP server.')  if (!subject.scope.includes(READ)) return oauthError(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.

400 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) return oauthError(400, 'invalid_request', 'subject_token has expired.')  const accessToken = base64url(crypto.getRandomValues(new Uint8Array(32)))  const record: 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(await sha256(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.

32 random bytesKV expirationTtl ≥ 60 s

  // 5. The answer RFC 8693 section 2.2.1 defines.  return json(200, {    access_token: accessToken,    issued_token_type: ACCESS_TOKEN_TYPE,    token_type: 'Bearer',    expires_in: expiresIn,    scope: STORE_SCOPE,  }, { 'Cache-Control': 'no-store', Pragma: 'no-cache' })}

The response MCP request

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.

token_type: Bearerexpires_in ≤ 300

base64url()

function · lines 164–166View on GitHub

Encodes bytes as base64url without padding.

Called by tokenExchange()

// Bytes as base64url without padding.const base64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')

Bytes to base64url, without padding MCP request

WhatEncodes the bytes as standard base64 with btoa, then converts the result to the URL-safe alphabet and drops the = padding.

Whybase64url needs no escaping in a header or a URL, which is why OAuth tokens commonly use it. 32 bytes become 43 characters.

challenge()

function · lines 167–174View on GitHub

The store's refusal, with a Bearer challenge.

Called by docsStoreRoute()Calls json() Shared helpers

// ─── 2. THE DOCUMENT STORE ───────────────────────────────────────────────────────────────────────────────────────

2. The document store Never runs

WhatA divider comment that opens the second part, the downstream API that accepts only an exchanged token.

WhyThe module is laid out top to bottom in the order a request meets its three parts.

/** A refusal with the Bearer challenge of RFC 6750 section 3; no error code when no token was sent at all. */function challenge(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}"`] : [])]  return json(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.

docsStoreRoute()

async function · lines 175–200View on GitHub

GET /api/docs-store/files returns the calling user's files.

Called by filesFromStore() oauthRoute(): the document storeCalls challenge() storeResource(), kvKey() json() Shared helpers sha256() Shared helpers

/** * `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. */export async function docsStoreRoute(request: Request, env: ExchangeEnv, origin: string): Promise<Response> {  const { pathname } = new URL(request.url)  if (pathname !== '/api/docs-store/files') return json(404, { error: 'not found' })  if (request.method !== 'GET') return json(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).

  // The bearer token (RFC 6750 section 2.1).  const header = request.headers.get('Authorization') ?? ''  if (!/^Bearer\s+\S+$/i.test(header)) return challenge(401)  const token = header.replace(/^Bearer\s+/i, '')

The bearer token MCP request

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(await sha256(token)), 'json')  if (found === null || found.aud !== storeResource(origin)) return challenge(401, 'invalid_token', 'The token was not issued for this API.')  if (found.exp <= Math.floor(Date.now() / 1000)) return challenge(401, 'invalid_token', 'The token has expired.')  if (!found.scope.split(' ').includes(STORE_SCOPE)) return challenge(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.

401 invalid_token403 insufficient_scope

  // 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>()  return json(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.

StoredFile

interface · lines 201–203View on GitHub

A file as the store lists it.

/** A file as the store lists it: its id, name and page count. */export interface StoredFile { id: number; name: string; pages: number }

A file's id, name and page count Type only

WhatA file's rowid, its stored name and its page count.

WhyThese are the same three fields as mcp.ts's FileRow, so the resource list builds each entry's URI, name and description from the store's response.

filesFromStore()

async function · lines 204–234View on GitHub

The MCP server as a client: exchange the caller's token, then call the store with the new one.

Called by build(): RESOURCES Files and pagesCalls docsStoreRoute() storeResource(), kvKey() tokenExchange()

// ─── 3. THE MCP SERVER AS A CLIENT ───────────────────────────────────────────────────────────────────────────────

3. The MCP server as a client Never runs

WhatA divider comment that opens the third part, where the MCP server uses the first two.

WhyThe module is laid out top to bottom in the order a request meets its three parts.

/** * 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. */export async function filesFromStore(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.

  // The exchange, authenticated with the MCP server's client secret (HTTP Basic).  const exchanged = await tokenExchange(new Request(`${origin}/oauth/token`, {    method: 'POST',    headers: {      'Content-Type': 'application/x-www-form-urlencoded',      Authorization: `Basic ${btoa(`${EXCHANGE_CLIENT}:${env.DOCS_STORE_CLIENT_SECRET ?? ''}`)}`,    },    body: new URLSearchParams({      grant_type: TOKEN_EXCHANGE,      subject_token: mcpToken,      subject_token_type: ACCESS_TOKEN_TYPE,      resource: storeResource(origin),      scope: STORE_SCOPE,    }),  }), env, origin)  if (!exchanged.ok) throw new Error(`token exchange failed: ${exchanged.status} ${await exchanged.text()}`)  const { access_token } = (await exchanged.json()) as { access_token: string }

The exchange request MCP request

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.

grant_type = urn:ietf:params:oauth:grant-type:token-exchangeresource = https://joelstevick.com/api/docs-storescope = documents:read

  // The store, called as the same user with the new token.  const listed = await docsStoreRoute(new Request(`${storeResource(origin)}/files`, { headers: { Authorization: `Bearer ${access_token}` } }), env, origin)  if (!listed.ok) throw new Error(`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.

demo/src/oauth.ts The subject-token check, the document store's route and the exchange caught before the library.

validateMcpToken()

function · lines 117–124View on GitHub

An MCP access token checked exactly as the MCP endpoint checks it.

Called by tokenExchange()Calls serversFor(): DISCOVERY The discovery documents

/** * 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). */export const validateMcpToken = (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.

resource = https://joelstevick.com/mcp/demo

oauthRoute(): the document store

async function · lines 157–162View on GitHub

Requests to /api/docs-store go to the store after the address count.

Calls docsStoreRoute() anonymousAllowed() Token validation and limits tooMany Token validation and limits

  // 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 (!(await anonymousAllowed(request, env))) return tooMany()    return docsStoreRoute(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.

PER_MINUTE_ANONYMOUS = 120

oauthRoute(): token exchange

async function · lines 166–168View on GitHub

oauthRoute answers a token-exchange grant before the library sees it.

Calls isTokenExchange() tokenExchange()

  // 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' && (await isTokenExchange(request))) return tokenExchange(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.

functions/api/docs-store/[[path]].ts The site's Pages Function for the store.

Module scope

module · lines 1–9View on GitHub

The Pages Function for /api/docs-store/*.

// Copyright (c) 2026 Joel Stevick// SPDX-License-Identifier: MIT// Licensed under the MIT License: https://opensource.org/licenses/MIT

Licence Never runs

WhatThe MIT licence header.

WhyThe same header as on every file of the public repository.

// /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, type DemoMcpEnv } 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.

onRequest

function · lines 10–10View on GitHub

Forwards every request under /api/docs-store to the demo Worker.

Calls forwardToDemo() The Pages Functions

export const onRequest: PagesFunction<DemoMcpEnv> = ({ request, env }) => forwardToDemo(request, env);

Forward, without cookies MCP request

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.