Joel Stevick

MCP server · Site forwarding · /mcp/demo and /oauth/* · stage 1 of 1

The Pages Functions

Every MCP and OAuth request reaches the site first. Three Pages Functions (/mcp/demo, the catch-all /oauth/* and /api/docs-store/*) and the middleware (for the /.well-known/ discovery documents) pass the request to one forwarder, forwardToDemo. The forwarder removes every header only the site may set, adds the caller's address and the recording flag, and passes cookies and the visitor's access key (from the demo cookie) only to the consent page. It then calls the demo Worker through the DEMO service binding at the request's own URL, and returns the Worker's response with the internal headers removed. On joelstevick.com a consent decision is recorded as an event; in this repository the analytics are stand-ins that record nothing.

Runs in: Pages Function, the site's server code on Cloudflare Pages, functions/. New to Cloudflare? How these fit together
functions/_lib/demo-mcp.ts69 / 69 lines on this page explainedevery line of the file
functions/mcp/demo.ts9 / 9 lines on this page explainedevery line of the file
functions/oauth/[[path]].ts11 / 11 lines on this page explainedevery line of the file
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.

functions/_lib/demo-mcp.ts The forwarder for every MCP, OAuth, discovery and document-store request.

Module scope

module scope · lines 1–22View on GitHub

The licence, the module's purpose, its imports, its env type and its two header lists.

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

Licence Never runs

WhatThe copyright and the MIT licence, with an SPDX identifier.

WhyThe repository is public under the MIT licence. Licence scanners read the SPDX line without parsing the prose.

// The site's door to the demo's MCP server and its OAuth endpoints (README.md, "The MCP server"). The// server and the authorization server are in the demo Worker (demo/src/mcp.ts, demo/src/oauth.ts),// which has no public URL: these paths are forwarded to it through the DEMO binding with the// request's own URL, so every address the Worker publishes is the site's. Nothing of the protocol// or of OAuth is here.

No protocol code on the site Never runs

WhatThe comment says the MCP server and the authorization server run in the demo Worker, which has no public URL. The site forwards these paths to it through the DEMO binding with the request's own URL, and the site's Pages Functions contain no MCP or OAuth code.

WhyBecause the request keeps its own URL, the Worker publishes the origin the caller used: the site's in production, the local address in a local run. The Worker replaces any other origin with https://joelstevick.com. A service binding is a call within the Cloudflare account, so the Worker needs no route or hostname of its own.

import { demoKey } from "./demo";import { mayRecord, serverEvent, type TrackEnv } from "./track";

Imports Module load

WhatdemoKey reads the demo cookie (functions/_lib/demo.ts). mayRecord and serverEvent are the site's visitor analytics. In this repository (functions/_lib/track.ts) they are stand-ins: mayRecord always returns false and serverEvent records nothing.

WhyOn joelstevick.com the same calls check consent and record events. The stand-ins keep the forwarder's code identical to the site's while recording nothing.

export interface DemoMcpEnv extends TrackEnv {  DEMO?: Fetcher;}

DemoMcpEnv Type only

WhatThe analytics env (an optional D1 binding, DB) plus DEMO, the optional service binding to the demo Worker.

WhyA deployment without the Worker has no DEMO binding. Typing it as optional makes the compiler require a check, and forwardToDemo answers 503 when the binding is missing.

/** The two discovery documents an MCP client reads: the protected resource's and the authorization server's. */export const WELL_KNOWN = ["/.well-known/oauth-protected-resource", "/.well-known/oauth-authorization-server"];

WELL_KNOWN Module load

WhatThe two discovery path prefixes, /.well-known/oauth-protected-resource (RFC 9728) and /.well-known/oauth-authorization-server (RFC 8414). The middleware forwards any path equal to or below one of them.

WhyThe module exports the list so the middleware (functions/_middleware.ts) uses the same strings. The Worker's MCP_PATHS (demo/src/oauth.ts) repeats both strings, so the two lists must be kept in step by hand. The protected resource metadata for /mcp/demo is at a path below the first prefix.

/.well-known/oauth-protected-resource/.well-known/oauth-authorization-server

/** Headers the Worker answers the site with, never passed on to the caller. */const INTERNAL = ["X-Demo-Email", "X-Demo-Id", "X-Mcp-Grant", "X-Mcp-Scopes"];

INTERNAL Module load

WhatThe four headers the Worker sets for the site only: X-Demo-Email, X-Demo-Id, X-Mcp-Grant and X-Mcp-Scopes.

WhyThe consent page's response carries the id of the visitor's demo account (their row in the demos table) and their email address so the site can record the decision. These headers must never reach the browser or the MCP host.

X-Demo-EmailX-Demo-IdX-Mcp-GrantX-Mcp-Scopes

forwardToDemo()

async function · lines 23–69View on GitHub

Forwards one request to the demo Worker and returns the Worker's response, with the site's headers set on the request and the internal headers removed from the response.

Called by onRequest onRequest onRequest The discovery documents onRequest Token exchange (RFC 8693)Calls demoKey() Pages Function /api/demo/* mayRecord() Pages Function /api/demo/* serverEvent() Pages Function /api/demo/*

/** * Forwards one request to the demo Worker and hands its answer back. `consent` is the authorization * page: only there do the browser's cookies go through (the consent form's own, set by the Worker), * with the demo cookie's key as X-Demo-Key, which is who the visitor is. A caller can never set that * header, or its own address, itself: both are removed from what arrived and set here. */

The contract Never runs

WhatThe doc comment. consent marks the authorization page, the only request whose cookies are forwarded: the library's consent cookie, which the Worker sets, and the demo cookie's key, sent as X-Demo-Key. A caller cannot set X-Demo-Key or X-Client-Address, because the forwarder removes both from the incoming request and sets them itself.

WhyX-Demo-Key identifies the visitor in the Worker, and the rate limits count by X-Client-Address, so both must come from the site.

export async function forwardToDemo(request: Request, env: DemoMcpEnv, consent = false): Promise<Response> {  // Without the binding there is no Worker to forward to.  if (env.DEMO === undefined) return Response.json({ error: "The demo is not available right now." }, { status: 503 });

Signature, and no binding MCP request

WhatTakes the request, the env and the consent flag (false by default). Without the DEMO binding it answers 503 with a JSON error.

WhyA 503 tells an MCP host that the MCP server is unavailable for now, where a 500 would point to a fault in the MCP server. Nothing is forwarded.

  // Start from the caller's headers, then drop any it sent that only the site may set.  const headers = new Headers(request.headers);  const names: string[] = [];  headers.forEach((_value, name) => names.push(name));  for (const name of names) if (name.toLowerCase().startsWith("x-demo-") || name.toLowerCase() === "x-client-address") headers.delete(name);

Remove what only the site may set MCP request

WhatDeletes every incoming header whose name starts with x-demo- (case-insensitive), and X-Client-Address. Authorization, MCP-Protocol-Version, Content-Type and the other headers pass through unchanged.

WhyThe names are collected first so that the Headers object is not modified while forEach iterates over it. The x-demo- prefix covers X-Demo-Key (identity), X-Demo-Keep (consent to recording), X-Demo-Via (which the Worker uses to label where a question came from) and the response-only names. A caller therefore cannot pose as a demo account or set any flag the Worker trusts.

removed: x-demo-*, x-client-address

  // Cookies only go through to the consent page.  if (!consent) headers.delete("Cookie");

Cookies only to the consent page MCP request

WhatUnless consent is true, the forwarder removes the Cookie header.

WhyMCP requests and token requests authenticate with OAuth credentials only. With the site's cookies removed, a cookie the browser sends can never authorize an MCP call, and the access key reaches the Worker only on the page where the visitor makes the decision.

  // Tell the Worker who is calling and whether this visitor may be recorded.  headers.set("X-Client-Address", request.headers.get("CF-Connecting-IP") ?? "unknown");  headers.set("X-Demo-Keep", mayRecord(request, env) ? "1" : "0");

The caller's address and the recording flag MCP request

WhatX-Client-Address is set from CF-Connecting-IP, Cloudflare's header for the client's IP, or to 'unknown' when that header is missing. X-Demo-Keep is '1' when mayRecord allows recording this visitor and '0' otherwise; in this repository it is always '0'.

WhyBefore it checks any token, the Worker counts requests per address, at 120 a minute. It counts every request to the MCP endpoint or its protected resource metadata, every consent page request, every OAuth POST and every document-store request. A request with a valid token is also limited to 60 a minute per demo account. The Worker needs the real client IP for this count, and only the site's edge knows it. Without CF-Connecting-IP (a local run), every caller shares the 'unknown' counter. X-Demo-Keep decides whether a question asked through the MCP server is kept past the 10-day purge.

X-Client-Address: CF-Connecting-IP or 'unknown'X-Demo-Keep: '1' or '0'

  // On the consent page, pass on the visitor's demo key so the Worker knows whose demo it is.  const key = consent ? demoKey(request) : null;  if (key !== null) headers.set("X-Demo-Key", key);

The visitor's access key, on the consent page MCP request

WhatOn the consent page, demoKey reads the demo cookie (43 URL-safe base64 characters, or null when it is missing or malformed), and the forwarder sends it as X-Demo-Key.

WhyThe Worker's signedIn finds the demo account by the key's SHA-256, and that is how the consent page knows whose account the app is asking for. Nothing in the OAuth request names an account, so the grant (the OAuth library's record of what the app may do) is written for the account the key matches.

  // Send the request on to the Worker at the same URL, leaving redirects for the caller to follow.  const answer = await env.DEMO.fetch(request.url, {    method: request.method,    headers,    body: request.method === "GET" || request.method === "HEAD" ? undefined : await request.arrayBuffer(),    redirect: "manual",  });

Call the Worker at the same URL MCP request

WhatCalls DEMO.fetch with request.url, the method, the rebuilt headers and redirect: 'manual'. The body is read whole into an ArrayBuffer; GET and HEAD send none.

WhyWith the same URL, the Worker builds its issuer and resource from the origin the caller used when that is the site's or a local run's. redirect: 'manual' returns a 302 to the caller unchanged. The consent page answers Allow and Deny with a redirect to the app's redirect URI, often http://localhost:<port>/callback on the visitor's machine, and only the browser can follow it. Buffering the body is acceptable because the bodies are small (OAuth form posts and JSON-RPC messages), and the Worker refuses an MCP body over 64 KiB with 413.

redirect: 'manual'

  // A decision on the consent page is recorded as an event, with the scopes and never the app's token.  const decision = answer.headers.get("X-Mcp-Grant");  if (decision !== null) {    await serverEvent(env, request, "demo_mcp_grant", { demo: answer.headers.get("X-Demo-Id"), decision, scopes: answer.headers.get("X-Mcp-Scopes") ?? "" }, answer.headers.get("X-Demo-Email"));  }

Record a consent decision MCP request

WhatIf the response carries X-Mcp-Grant (allowed or denied, set by the consent page), serverEvent records demo_mcp_grant under the email address from X-Demo-Email. The event holds the account's id, the decision and the granted scopes (space-separated, without offline_access, empty for a denial). In this repository serverEvent does nothing.

WhyThe site keeps a record of which demo account allowed or denied an app, and with which scopes. The Worker sets X-Mcp-Grant, X-Mcp-Scopes, X-Demo-Id and X-Demo-Email for that purpose only, and they hold no token or code. The authorization code travels only in the redirect's Location header.

event: demo_mcp_grant

  // Pass the answer back without the headers meant only for the site.  const response = new Response(answer.body, answer);  for (const name of INTERNAL) response.headers.delete(name);  return response;}

Return the response MCP request

Whatnew Response(answer.body, answer) copies the status and headers into a new, mutable response around the same body stream, and the forwarder deletes the four INTERNAL headers from it.

WhyThe headers of a fetched response are immutable, so deleting from them needs a copy. Passing the body stream through, instead of reading it, keeps a server-sent events response streaming to the host; an MCP call that sends progress notifications returns one.

functions/mcp/demo.ts The Pages Function at /mcp/demo, the MCP endpoint.

Module scope

module scope · lines 1–8View on GitHub

The licence, the route's purpose and its import.

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

Licence Never runs

WhatThe copyright and the MIT licence, with an SPDX identifier.

WhyThe repository is public under the MIT licence. Licence scanners read the SPDX line without parsing the prose.

// /mcp/demo: the demo's MCP server (README.md, "The MCP server"), served by the demo Worker. On the site// this static route sits beside other MCP routes in the same folder, which are not part of this repository.

The MCP endpoint Never runs

WhatThe comment says /mcp/demo is the demo app's MCP server, served by the demo Worker. On the site, this static route shares its folder with other MCP routes that are not in this repository.

WhyPages matches a static path such as mcp/demo.ts before a dynamic one in the same folder, so /mcp/demo always reaches this file.

import { forwardToDemo, type DemoMcpEnv } from "../_lib/demo-mcp";

Import Module load

WhatforwardToDemo and the DemoMcpEnv type from functions/_lib/demo-mcp.ts.

WhyEvery MCP, OAuth, discovery and document-store request goes through this one forwarder, so the header rules are written once.

onRequest

handler · lines 9–9View on GitHub

Forwards every request to /mcp/demo without cookies.

Calls forwardToDemo()

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

Forward every method MCP request

WhatonRequest is the Pages Functions export called for every HTTP method, and calls forwardToDemo with consent left false, so the forwarder removes the Cookie header and adds no access key.

WhyThe Worker decides what each method means: the library and the SDK take POST for messages and OPTIONS for CORS preflight, and answer GET and DELETE, the session operations of the 2025 protocol revisions, with 405. The only credential that counts on this route is the bearer token, which passes through in the Authorization header.

functions/oauth/[[path]].ts The catch-all Pages Function for /oauth/*.

Module scope

module scope · lines 1–9View on GitHub

The licence, what the catch-all serves, and its import.

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

Licence Never runs

WhatThe copyright and the MIT licence, with an SPDX identifier.

WhyThe repository is public under the MIT licence. Licence scanners read the SPDX line without parsing the prose.

// /oauth/*: the authorization server of the demo's MCP server (README.md, "The MCP server"), served by// the demo Worker: the consent page (/oauth/authorize), the token endpoint and client registration.// Only the consent page is given the browser's cookies and the demo cookie's key.

The authorization server's paths Never runs

WhatThe comment says /oauth/* is the authorization server, served by the demo Worker: the consent page (/oauth/authorize), the token endpoint and client registration. Only the consent page receives the browser's cookies and the access key.

Why[[path]] is Pages' optional catch-all, so one file covers every path under /oauth, including paths the Worker answers with 404.

import { forwardToDemo, type DemoMcpEnv } from "../_lib/demo-mcp";

Import Module load

WhatforwardToDemo and the DemoMcpEnv type from functions/_lib/demo-mcp.ts.

WhyThe same forwarder serves /mcp/demo and the discovery paths.

onRequest

handler · lines 10–11View on GitHub

Forwards every /oauth/ request and sets the consent flag for the consent page.

Calls forwardToDemo()

export const onRequest: PagesFunction<DemoMcpEnv> = ({ request, env }) =>  forwardToDemo(request, env, new URL(request.url).pathname === "/oauth/authorize");

Consent only at /oauth/authorize MCP request

WhatForwards every request, with consent true exactly when the path is /oauth/authorize. That covers the GET that shows the consent page and the POST that carries the decision.

WhyThe consent page needs the access key and the library's consent cookie, which is set on the GET and checked on the POST so that only the browser that saw the page can submit it. The MCP host calls /oauth/token and /oauth/register itself, and those requests get neither.