MCP server · Connected apps · GET and DELETE /api/grants · stage 1 of 1
Listing and disconnecting apps
The demo page shows the claude mcp add line to copy and the apps the visitor has allowed, read from the OAuth library's grants for the visitor's demo account (their row in the demos table). A grant is the library's record, in the KV store OAUTH_KV, of what one app may do for one account. Disconnect sends DELETE /api/grants with one grant's id. The Worker looks the grant up among this account's apps and revokes it. The library then deletes the grant's access tokens and then the grant, which holds the refresh token's hash. The Worker returns the new list, and the site records the disconnection as an event. The daily idle purge uses the same revocation to disconnect every app of an account at once.
Browser: the visitor's page: demo.html and its module scriptPages Function: the site's server code on Cloudflare Pages, functions/Demo Worker: the private Worker behind the DEMO service binding, demo/src/New to Cloudflare? How these fit together
demo/src/oauth.ts62 / 62 lines on this page explainedlines 30-31,332-391 of 391; the rest are on other stage pages
demo.html51 / 51 lines on this page explainedlines 205-255 of 505; the rest are on other stage pages
functions/api/demo/[[path]].ts3 / 3 lines on this page explainedlines 65-67 of 79; 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
The most apps one demo account can have connected.
/** The most apps one demo can have connected at a time. */exportconstMAX_APPS = 5
MAX_APPS = 5 Module load
WhatExported as 5. The consent page answers 409 when the account already has this many grants, unredeemed ones included. The exception is an app already connected with the same client id and redirect URI, whose new grant replaces its old one.
WhyEach grant is a KV record with its own tokens, and appsOf reads every one of an account's grants on each list; the cap bounds both per account.
/** One connected app as the demo page and /admin list it. */exportinterfaceApp {id: stringname: stringhost: stringcan: string[]allowed_at: number}
What the page is told about an app Type only
Whatid (the grant's id), name, host, can (the permissions in words) and allowed_at (Unix seconds).
WhyIt is a projection of the library's GrantSummary; the client id, user id, redirect URI and resource never leave the Worker. The doc comment also names /admin, the site's admin page, which reads the same list through the Worker's adminDemo.
/** The apps connected to a demo, oldest first. */exportasyncfunctionappsOf(env: Env, demoId: string): Promise<App[]> {// Without the store there are no apps.if (env.OAUTH_KV === undefined) return []
Signature, and no store Site request
WhatTakes the bindings (env) and an account id. Without the OAUTH_KV binding (env.OAUTH_KV, a KV namespace) it returns an empty list.
WhyA deployment without the MCP server still serves the demo page and the admin view; neither fails for lack of the store.
// Load the demo's grants.const grants = (awaitapi(env).listUserGrants(demoId)).items
This account's grants Site request
WhatlistUserGrants(demoId) lists the KV keys under grant:<demoId>: and reads each grant. It returns summaries without secrets (id, clientId, scope, metadata, createdAt, redirectUri, resource and more).
WhyThe consent page wrote every grant with userId set to the account's id, so this prefix holds exactly the account's apps. One call returns one KV list page at KV's default page size, far above MAX_APPS; the library lists further pages only while a page holds none of this account's keys. A grant whose code was never redeemed is listed until it expires from KV after 10 minutes.
// Turn each grant into what the page shows, oldest first.return grants .map((grant) => {const meta = (grant.metadata ?? {}) as { name?: string; domain?: string | null; host?: string }return {id: grant.id,name: String(meta.name ?? 'An app').slice(0, 120),host: String(meta.domain ?? meta.host ?? '').slice(0, 120),can: grant.scope.filter((scope) => scope inSCOPE_WORDS).map((scope) =>SCOPE_WORDS[scope]),allowed_at: grant.createdAt, } })
Each grant as an App Site request
Whatname is the stored metadata name, else "An app". host is the verified domain, else the redirect host. Both are cut to 120 characters. can keeps only the scopes that have a SCOPE_WORDS entry, which drops offline_access, and maps each to its sentence. allowed_at is the grant's createdAt.
WhyThe consent page wrote the metadata from describeConsent, so the name may be one the client asserted about itself. appsOf cuts it, and the page inserts it as text, never as markup. Showing the verified domain first matches what the consent page said under "Published by".
WhyKV lists keys in lexicographic order, here the order of random grant ids, and the reads finish in any order. Sorting by creation time gives the page a stable order.
/** Disconnects every app from a demo: its grants and their tokens are revoked by the library. */exportasyncfunctionrevokeGrants(env: Env, demoId: string): Promise<void> {// Without the store there is nothing to revoke.if (env.OAUTH_KV === undefined) return
Signature, and no store Scheduled
WhatTakes the bindings and an account id; without OAUTH_KV there is nothing to revoke.
WhyIts only caller is purge() in app.ts, the daily job that deletes the documents of a demo account idle for 10 days.
const oauth = api(env)for (const grant of (await oauth.listUserGrants(demoId)).items) await oauth.revokeGrant(grant.id, demoId)}
Revoke each grant Scheduled
WhatrevokeGrant is called on each grant in turn, for the one page listUserGrants returns (the cursor is not followed; MAX_APPS keeps the list to a handful). It deletes every access token under token:<demoId>:<grantId>: and then the grant itself, which holds the refresh token's hash.
Whypurge() calls this after deleting the account's vectors and before the D1 batch that deletes its chunks, files and unconsented questions. If revocation throws, those rows stay, the account is still selected as idle with files, and the next day's run retries. An account's chunks are therefore never deleted while an app still holds a token.
/** The demo page's Connected apps: GET lists them, DELETE { id } disconnects one of this demo's. */exportasyncfunctiongrantsRoute(request: Request, env: Env, demo: Demo): Promise<Response> {// Without the store the page shows no apps and says the feature is off.if (env.OAUTH_KV === undefined) returnjson(200, { apps: [], available: false })
Signature, and the feature switched off Site request
WhatThe router calls it for GET and DELETE /api/grants with the demo account the cookie's access key matches. Without OAUTH_KV it answers 200 with no apps and available: false.
WhyWith available: false, the page hides the whole Use it from Claude Code box instead of showing a command that would fail.
// GET lists the apps.if (request.method === 'GET') returnjson(200, { apps: awaitappsOf(env, demo.id), available: true })
GET: the list Site request
WhatReturns { apps, available: true }.
WhyThe router finds the demo account with signedIn, from the access key the site forwards from the demo cookie, never from a parameter the page sends, so the page cannot ask for another account's list.
// DELETE: find the app named in the body among this demo's.const body = (await request.json().catch(() => ({}))) as { id?: unknown }const app = (awaitappsOf(env, demo.id)).find((one) => one.id === body.id)
DELETE: find the id among this account's apps Site request
WhatReads the JSON body (an unparsable body reads as {}) and looks for an app in this account's list whose id equals body.id.
WhyStrict equality against ids from this account's own list means a missing, non-string or foreign id matches nothing. One input is not guarded against: a body of literal null parses, and reading body.id then throws whenever the account has at least one app, so the request fails instead of answering 404.
Explained in Ep 3: Disconnect: revoking a grant and every token from it From MCP deep dive, Ep 3: MCP Authorization Deep Dive: Scopes, Step-Up and Token Exchange
// Only a grant of this demo: an id from another demo's list finds nothing here.if (app === undefined) returnjson(404, { error: 'That app is not connected to your demo.' })
Not this account's: 404 Site request
WhatWith no match, 404 "That app is not connected to your demo."
WhyrevokeGrant keys the deletion by the user id passed in, so a foreign grant id would delete nothing anyway. The lookup turns that case into a clear error instead of a silent success, and the page shows the message.
// Revoke it, and send back the new list with the details the site records.awaitapi(env).revokeGrant(app.id, demo.id)returnjson(200, { apps: awaitappsOf(env, demo.id), available: true }, { ...about(demo), 'X-Mcp-Grant': 'disconnected' })}
Revoke, and say so Site request
WhatrevokeGrant(app.id, demo.id) deletes the grant's access tokens and the grant. The reply is the new list, with the headers X-Demo-Id, X-Demo-Email when known, and X-Mcp-Grant: disconnected.
WhyThe app's next MCP request finds no token record and gets 401. Its refresh token no longer matches a grant, so the app must ask for the visitor's consent again. KV is eventually consistent, so another Cloudflare location may still read a deleted record for a short time. Returning the list saves the page a second request. The headers are for the site, which records the event and strips them.
// "Use it from Claude Code": the line to paste and the apps the visitor has allowed// (README.md, "The MCP server"). Shown only while the demo has a PDF; the line holds no secret.functiondrawApps(apps) {
What the box is In the browser
WhatThe comment says the box holds the line to paste and the allowed apps, is shown only while the demo account has a PDF, and that the line holds no secret; it points to the README's section on the MCP server.
WhyThe line names only the public MCP endpoint. The visitor approves on the consent page in the browser, and Claude Code then exchanges the authorization code for its tokens at the token endpoint.
WhatEach app becomes an li whose label reads "<name> (<host>): <permissions joined by ;>. Allowed <date>.", with the host only when there is one and the date in the visitor's locale.
WhyThe label is set through textContent, so a client name containing markup is shown as characters and never parsed. The client controls the name, and this is the page's defence against it. allowed_at is in Unix seconds and Date takes milliseconds, hence × 1000.
WhatA type=button element with class remove, text Disconnect and aria-label "Disconnect <name>".
WhyEvery row's button reads Disconnect, so the aria-label names the app for a screen reader. setAttribute stores the name as an attribute value, which is not parsed as markup either.
WhatThe button is disabled, then the page sends DELETE /api/demo/grants with the JSON body { id }. A network failure gives a null response, and the body is read as JSON or else {}.
WhyDisabling the button prevents a second request while the first is in flight. The demo cookie, which holds the visitor's access key, goes with the same-origin fetch, and the site sends the key on as X-Demo-Key, so the Worker knows the account without the page naming it.
if (!response || !response.ok) { $("apps-status").textContent = body.error || `${app.name} could not be disconnected.`; disconnect.disabled = false;return; } $("apps-status").textContent = `${app.name} disconnected.`;drawApps(body.apps ?? []); });
Failure or the new list In the browser
WhatOn failure the status line shows the reply's error field or "<name> could not be disconnected." and the button is enabled again. On success it says "<name> disconnected." and redraws from the list in the reply.
WhyThe reply carries the list after revocation, so the page shows the list the Worker returned instead of guessing by removing the row itself.
WhatIf the file list is empty the box is hidden and nothing is fetched.
WhyThe MCP server has nothing to search without documents. The page calls showConnect after the session loads, after each upload and after each removal, so the box appears with the first file and disappears with the last.
const response = awaitfetch("/api/demo/grants").catch(() =>null);const body = response && response.ok ? await response.json().catch(() => ({})) : {};// Where the MCP server is not set up, the box is not shown at all.if (body.available !== true) { $("connect").hidden = true; return; }
Ask the Worker In the browser
WhatSends GET /api/demo/grants. A network error, an error status or a body that is not JSON all give {}. Unless available is true, the box stays hidden.
WhyA deployment without the OAuth store answers available: false, and the page treats any failure the same way, so the box is shown only when connecting can work.
WhatSets the line to claude mcp add --transport http my-docs <origin>/mcp/demo with the page's own origin, draws the apps and shows the box.
Whylocation.origin makes the line correct wherever the page is served, a local run included. --transport http selects MCP's Streamable HTTP transport. On first use, Claude Code gets the MCP server's 401 and starts the OAuth flow that ends on the consent page.
claude mcp add --transport http my-docs <origin>/mcp/demo
$("connect-copy").addEventListener("click", async () => {try {await navigator.clipboard.writeText($("connect-line").textContent); $("apps-status").textContent = "Copied."; } catch { $("apps-status").textContent = "Select the line and copy it."; } });
Copy, or say how In the browser
WhatOn click, navigator.clipboard.writeText copies the line and the status says "Copied."; if that throws, the status says "Select the line and copy it."
WhyThe Clipboard API needs a secure context, and the browser or a permission policy can refuse it, so the failure message tells the visitor to copy by hand. The status element is an aria-live region, so screen readers announce the result.
// Disconnecting an app from the demo's MCP server is recorded as the consent page's decisions are.if (answer.ok && path === "grants" && answer.headers.get("X-Mcp-Grant") !== null) awaitserverEvent(env, request, "demo_mcp_grant", { demo, decision: "disconnected", scopes: "" }, email);
Record the disconnection Site request
WhatWhen a grants request succeeds and the Worker's reply carries X-Mcp-Grant, the forwarder records a demo_mcp_grant event with the account's id, decision disconnected and empty scopes, under the account's email.
WhyOnly DELETE replies carry X-Mcp-Grant, so listing apps records nothing. The consent page's allowed and denied decisions produce the same event name through forwardToDemo, so all three decisions appear together. This forwarder's own INTERNAL list then strips the header before the reply reaches the browser.