Joel Stevick

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.

parseAuthRequest(): the library checks the client, the redirect URI, the resource and PKCE (S256)parseAuthRequest()the library checks theclient, the redirectURI, the resourceand PKCE (S256)Visitor's demo account: signedIn() finds it by the SHA-256 hash of the access key in X-Demo-Key; no live account gets 401Visitor's demoaccountsignedIn() finds it bythe SHA-256 hash ofthe access key inX-Demo-Key; no liveaccount gets 401Five-app cap: a new app past five connected apps gets 409Five-app capa new app past fiveconnected apps gets409Consent page: names the app and where the access goes; a checkbox per permission, docs:read always onConsent pagenames the app andwhere the accessgoes; a checkbox perpermission,docs:read always onVisitor's demo account, again: signedIn() runs again; no live account gets 401Visitor's demoaccount, againsignedIn() runsagain; no liveaccount gets 401Allow: approves docs:read, and docs:write if tickedAllowapproves docs:read,and docs:write iftickedDeny: redirects to the client with error=access_deniedDenyredirects to the clientwitherror=access_deniedFive-app cap, again: checked again, since pages opened at once could each pass the first check; over it, 409Five-app cap,againchecked again, sincepages opened atonce could eachpass the first check;over it, 409completeAuthorization(): writes the grant with the demo account's id as its usercompleteAuthorization()writes the grant withthe demo account'sid as its user302 to the client: carries the code, the state and iss302 to the clientcarries the code, thestate and issAn invalid request is redirected to the client only after the library has validated its redirect URI; otherwise authorize() shows the error on a 400 page.An invalid request is redirected to the client only after the library has validated its redirect URI; otherwise authorize() shows the error on a 400page.
Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
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

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

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.

SCOPE_WORDS

constant · lines 32–38View on GitHub

The sentence shown for each permission.

/** What each permission means, as the consent page and the demo page say it. */export const SCOPE_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"

serversFor(): /oauth/authorize

segment · lines 80–81View on GitHub

The scopes the authorization server accepts.

    scopesSupported: [READ, WRITE, OFFLINE],  })

scopesSupported MCP request

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.

scopesSupported = ["docs:read", "docs:write", "offline_access"]

oauthRoute(): /oauth/authorize

segment · lines 138–144View on GitHub

Routes the authorization endpoint to this file's own authorize(), after the per-address limit.

Calls authorize() anonymousAllowed() Token validation and limits api() Tokens and grants tooMany Token validation and limits

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

escape

function · lines 173–174View on GitHub

HTML-escapes a string for element content and quoted attribute values.

Called by authorize() consentPage() page()

// Makes text safe to put in HTML.const escape = (value: string) => value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`)

Five characters become character references MCP request

WhatReplaces each of & < > " ' with its numeric character reference (&#38; &#60; &#62; &#34; &#39;).

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.

page()

function · lines 175–210View on GitHub

Wraps a body in a full HTML page with headers that forbid caching, framing and indexing.

Called by authorize() needDemoCalls escape

/** A page of the site's own look, for the consent form and what is said in its place. Never indexed, never framed. */function page(title: string, body: string, status = 200, headers = new Headers()): 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.  return new Response(`<!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.

<style>  .consent { max-width: 34rem; margin: 3rem auto; padding: 0 1.25rem; }  .consent h1 { font-size: 1.6rem; }  .consent label { display: block; margin: .6rem 0; }  .consent .buttons { display: flex; gap: .75rem; margin-top: 1.5rem; }  .consent button { font: inherit; padding: .6rem 1.2rem; border-radius: .4rem; border: 1px solid currentColor; background: none; cursor: pointer; }  .consent button[value="approve"] { background: #1f6feb; border-color: #1f6feb; color: #fff; }  .consent .warn { border-left: 4px solid #d29922; padding: .5rem .9rem; }</style>

The page's own styles Never runs

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.

max-width: 34remAllow: #1f6febwarning border: #d29922

</head><body><main class="consent"><p><a href="/">Joel Stevick</a></p>${body}</main></body></html>`, { status, headers })}

Body and response MCP request

WhatA main element holding a home link and the body, returned as a Response with the given status (200 by default) and the headers.

WhyThe body is inserted unescaped. Every caller passes markup it built itself, with any client value already escaped (consentPage, the error page).

needDemo

function · lines 211–215View on GitHub

The page shown when the browser is not signed in to a live demo account.

Called by authorize()Calls page()

/** Said when the browser has no demo: nothing is granted. */const needDemo = () => 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.

consentPage()

function · lines 216–237View on GitHub

Builds the consent form from the library's ConsentDescription and the transaction handle.

Called by authorize()Calls escape

/** The consent form: every value that came from the client is escaped. */function consentPage(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&#39;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.

<form method="post">  <input type="hidden" name="handle" value="${escape(handle)}">  ${details.scope.includes(OFFLINE) ? '<input type="hidden" name="offline" value="1">' : ''}

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.

  <label><input type="checkbox" checked disabled> ${escape(SCOPE_WORDS[READ])}</label>  <label><input type="checkbox" name="scope" value="${WRITE}"> ${escape(SCOPE_WORDS[WRITE])}</label>

One box per permission MCP request

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.

decided()

function · lines 238–246View on GitHub

Adds the headers the site reads to record a consent decision.

Called by authorize()Calls about() Shared helpers

/** What the site records of a decision (never forwarded to the browser): the demo, the decision and the scopes. */function decided(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.

  for (const [name, value] of Object.entries(about(demo))) headers.set(name, value)  headers.set('X-Mcp-Grant', decision)  headers.set('X-Mcp-Scopes', scopes.filter((scope) => scope !== OFFLINE).join(' '))  return headers}

Account, decision, scopes MCP request

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.

authorize()

async function · lines 247–331View on GitHub

The authorization endpoint: GET shows the consent page, POST applies the visitor's decision.

Called by oauthRoute(): /oauth/authorizeCalls consentPage() decided() escape needDemo page() json() Shared helpers signedIn() Shared helpers

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

async function authorize(request: Request, env: Env, oauth: OAuthHelpers): Promise<Response> {  try {

Signature MCP request

WhatTakes the request, the bindings and the library's OAuthHelpers for this origin; everything runs inside one try.

WhyThe library reports a bad request by throwing AuthorizationError or CimdFetchError. The catch at the end turns either into a redirect or a page.

    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.

      // Nothing is shown without a demo open in this browser.      const demo = await signedIn(request, env)      if (demo === null) return needDemo()

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)) {        return page('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.

MAX_APPS = 5status 409

      // Show the consent form.      const consent = await oauth.beginConsent(asked)      return page(`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)

    // Only GET and POST are allowed.    if (request.method !== 'POST') return json(405, { error: 'method not allowed' })

GET or POST only MCP request

WhatAny other method is answered 405 with a JSON error.

WhyEvery request past this line is a POST, the form submission.

    // The decision: the visitor must still have a demo open.    const demo = await signedIn(request, env)    if (demo === null) return needDemo()

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.

    // Read the form.    const form = await request.formData()    const handle = String(form.get('handle') ?? '')

Read the form MCP request

WhatParses the urlencoded body and reads handle as a string, empty when absent.

WhyAn empty or unknown handle is not checked here: approveConsent and denyConsent throw AuthorizationError for it, which the catch shows as a page.

    // Anything but Allow is a denial, sent back to the app.    if (form.get('decision') !== 'approve') {      const denied = await oauth.denyConsent(request, handle)      return new Response(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)

    // The cap is checked again here: several consent pages could have been opened at once.    const apps = (await oauth.listUserGrants(demo.id)).items    if (apps.length >= MAX_APPS && !apps.some((app) => app.clientId === approved.request.clientId && app.redirectUri === approved.request.redirectUri)) {      return page('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.

    // Write the grant for this demo.    const details = await oauth.describeConsent(approved.request)

Describe the app for the grant MCP request

WhatdescribeConsent is called on the approved request to get the name, verified domain and redirect host to store with the grant.

WhyThe description from the GET request is not kept. Recomputing it from the stored request gives the same values for the same client.

    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 } satisfies Props,    })

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)    return new Response(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.

  } catch (error) {    // A redirect back to the client is safe only once the library has validated it; everything else is said here.    if (error instanceof AuthorizationError && error.redirectTo) return new Response(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 instanceof AuthorizationError || error instanceof CimdFetchError) {      const message = error instanceof AuthorizationError ? error.description : 'This app could not be verified.'      return page('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.

status 400

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

demo/src/mcp.ts The MCP server: only its two scope names.

READ and WRITE

constant · lines 20–22View on GitHub

The two scope names a token can carry.

/** The scopes a token can carry. `READ` is needed for anything; `WRITE` only to remove a file. */export const READ = 'docs:read'export const WRITE = '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.

READ = "docs:read"WRITE = "docs:write"