Joel Stevick

MCP server · Discovery · /.well-known/ · stage 1 of 1

The discovery documents

An MCP host starts with only the MCP server's URL. Its first unauthenticated request gets a 401 that points to the protected resource metadata (RFC 9728), which names the authorization server. The host then reads that server's metadata (RFC 8414) for the authorize, token and registration endpoints. The site's middleware forwards both /.well-known/ paths to the demo Worker with the request's own URL. In the Worker, originOf() settles the origin as the site's or a local run's, and the library builds both documents from the authorization server and resource server constructed once for that origin, so every address in them starts with that origin.

Pages Function: Site middleware: forwards /.well-known/oauth-protected-resource/… to the WorkerPAGES FUNCTIONSite middlewareforwards/.well-known/oauth-protected-resource/…to the WorkerDemo Worker: originOf(): returns the site's origin or a local run's; any other host counts as the siteDEMO WORKERoriginOf()returns the site'sorigin or a local run's;any other host countsas the siteDemo Worker: serversFor(): returns the OAuthAuthorizationServer and OAuthResourceServer built once for that originDEMO WORKERserversFor()returns theOAuthAuthorizationServer andOAuthResourceServer built once for thatoriginDemo Worker: Resource server answers: names <origin>/mcp/demo as the resource and the origin as its authorization serverDEMO WORKERResource serveranswersnames<origin>/mcp/demoas the resource andthe origin as itsauthorization serverPages Function: Site middleware: forwards /.well-known/oauth-authorization-server to the WorkerPAGES FUNCTIONSite middlewareforwards/.well-known/oauth-authorization-serverto the WorkerDemo Worker: originOf(), again: settles the origin the same wayDEMO WORKERoriginOf(), againsettles the origin thesame wayDemo Worker: serversFor(), again: returns the same origin's pair, built on first useDEMO WORKERserversFor(),againreturns the sameorigin's pair, built onfirst useDemo Worker: Authorization server answers: the issuer is the origin; names /oauth/authorize, /oauth/token and /oauth/registerDEMO WORKERAuthorizationserver answersthe issuer is theorigin; names/oauth/authorize,/oauth/token and/oauth/registerA request to any other host gets the site's servers, so its origin matches no library endpoint. Discovery paths then answer 404, and /oauth/authorize answers 400.A request to any other host gets the site's servers, so its origin matches no library endpoint. Discovery paths thenanswer 404, and /oauth/authorize answers 400.
Pages 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
A terminal: the command claude mcp add --transport http my-docs https://joelstevick.com/mcp/demo, and Claude Code's reply that it added the HTTP MCP server my-docs to its local config.
Adding the demo app's MCP server to Claude Code takes one HTTP address and no key. The command configures nothing about OAuth. The first time the MCP server answers 401, Claude Code reads the discovery documents to find where to get a token. 2026-11-29, Terminal on macOS, Claude Code 2.1.332, against the live MCP server, which is newer than the pinned commit
functions/_middleware.ts17 / 17 lines on this page explainedevery line of the file
demo/src/oauth.ts62 / 62 lines on this page explainedlines 1-27,41-50,62-75,82-85,107-113 of 391; 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.

functions/_middleware.ts The site's Pages Functions middleware, which runs before every request routed to its Pages Functions.

Module scope

module scope · lines 1–9View on GitHub

The licence, why this middleware exists, 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 MIT. The SPDX line lets licence scanners read it without parsing prose.

// The two OAuth discovery documents of the demo's MCP server (README.md, "The MCP server") live under /.well-known/,// where a Pages function's file cannot: they are forwarded to the demo Worker from here. Every other request goes on// unchanged. (On joelstevick.com this middleware also does the site's own redirects, which are not part of this repo.)

Why a middleware Never runs

WhatThe comment says that no Pages Function file can serve the two discovery documents under /.well-known/, so this middleware forwards them to the demo Worker and passes every other request on unchanged.

WhyRFC 8414 and RFC 9728 fix these paths at the root of the origin, so the documents cannot move to a path a Function file could own. On joelstevick.com the same middleware also does the site's redirects, which are not in this repository.

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

Import Module load

WhatforwardToDemo (the one forwarder every MCP and OAuth route uses), WELL_KNOWN (the two path prefixes) and the DemoMcpEnv type, from functions/_lib/demo-mcp.ts.

WhyWELL_KNOWN is defined with the forwarder in functions/_lib/demo-mcp.ts, the site's one module for the demo app's MCP routes. The Worker keeps its own copy of the two paths in MCP_PATHS (demo/src/oauth.ts), so the two lists must name the same paths.

onRequest

handler · lines 10–17View on GitHub

Sends the two discovery paths to the demo Worker; everything else continues. It runs on every request to the site, a page load, a question, an upload or an MCP call alike, so its shared lines are marked Query time, the value for the request handling every route shares; the line that forwards a discovery document is marked MCP request.

Calls forwardToDemo() The Pages Functions

export const onRequest: PagesFunction<DemoMcpEnv> = async ({ request, next, env }) => {  const url = new URL(request.url);

The handler and the URL Query time

WhatA PagesFunction typed with DemoMcpEnv (the DEMO service binding and the D1 database for visit tracking). It receives the request, next (the rest of the chain: other Functions or the static assets) and env, and parses the request URL.

WhyAs _middleware.ts at the root of functions/, it runs first for every request routed to Pages Functions, so its path check must be cheap: one URL parse and at most four string comparisons.

  // A discovery document goes to the demo Worker; anything else carries on as normal.  if (WELL_KNOWN.some((prefix) => url.pathname === prefix || url.pathname.startsWith(`${prefix}/`))) return forwardToDemo(request, env);

A discovery path goes to the Worker MCP request

WhatA path equal to or below /.well-known/oauth-protected-resource or /.well-known/oauth-authorization-server goes to forwardToDemo with no consent flag, so no cookies go through.

WhyThe prefix match matters: the protected resource metadata for /mcp/demo is at /.well-known/oauth-protected-resource/mcp/demo (RFC 9728 inserts the resource's path after the well-known prefix). The URL is forwarded unchanged, so the library in the Worker builds the documents for the origin the host used when that is the site's or a local run's.

  return next();};

Anything else carries on Query time

WhatEvery other request calls next(), which runs the matching Function (/mcp/demo, /oauth/*, /api/docs-store/*, /api/demo/*, /demo) or serves the static file.

WhyThe middleware adds nothing to other requests: no headers, no logging, no rewrite.

demo/src/oauth.ts The OAuth side of the demo Worker: its header comment and imports, the forwarded paths, the origin, and the settings the two discovery documents are built from.

Module scope

module scope · lines 1–23View on GitHub

The licence, what the module owns and what it leaves to the library, and its imports.

// 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 MIT. The SPDX line lets licence scanners read it without parsing prose.

/** * Who may call the demo's MCP server (README.md, "The MCP server"). OAuth 2.1 is the library's * (`@cloudflare/workers-oauth-provider`): discovery documents, client registration, PKCE, codes, * tokens, refresh, revocation and the 401 challenge; its state (clients, grants, tokens) is in KV, `OAUTH_KV`. * This Worker is both roles: the authorization server (issuer: the site's origin, or a local run's) and the one * resource it issues tokens for (`<origin>/mcp/demo`). *

OAuth 2.1 is the library's Never runs

WhatThe module's contract: Cloudflare's @cloudflare/workers-oauth-provider supplies the discovery documents, client registration, PKCE, codes, tokens, refresh, revocation and the 401 challenge, and keeps its state (clients, grants, tokens) in the KV namespace OAUTH_KV. The Worker plays both roles: the authorization server (issuer: the request's origin, the site's or a local run's) and the single protected resource, <origin>/mcp/demo.

WhyBecause one Worker plays both roles, the resource server validates a token with a direct function call into the authorization server (validateToken), with no introspection request. KV holds only the clients, grants and tokens. The library builds the discovery documents from the settings in serversFor() and builds the 401 challenge for each request.

 * What is ours is the part only the application knows: *   - who the visitor is: the demo their browser's cookie names (the site forwards its key); *   - the consent page: which app is asking, where the access goes, and what it may do; *   - what a grant holds: the demo's id and the scopes the visitor ticked, never more; *   - the list of connected apps on the demo page, and Disconnect. */

What the application owns Never runs

WhatThe four things only the demo app can know: who the visitor is (the demo account whose access key their demo cookie holds), the consent page, what a grant holds (the account's id and the ticked scopes) and the list of connected apps with Disconnect.

WhyThis is the boundary between protocol and application. Everything a standard defines comes from the library, and the demo app writes only what depends on its own users and data.

import { AuthorizationError, CimdFetchError, OAuthAuthorizationServer, OAuthResourceServer, type ConsentDescription, type OAuthHelpers } from '@cloudflare/workers-oauth-provider'import { about, json, signedIn, type Demo, type Env, type Options } from './app'import { anonymousAllowed, READ, serveMcp, tooMany, WRITE, type Run } from './mcp'import type { Models } from './models'import { docsStoreRoute, isTokenExchange, tokenExchange } from './token-exchange'

Imports Module load

WhatFrom the library: the two role classes, the two error classes the consent page catches, and the ConsentDescription and OAuthHelpers types. From app.ts: about, json, signedIn and the Demo, Env and Options types. From mcp.ts: the address limit (anonymousAllowed, tooMany), the scopes READ and WRITE, serveMcp and the Run type. The Models type from models.ts. From token-exchange.ts: docsStoreRoute, isTokenExchange and tokenExchange, for the document store's route and the token exchange that oauthRoute answers before the library.

Whyapp.ts imports this module for its router and mcp.ts imports app.ts, so the three form an import cycle, and token-exchange.ts, which imports app.ts, this module and mcp.ts, joins it. From the Worker's entry (index.ts imports app.ts) the order is app.ts → oauth.ts → mcp.ts → token-exchange.ts. token-exchange.ts finishes first (it reads none of its imports at load), then mcp.ts, before oauth.ts: READ and WRITE are initialised when SCOPE_WORDS reads them at load. What comes from app.ts and token-exchange.ts is used only inside functions, after every module has loaded.

MCP_PATHS

constant · lines 24–25View on GitHub

The paths the Worker's router passes to oauthRoute.

/** The paths the site forwards here with its own URL: the MCP endpoint, the OAuth endpoints, the two discovery documents and the document store (token-exchange.ts). */export const MCP_PATHS = ['/mcp/demo', '/oauth', '/.well-known/oauth-protected-resource', '/.well-known/oauth-authorization-server', '/api/docs-store']

The forwarded paths Module load

What/mcp/demo, /oauth, the two /.well-known/ discovery paths, and /api/docs-store, the document store that the MCP server calls with an exchanged token. The router in app.ts matches each as an exact path or as a prefix followed by /, and sends a match to oauthRoute before the visitor routes, which need an access key.

WhyMCP, OAuth and document store requests carry no access key. The demo account they act for comes from the bearer token or, on the consent page, from the demo cookie, whose access key the site sends on as X-Demo-Key. Checking these paths first keeps them out of the signed-in routes' 401. '/oauth' as a prefix covers /oauth/authorize, /oauth/token and /oauth/register; '/api/docs-store' covers /api/docs-store/files.

/mcp/demo/oauth/.well-known/oauth-protected-resource/.well-known/oauth-authorization-server/api/docs-store

SITE

constant · lines 26–27View on GitHub

The production origin, used for any request that does not come from it or from a local run.

/** The site, when a request comes from anywhere but it or a local run. */const SITE = 'https://joelstevick.com'

The site's origin Module load

WhatSITE is https://joelstevick.com, with no trailing slash, the form of an origin.

WhyIt becomes the issuer, the resource's origin and every endpoint's origin for production traffic. The issuer must match byte for byte, because the host compares it with the iss parameter on the redirect and with the issuer in the metadata.

SITE = 'https://joelstevick.com'

originOf()

function · lines 41–50View on GitHub

The origin the host and the browser see: the site's, or a local run's.

Called by oauthRoute(): RESOURCE Token validation and limits

/** The origin the visitor and the client see: the site's own, or a local run's. Anything else is the site. */function originOf(request: Request): string {  const url = new URL(request.url)

Signature MCP request

WhatParses the request's URL. The site forwards with the request's own URL, so this is the address the host or the browser used.

WhyThe Worker has no public URL (workers_dev = false in demo/wrangler.toml); it is reached only through the site's DEMO service binding, which preserves the URL.

  // A plain-http localhost address is a local run.  const local = url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1')

A local run MCP request

WhatPlain http on localhost or 127.0.0.1, any port, counts as a local run.

WhyThe library accepts http only on a loopback host (localhost, 127.0.0.0/8, ::1) and requires https elsewhere. The code treats two of those hosts, localhost and 127.0.0.1, as a local run; any other loopback address is replaced by SITE. Under wrangler pages dev the documents then name http://localhost:<port>, so a local host can complete the flow.

  return local || url.origin === SITE ? url.origin : SITE}

Anything else is the site MCP request

WhatThe site's own origin or a local run's is returned as is; any other origin is replaced by SITE.

WhyThe issuer is never taken from an arbitrary Host header. A request under another host gets the site's servers. The library compares the request's origin with the issuer's, so the request matches no library endpoint or resource and is answered 404. For the same reason, parseAuthRequest refuses /oauth/authorize, which the demo app serves itself, with 400. Mapping every other origin to SITE also limits the cache of server pairs to the site and local origins.

serversFor(): DISCOVERY

segment · lines 62–113View on GitHub

Builds, once per origin, the two roles whose settings the discovery documents come from.

Called by api() Tokens and grants oauthRoute(): RESOURCE Token validation and limits validateMcpToken() Token exchange (RFC 8693)

/** The two roles for one origin, built once: every URL the library publishes starts from `origin`. */function serversFor(origin: string): Servers {

One pair per origin MCP request

WhatReturns the authorization server and the resource server for one origin. Every URL the library publishes is built from that origin.

WhyThe library's role-based authorization server takes a fixed issuer, so a server built for the site cannot serve a local run and the other way round. Building per origin keeps one code path for both.

  // Reuse the pair already built for this origin.  const known = servers.get(origin)  if (known !== undefined) return known

Reuse what is built MCP request

WhatIf the module-level map servers already has a pair for this origin, it is returned at once.

WhyConstructing the servers validates every option and builds the protected resource metadata. Doing that once per Worker isolate keeps the work off every request after the first. The map lasts as long as the isolate.

  // The address of the one resource tokens are issued for.  const resourceUrl = `${origin}/mcp/demo`

The resource's URL MCP request

WhatresourceUrl is <origin>/mcp/demo, the one protected resource.

WhyIt is the audience every token is bound to (RFC 8707), the resource in the protected resource metadata, and the base of that metadata's URL. The MCP specification requires a host to send it as the resource parameter. The library also accepts a request without one, binding the token to this resource by default, and refuses any other value.

resourceUrl = https://joelstevick.com/mcp/demo

  // The authorization server: tokens and client registration (consent is authorize() below, with its helpers).  const authorization = new OAuthAuthorizationServer<Env>({    issuer: origin,

The authorization server and its issuer MCP request

WhatBuilds the library's OAuthAuthorizationServer with issuer set to the origin. The library serves its RFC 8414 metadata at <issuer>/.well-known/oauth-authorization-server, built from this constructor's options (the endpoints, registration and scopes set on the following lines) plus its own fixed capabilities: response_types_supported ["code"], code_challenge_methods_supported ["S256"] and authorization_response_iss_parameter_supported true.

WhyThe host reaches this document from the authorization_servers entry in the resource metadata, so the issuer here must equal that entry, which is the same origin. The library adds iss to the authorization redirect, so a host can check that the code came from the issuer it discovered (RFC 9207, the mix-up defence). This object serves tokens and client registration; consent is the demo app's own authorize(), which uses the library's helpers.

    resources: [resourceUrl],

The resources it issues tokens for MCP request

Whatresources lists one resource, <origin>/mcp/demo. The library publishes it as protected_resources, uses it as the default when a request names no resource, and refuses a resource parameter naming anything else.

WhyTokens are audience-restricted: a token issued here is good at /mcp/demo and nowhere else, which the MCP authorization specification requires so that a token cannot be replayed against another server.

Explained in Ep 3: The resource indicator (RFC 8707) and the token's audience From MCP deep dive, Ep 3: MCP Authorization Deep Dive: Scopes, Step-Up and Token Exchange
    authorizeEndpoint: '/oauth/authorize',

The authorization endpoint MCP request

WhatauthorizeEndpoint is /oauth/authorize; the library publishes <origin>/oauth/authorize as authorization_endpoint. It does not serve that path: oauthRoute sends it to the demo app's own authorize(), the consent page.

WhyThe host opens this address in the visitor's browser. Only the application knows who the visitor is and can render the consent page, so the library leaves the page to it and provides helpers (parseAuthRequest, completeAuthorization).

authorization_endpoint: <origin>/oauth/authorize

  // The resource server: checks the token on each MCP request, then hands it to serveMcp.  const resource = new OAuthResourceServer<Env, Props>({    resourceMetadata: { resource: resourceUrl, authorization_servers: [origin], bearer_methods_supported: ['header'], resource_name: 'Your demo documents' },

The protected resource metadata MCP request

WhatBuilds the library's OAuthResourceServer with resourceMetadata: resource <origin>/mcp/demo, authorization_servers [origin], bearer_methods_supported ['header'] and resource_name 'Your demo documents'. The library serves the document, uncached, at <origin>/.well-known/oauth-protected-resource/mcp/demo, adding scopes_supported from requiredScopes (set on the next line, with the Resource server's token validation) with offline_access dropped; the bare /.well-known/oauth-protected-resource path answers 404.

WhyThis is the first document a host reads. The 401 challenge's resource_metadata parameter points to it, and it names the authorization server. bearer_methods_supported is header only (the library accepts no other method), so the token never travels in a URL, where logs would keep it.

resource_name: 'Your demo documents'bearer_methods_supported: ["header"]

Explained in Ep 2: The 401, its metadata link, and the two discovery documents From MCP deep dive, Ep 2: OAuth Deep Dive with an MCP Server (OAuth 2.1, PKCE)
  // Keep the pair for next time.  const made = { authorization, resource }  servers.set(origin, made)  return made}

Keep the pair MCP request

WhatThe two servers are stored in servers under the origin and returned.

WhyserversFor contains no await, so within one isolate two requests cannot interleave inside it, and each origin's pair is built once. The pair holds no request state; clients, grants and tokens are in OAUTH_KV.