Joel Stevick

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: showConnect(): runs only when the demo account has a PDF; requests the listBROWSERshowConnect()runs only when thedemo account has aPDF; requests the listDemo Worker: grantsRoute(): GET: answers with the apps and available: trueDEMO WORKERgrantsRoute():GETanswers with theapps and available:trueDemo Worker: appsOf(): turns this account's grants into apps, oldest firstDEMO WORKERappsOf()turns this account'sgrants into apps,oldest firstBrowser: drawApps(): writes each app as text, with a Disconnect buttonBROWSERdrawApps()writes each app astext, with aDisconnect buttonBrowser: Disconnect button: sends DELETE /api/demo/grants with the grant's idBROWSERDisconnect buttonsends DELETE/api/demo/grants withthe grant's idDemo Worker: grantsRoute(): DELETE: finds the id among this account's apps; any other id gets 404DEMO WORKERgrantsRoute():DELETEfinds the id amongthis account's apps;any other id gets 404Demo Worker: revokeGrant(): the library deletes the grant and its tokensDEMO WORKERrevokeGrant()the library deletes thegrant and its tokensPages Function: Disconnection event: the Pages Function records demo_mcp_grantPAGES FUNCTIONDisconnectioneventthe Pages Functionrecordsdemo_mcp_grantBrowser: drawApps(), again: replaces the list with the one returnedBROWSERdrawApps(),againreplaces the list withthe one returnedAn id that is not one of this account's grants is answered 404 and nothing is revoked.An id that is not one of this account's grants is answered 404 and nothing is revoked.
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

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

demo/src/oauth.ts The OAuth side of the demo Worker: the app cap and the file's last 60 lines, which list the connected apps and revoke them.

MAX_APPS

constant · lines 30–31View on GitHub

The most apps one demo account can have connected.

/** The most apps one demo can have connected at a time. */export const MAX_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.

MAX_APPS = 5

App

interface · lines 332–340View on GitHub

One connected app as the page receives it.

/** One connected app as the demo page and /admin list it. */export interface App {  id: string  name: string  host: string  can: 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.

appsOf()

async function · lines 341–363View on GitHub

Turns a demo account's grants into the list the page shows, oldest first.

Called by grantsRoute() adminDemo() Consent and the archiveCalls api() Tokens and grants

/** The apps connected to a demo, oldest first. */export async function appsOf(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 = (await api(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 in SCOPE_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".

name, host: at most 120 characters

    .sort((a, b) => a.allowed_at - b.allowed_at)}

Oldest first Site request

WhatSorted by allowed_at ascending.

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.

revokeGrants()

async function · lines 364–372View on GitHub

Disconnects every app from a demo account, for the idle purge.

Called by purge() Idle purge and expiryCalls api() Tokens and grants

/** Disconnects every app from a demo: its grants and their tokens are revoked by the library. */export async function revokeGrants(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.

grantsRoute()

async function · lines 373–391View on GitHub

GET lists this account's apps; DELETE { id } disconnects one of them.

Called by route(): the visitor's routes Worker routerCalls appsOf() about() Shared helpers api() Tokens and grants json() Shared helpers

/** The demo page's Connected apps: GET lists them, DELETE { id } disconnects one of this demo's. */export async function grantsRoute(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) return json(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') return json(200, { apps: await appsOf(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 = (await appsOf(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) return json(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.  await api(env).revokeGrant(app.id, demo.id)  return json(200, { apps: await appsOf(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.

demo.html The demo page: the script that draws the Use it from Claude Code box, its app list, Disconnect and Copy.

drawApps()

function · lines 205–233View on GitHub

Renders the connected apps, each with a Disconnect button.

Called by showConnect()Calls Module scope The demo page

  // "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.  function drawApps(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.

    $("apps").replaceChildren(...apps.map((app) => {      const li = document.createElement("li");      const label = document.createElement("span");      label.textContent = `${app.name}${app.host ? ` (${app.host})` : ""}: ${app.can.join("; ")}. Allowed ${new Date(app.allowed_at * 1000).toLocaleDateString()}.`;

One line per app, as text In the browser

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.

      const disconnect = document.createElement("button");      disconnect.type = "button";      disconnect.className = "remove";      disconnect.textContent = "Disconnect";      disconnect.setAttribute("aria-label", `Disconnect ${app.name}`);

The Disconnect button In the browser

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.

      disconnect.addEventListener("click", async () => {        disconnect.disabled = true;        const response = await fetch("/api/demo/grants", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: app.id }) }).catch(() => null);        const body = response ? await response.json().catch(() => ({})) : {};

Click: DELETE /api/demo/grants In the browser

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.

      li.append(label, disconnect);      return li;    }));    $("apps-none").hidden = apps.length > 0;  }

Replace the list In the browser

WhatEach li gets its label and button; replaceChildren swaps the whole list at once, and "No app is connected." shows only when the list is empty.

WhyRedrawing from scratch on every call keeps the list identical to the last reply, with no rows left from an earlier state.

showConnect()

async function · lines 234–245View on GitHub

Shows or hides the Use it from Claude Code box and fills it.

Called by #pdfs change handler Upload handler removeFile() Removing a file start() Demo accounts and sessionsCalls drawApps() Module scope The demo page

  async function showConnect() {    const has = $("files").children.length > 0;    if (!has) { $("connect").hidden = true; return; }

Only with a PDF In the browser

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 = await fetch("/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.

    $("connect-line").textContent = `claude mcp add --transport http my-docs ${location.origin}/mcp/demo`;    drawApps(body.apps ?? []);    $("connect").hidden = false;  }

The command, the list, the box In the browser

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

Copy button handler

handler · lines 246–255View on GitHub

Copies the command line to the clipboard.

Calls Module scope The demo page

  $("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.

functions/api/demo/[[path]].ts The site's forwarder for the demo page's API: the one line that records a disconnection.

onRequest(): disconnect event

segment · lines 65–67View on GitHub

Records a disconnection as a site event.

Calls serverEvent() Pages Function /api/demo/*

  // 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) await serverEvent(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.

event: demo_mcp_grantdecision: disconnected