MCP server · Authorize and consent · /oauth/authorize · stage 1 of 1
The consent page
When an MCP client sends the visitor's browser to /oauth/authorize, the library validates the request (client, redirect URI, resource, PKCE). This code then finds the visitor's demo account (their row in the demos table) from the access key in the browser's demo cookie and shows the consent page. The page says which app is asking and where the access will be sent; the visitor ticks what the app may do. On Allow, the library writes a grant, its record of what this app may do for this account, kept in the KV store OAUTH_KV. The grant's user is the demo account and its props (the private data the library attaches to the grant) hold only the account's id. The browser is then redirected to the client with an authorization code, which the client exchanges at the token endpoint.
Explained in Ep 2: The client's state check: the redirect belongs to its own request From MCP deep dive, Ep 2: OAuth Deep Dive with an MCP Server (OAuth 2.1, PKCE)
demo/src/oauth.ts175 / 175 lines on this page explainedlines 32-38,80-81,138-144,173-331 of 391; the rest are on other stage pages
demo/src/mcp.ts3 / 3 lines on this page explainedlines 20-22 of 516; 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
demo/src/oauth.ts The OAuth side of the demo Worker: the scope wording, the scopes the authorization server accepts (scopesSupported), the route to the authorization endpoint and the whole consent page.
/** What each permission means, as the consent page and the demo page say it. */exportconstSCOPE_WORDS: Record<string, string> = { [READ]: 'Search, ask and read your uploaded documents', [WRITE]: 'Remove a file from your demo',}
What each scope means, in words Module load
WhatMaps docs:read and docs:write to the sentences a visitor reads. offline_access has no entry.
WhyOne table feeds both places a visitor reads a permission: the consent page's checkboxes and the demo page's Connected apps list (appsOf). appsOf shows only scopes that have an entry, so offline_access never appears in Connected apps. The consent page never shows it either, because it draws exactly two boxes, docs:read and docs:write.
docs:read → "Search, ask and read your uploaded documents"docs:write → "Remove a file from your demo"
Explained in Ep 3: docs:read and docs:write, and the words the consent page shows From MCP deep dive, Ep 3: MCP Authorization Deep Dive: Scopes, Step-Up and Token Exchange
WhatThe authorization server is constructed with scopesSupported [docs:read, docs:write, offline_access]. serversFor builds it once per origin, on that origin's first request.
WhyThe library publishes this list as scopes_supported in the authorization server metadata (RFC 8414), and approveConsent refuses with invalid_scope any approved scope that is not in it. Whatever a tampered consent form posts, a grant can hold only these three scopes.
// The consent page can make the Worker fetch a client's metadata document, so it is limited by address too.if (pathname === '/oauth/authorize') {if (!(awaitanonymousAllowed(request, env))) returntooMany()returnauthorize(request, env, api(env, origin)) }
The authorization endpoint is ours MCP request
WhatEvery request to /oauth/authorize, whatever its method, is counted against the caller's address (120 a minute, PER_MINUTE_ANONYMOUS in mcp.ts) and answered 429 over the limit. Otherwise it goes to authorize() with the library's helpers for this request's origin.
WhyThe library's role-based API leaves the interactive authorization route to the application; its fetch() serves only the protocol endpoints. The endpoint needs the limit because anyone can call it, and parseAuthRequest can make the Worker fetch a Client ID Metadata Document from a URL the caller chose.
PER_MINUTE_ANONYMOUS = 120 (mcp.ts)over the limit: 429, Retry-After: 60
// Makes text safe to put in HTML.constescape = (value: string) => value.replace(/[&<>"']/g, (char) =>`&#${char.charCodeAt(0)};`)
Five characters become character references MCP request
WhatReplaces each of & < > " ' with its numeric character reference (& < > " ').
WhyThe consent page interpolates strings a client controls: its registered name, its client_id's host and its redirect URI's host. Escaping all five characters makes those strings safe as element text and inside a double- or single-quoted attribute, so a client named <script>… shows as text. The function is not safe for an unquoted attribute, a URL attribute or a script, and the page puts no value in any of those.
/** A page of the site's own look, for the consent form and what is said in its place. Never indexed, never framed. */functionpage(title: string, body: string, status = 200, headers = newHeaders()): Response {// No caching, no framing and no indexing. headers.set('Content-Type', 'text/html; charset=utf-8') headers.set('Cache-Control', 'no-store') headers.set('X-Frame-Options', 'DENY') headers.set('X-Robots-Tag', 'noindex')
Headers: no cache, no frame, no index MCP request
WhatSets Content-Type, Cache-Control: no-store, X-Frame-Options: DENY and X-Robots-Tag: noindex on the headers passed in, or on a new Headers object.
WhyX-Frame-Options: DENY stops another site from loading the page in an invisible frame and tricking the visitor into clicking Allow (clickjacking). For the consent form, the headers passed in are beginConsent's. They already carry Content-Security-Policy: frame-ancestors 'none', the same rule for current browsers, and the handle's binding cookie. Cache-Control: no-store keeps a page holding a one-use handle out of every cache.
// The page itself, in the site's style.returnnewResponse(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${escape(title)} | Joel Stevick</title><link rel="stylesheet" href="/site.css">
The document head MCP request
WhatAn HTML5 document with a viewport meta, a robots noindex meta, the escaped title followed by "| Joel Stevick", and a stylesheet link to /site.css.
WhyThe title can hold the client's name, so it goes through escape like the body's values. /site.css resolves on the serving origin, which is the site's, because the Worker answers at the site's URL through the site's Pages Functions. The stylesheet belongs to the site and is not in this repository.
WhatA centred column at most 34rem wide, one label per line, the two buttons in a flex row with Allow filled blue (#1f6feb), and an amber left border (#d29922) on the warning paragraph.
WhyWith the styles inline, the page needs no file besides site.css. Allow and Deny have the same padding and border; only Allow's fill colour sets it apart.
/** Said when the browser has no demo: nothing is granted. */constneedDemo = () => page('Open your demo first', `<h1>Open your demo first</h1><p>An app is asking to use the documents in your demo, but this browser has no demo open.</p><p><a href="/demo">Open your demo</a> in this browser (or <a href="/register?for=demo">start one</a>), then go back to the app and connect again.</p>`, 401)
The 'Open your demo first' page MCP request
WhatA 401 page saying the browser is not signed in to a demo account. It links to /demo and to /register?for=demo and asks the visitor to connect again from the app afterwards.
WhyThe authorization server has no sign-in of its own; the user is whichever demo account the cookie's access key matches. With no account there is no user to grant access for, so no grant is created and the browser is not redirected to the client. The visitor signs in to their demo account on the demo page and starts the connection again from the app, which sends a new authorization request.
/** The consent form: every value that came from the client is escaped. */functionconsentPage(details: ConsentDescription, handle: string): string {
Signature MCP request
WhatTakes the ConsentDescription from describeConsent and the handle from beginConsent; returns the body markup.
WhyThe library documents every string in ConsentDescription as possibly client-supplied (from dynamic registration or a Client ID Metadata Document). consentPage() therefore escapes every value that came from the client.
// The app's name, and who published it if that is known.const name = escape(details.clientName || 'An app')const who = details.clientDomain ? `Published by <strong>${escape(details.clientDomain)}</strong>.` : 'This app registered itself, so its name is not verified.'
The app's name, and whether it is verified MCP request
Whatname is the escaped clientName. who reads "Published by <domain>" when clientDomain is set, and otherwise "This app registered itself, so its name is not verified."
WhyclientDomain is set only for a Client ID Metadata Document client. It is the host of the client's HTTPS client_id, a domain the client must control to serve that document. A dynamically registered client's name is whatever the client sent, so the page says the name is unverified. describeConsent falls back to the client_id when no name was given, so the 'An app' fallback does not occur in practice.
// The form: who is asking, where the access goes, and a box for each permission.return`<h1>Allow ${name} to use your demo's documents?</h1><p>${who} The access will be sent to <strong>${escape(details.redirectHost)}</strong>.</p>${details.redirectIsLoopback ? '<p class="warn"><strong>This sends access to an app on your computer.</strong> Continue only if you just started connecting from it.</p>' : ''}
Who is asking and where the access goes MCP request
WhatThe heading asks whether to allow the named app. The next line names the redirect URI's host, where the authorization code will be sent. A redirect to a loopback host (localhost, 127.0.0.0/8, ::1) adds a warning paragraph.
WhyThe redirect host is the one fact the client cannot misrepresent, because the library has already matched the redirect URI against the client's registered URIs. A loopback redirect reaches whatever local process listens on that port, whatever name the client claims, so the warning tells the visitor to continue only if they just started the connection.
The form, the handle and the refresh request MCP request
WhatA POST form with no action attribute, so it posts back to the same URL. It carries the handle in a hidden field and, when the client asked for offline_access, a hidden offline=1.
WhyThe handle is 256 random bits naming the encrypted request that the library stored in KV for 10 minutes. The handle works only with the __Host- binding cookie that beginConsent set in this browser. That cookie is SameSite=Lax, so a cross-site form post does not carry it, which protects the form against CSRF. The POST handler never reads the query string again; the request it approves is the stored one.
WhatReading is a checked, disabled checkbox with no name; removing a file is an unticked checkbox named scope with value docs:write.
WhyBrowsers never submit a disabled input, so authorize() adds docs:read itself. The docs:write box is shown unticked whether or not the client asked for it, so the visitor decides whether the app may delete files. The MCP server asks for docs:write only when remove_file needs it (step-up).
<p>You can disconnect it at any time on your <a href="/demo">demo page</a>.</p> <p class="buttons"><button name="decision" value="approve">Allow</button> <button name="decision" value="deny">Deny</button></p></form>`}
Disconnect, Allow, Deny MCP request
WhatA line saying the app can be disconnected on the demo page, then two submit buttons named decision, with the values approve and deny.
WhyThe decision travels as the submitting button's name and value. authorize() treats any post without decision=approve as a denial, so a post that names no decision grants nothing.
The consent page Claude Code opened in the browser, served by the demo Worker at /oauth/authorize. It shows the app's name from its client metadata document and the host the access is sent to. docs:read is ticked and cannot be cleared. docs:write is unticked, and the visitor leaves it so and presses Allow. 2026-11-29, joelstevick.com in Chrome, opened from Claude Code's sign-in
/** What the site records of a decision (never forwarded to the browser): the demo, the decision and the scopes. */functiondecided(headers: Headers, demo: Demo, decision: string, scopes: string[]): Headers {
Signature MCP request
WhatTakes the response headers, the account's row (demo), the decision word and the scopes; returns the same headers with more set.
WhyThe site records the decision because the site's visitor events are in its own database, which the Worker does not write to.
WhatSets X-Demo-Id, and X-Demo-Email when the account's contact has an address (both from about), then X-Mcp-Grant (allowed or denied) and X-Mcp-Scopes, the scopes space-separated without offline_access.
WhyforwardToDemo in functions/_lib/demo-mcp.ts records a demo_mcp_grant event from these headers and deletes all four before the 302 reaches the browser. The client therefore never sees the account's id or address in a header. No token or code is recorded.
/** * The authorization endpoint. GET shows the consent page and grants nothing; POST is the visitor's * decision. The visitor is the demo their cookie names, and nothing in the client's request can * name another: the grant is written for that demo and holds only the scopes they ticked. */
The contract Never runs
WhatGET shows the page and grants nothing; POST is the decision. The user is the demo account the cookie's access key matches, and the grant holds only the ticked scopes.
WhyNothing in the client's request names a demo account. The identity comes only from the X-Demo-Key header, which the site sets from the cookie after removing any X-Demo- header a caller sent.
if (request.method === 'GET') {// The library checks the client, its redirect address, the resource and PKCE before anything is shown.const asked = await oauth.parseAuthRequest(request)
The library validates the request MCP request
WhatparseAuthRequest checks that the request arrived at the configured authorize endpoint and looks the client up, fetching its metadata document when client_id is an HTTPS URL. It matches redirect_uri exactly against the client's registered URIs, except that for a loopback URI it accepts any port when scheme, host, path and query match, as RFC 8252 allows. It resolves resource to /mcp/demo and checks response_type and PKCE (S256 only; required of public clients).
WhyIt runs before the cookie is read, so a malformed request or an unknown client is rejected before anything about the visitor is looked up. Every later step uses the validated AuthRequest it returns.
Explained in Ep 2: The authorization request, the PKCE code challenge and consent From MCP deep dive, Ep 2: OAuth Deep Dive with an MCP Server (OAuth 2.1, PKCE)
// Nothing is shown without a demo open in this browser.const demo = awaitsignedIn(request, env)if (demo === null) returnneedDemo()
No account, no page MCP request
WhatsignedIn hashes the X-Demo-Key header with SHA-256 and selects the unpurged demo account with that key_hash; with none, the needDemo page is returned.
WhyThe cookie reaches the Worker only on this path. forwardToDemo passes the browser's cookies through for /oauth/authorize alone and adds X-Demo-Key, which holds the demo cookie's key.
// Describe the app, and see how many are already connected.const details = await oauth.describeConsent(asked)const apps = (await oauth.listUserGrants(demo.id)).items
Describe the app, list the account's grants MCP request
WhatdescribeConsent returns the client's name, its verified domain (metadata-document clients only), the redirect URI and its host, whether that host is loopback, and the requested scopes. listUserGrants(demo.id) lists this account's grants from KV.
WhyGrants are stored under grant:<userId>:<grantId>, and userId is the account's id, so listing one KV prefix returns exactly this account's connected apps.
// An app already connected is replaced by its new grant; a new one needs room.if (apps.length >= MAX_APPS && !apps.some((app) => app.clientId === asked.clientId && app.redirectUri === asked.redirectUri)) {returnpage('Too many connected apps', `<h1>Too many connected apps</h1><p>This demo already has ${MAX_APPS} apps connected. Disconnect one on your <a href="/demo">demo page</a>, then connect again.</p>`, 409) }
At most five apps MCP request
WhatWith 5 or more grants, none of them for the same client_id and redirect URI, the visitor gets a 409 page asking them to disconnect an app first.
WhyA reconnecting app is let through because completeAuthorization revokes the client's earlier grant for the same resource when it writes the new one. The count includes grants whose code has not been redeemed yet; those expire from KV after 10 minutes.
// Show the consent form.const consent = await oauth.beginConsent(asked)returnpage(`Allow ${details.clientName || 'an app'}`, consentPage(details, consent.handle), 200, consent.headers) }
Begin the transaction, show the form MCP request
WhatbeginConsent stores the validated request in KV, encrypted, under the SHA-256 of a new random handle. It returns the handle and headers: a __Host- binding cookie, no-store, frame-ancestors 'none' and X-Frame-Options: DENY. The page is sent with those headers.
WhyOnly the holder of the handle can decrypt the record, and only the browser holding the matching cookie can use the handle, within 10 minutes. The library deletes the record on first use, though not atomically (a KV get, then a delete); the binding cookie confines any double use to the browser that started the flow. Nothing has been granted yet.
handle: 32 random bytes, base64urltransaction TTL: 600 s (library)
// The decision: the visitor must still have a demo open.const demo = awaitsignedIn(request, env)if (demo === null) returnneedDemo()
Still signed in at decision time MCP request
WhatThe demo account is looked up again from the cookie's access key; with none, the needDemo page.
WhyThe transaction does not record which account saw the page, so the grant is written for the account the cookie's key matches when Allow is pressed. If that account was purged or given a new key in between, nothing is granted.
// Anything but Allow is a denial, sent back to the app.if (form.get('decision') !== 'approve') {const denied = await oauth.denyConsent(request, handle)returnnewResponse(null, { status: 302, headers: decided(denied.headers, demo, 'denied', []) }) }
Deny MCP request
WhatUnless decision is approve, denyConsent consumes the handle and returns headers whose Location is the client's redirect URI with error=access_denied, the client's state and iss. The response is a 302 with those headers plus the decision headers.
WhyThe redirect URI comes from the stored, validated request, never from the form, so a denial cannot be turned into an open redirect. The client learns that the user refused (RFC 6749 §4.1.2.1), and the site records the denial.
// What is granted is what the visitor ticked: reading always, removing only with its box, offline_access when the client asked.const scope = [READ, ...(form.getAll('scope').includes(WRITE) ? [WRITE] : []), ...(form.get('offline') === '1' ? [OFFLINE] : [])]const approved = await oauth.approveConsent(request, handle, { scope })
The scopes the visitor ticked MCP request
WhatThe granted scopes are docs:read always, docs:write when its box was ticked, and offline_access when the form carried offline=1. approveConsent checks the handle against this browser's cookie, replaces the request's scopes with these (each must be in scopesSupported), consumes the handle, and returns the approved request and a header that clears the cookie.
WhyapproveConsent accepts fewer or more scopes than the client requested, so the grant holds what the visitor chose. offline_access is added when the client asked for it, but it only appears in the grant's scope list. The library issues a refresh token on every code exchange regardless of scope, because refreshTokenTTL is left at its 30-day default.
always: docs:readrefresh token TTL: 30 days (library default)
Explained in Ep 3: Step-up: the second consent, and scopes from the ticked boxes From MCP deep dive, Ep 3: MCP Authorization Deep Dive: Scopes, Step-Up and Token Exchange
// The cap is checked again here: several consent pages could have been opened at once.const apps = (await oauth.listUserGrants(demo.id)).itemsif (apps.length >= MAX_APPS && !apps.some((app) => app.clientId === approved.request.clientId && app.redirectUri === approved.request.redirectUri)) {returnpage('Too many connected apps', `<h1>Too many connected apps</h1><p>This demo already has ${MAX_APPS} apps connected. Disconnect one on your <a href="/demo">demo page</a>, then connect again.</p>`, 409) }
The cap, again MCP request
WhatThe account's grants are listed again and the same five-app test is applied, this time to the approved request's client and redirect URI. Over the cap, the visitor gets the 409 page.
WhySeveral consent pages opened at once each passed the GET check. This second check narrows that race but cannot close it, because nothing locks the grant list between this read and the write in completeAuthorization. The handle has already been consumed, so the visitor starts again from the app.
const { redirectTo } = await oauth.completeAuthorization({request: approved.request,// The grant's user is the demo, so its grants can be listed and revoked by demo.userId: demo.id,metadata: { name: details.clientName, domain: details.clientDomain ?? null, host: details.redirectHost },scope: approved.request.scope,props: { demo: demo.id } satisfiesProps, })
completeAuthorization writes the grant MCP request
WhatThe library re-checks the client, redirect URI, response type, resource and PKCE. It stores grant:<demo.id>:<grantId> with the approved scopes, the metadata { name, domain, host } and the encrypted props { demo: demo.id }, with a 10-minute expiry until the code is redeemed. It returns the redirect URL carrying a new authorization code, state and iss. It also revokes this client's earlier grants for this account and resource; for a metadata-document client, only those with the same redirect URI.
WhyuserId is the account's id, so one KV prefix lists or revokes all of the account's grants. props reach the resource server with every valid token, and serveMcp serves only ctx.props.demo, so a token can never reach another account's documents. The code and later tokens have the form <userId>:<grantId>:<secret>, so the client sees the account's id. The id is not a credential; the cookie's key is.
grant key: grant:<demo.id>:<grantId>unredeemed grant expiry: 600 s (library)props: { demo: demo.id }
// Send the browser back to the app, with the decision for the site to record. approved.headers.set('Location', redirectTo)returnnewResponse(null, { status: 302, headers: decided(approved.headers, demo, 'allowed', approved.request.scope) })
Back to the client with the code MCP request
WhatLocation on approveConsent's headers is set to redirectTo, and a 302 is returned with the decision headers (allowed, the granted scopes).
WhyThe browser takes the code to the client's redirect URI, and the client exchanges it at /oauth/token with its PKCE code_verifier. approveConsent's Set-Cookie clears the binding cookie in the same response.
Explained in Ep 2: The redirect URI check and the 302 carrying the code and state From MCP deep dive, Ep 2: OAuth Deep Dive with an MCP Server (OAuth 2.1, PKCE)
} catch (error) {// A redirect back to the client is safe only once the library has validated it; everything else is said here.if (error instanceofAuthorizationError && error.redirectTo) returnnewResponse(null, { status: 302, headers: { Location: error.redirectTo } })
Redirect only when the library says it is safe MCP request
WhatAn AuthorizationError with redirectTo set becomes a 302 to that error redirect. The library sets redirectTo only after it has validated the client and redirect URI, as for a bad resource or missing PKCE.
WhyRedirecting to an unvalidated redirect_uri would make the endpoint an open redirector. An error found after validation belongs to the client, which can show it or retry.
if (error instanceofAuthorizationError || error instanceofCimdFetchError) {const message = error instanceofAuthorizationError ? error.description : 'This app could not be verified.'returnpage('This could not be completed', `<h1>This could not be completed</h1><p>${escape(message ?? 'The request was not valid.')}</p><p>Go back to the app and connect again.</p>`, 400) }
Every other error: a 400 page MCP request
WhatAny other AuthorizationError (unknown client, bad redirect URI, missing, unbound, expired or reused handle, unsupported scope) becomes a 400 page with the escaped description, or "The request was not valid." when the error has none. A CimdFetchError (the client's metadata document could not be fetched or validated) becomes the same page with "This app could not be verified."
WhyWithout a validated redirect URI there is nowhere safe to send the browser, so the page tells the visitor to go back to the app. The description is the library's own text, escaped anyway.
// Anything unexpected is passed on.throw error }}
Anything unexpected MCP request
WhatAny other error, such as a KV failure, is rethrown to the caller.
WhyOnly the library's expected validation failures become pages. Anything else is a fault, which the Worker's fetch handler in createApp logs and answers with 500.
/** The scopes a token can carry. `READ` is needed for anything; `WRITE` only to remove a file. */exportconstREAD = 'docs:read'exportconstWRITE = 'docs:write'
docs:read and docs:write Module load
WhatREAD (docs:read) is needed for any MCP request; WRITE (docs:write) is needed only by remove_file.
Whymcp.ts enforces the scopes and defines them. oauth.ts grants them and imports them from mcp.ts, so the two files always use the same names. docs:read is the resource server's requiredScopes. remove_file declares requireScopes(READ, WRITE), so the SDK answers a token without docs:write with a step-up challenge, and the client returns to the consent page to ask for it.