Joel Stevick

MCP server · Token · /oauth/token · stage 1 of 2

Tokens and grants

After the visitor allows an app, the app posts the authorization code and its PKCE verifier to /oauth/token. It gets an access token valid for one hour and a refresh token, and later posts the refresh token to the same endpoint for a new pair. The OAuth library implements the endpoint for the authorization-code and refresh-token grant types (the two kinds of request it accepts there). The demo app's code names the endpoint's path, declares what a grant (the library's record of what one app may do for one demo account) carries (the account's id, encrypted in the grant) and names the offline_access scope. oauthRoute passes every request to the library except the consent page, the MCP endpoint and its protected resource metadata, the document store and a token-exchange request. The library keeps grants and tokens in OAUTH_KV, a Cloudflare KV namespace (a key-value store), and stores each token only as its SHA-256 hash.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
Claude Code after /mcp: "Signed in and connected to my-docs."
Claude Code after Allow was pressed. The browser was redirected to Claude Code's local callback with the authorization code. Claude Code exchanged the code at the token endpoint with its PKCE verifier, and the MCP server now accepts its requests. 2026-11-29, Terminal on macOS, Claude Code 2.1.332, against the live MCP server, which is newer than the pinned commit
demo/src/oauth.ts12 / 12 lines on this page explainedlines 28-29,39-40,76,114-116,169-172 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.

demo/src/oauth.ts Who may call the MCP server.

OFFLINE

constant · lines 28–29View on GitHub

The scope a client asks for when it wants a refresh token.

/** Clients ask for refresh tokens with this scope; the library issues one on every code exchange regardless. Not a permission to show. */const OFFLINE = 'offline_access'

offline_access: the refresh-token scope Module load

WhatOFFLINE is 'offline_access', the OpenID Connect scope a client uses to ask for a refresh token. The authorization server lists it in scopes_supported. When the client asks for it, the consent form carries it as a hidden field, and authorize() adds it to the grant on Allow (Authorize and consent).

WhyIt grants no access to documents, so it gets no checkbox, the site's record of the decision leaves it out, and the demo page does not list it among a connected app's permissions. In library 1.2.4 it also does not control refresh tokens: the token endpoint issues one whenever refreshTokenTTL is not 0 (default 30 days), whatever the grant's scopes.

OFFLINE = 'offline_access'library 1.2.4: refreshTokenTTL default 30 days

Props

interface · lines 39–40View on GitHub

What a grant carries for the demo app: the id of one demo account.

// What a grant carries: the id of the demo it was given for.interface Props { demo: string }

A grant names one account Type only

WhatProps is { demo: string }. completeAuthorization writes { demo: demo.id } into the grant. The library encrypts the props with AES-GCM under a fresh 256-bit key per grant and wraps that key with a key derived from each token, so only someone presenting a valid code, access token or refresh token can read the props back.

WhyThis is how a token reaches exactly one demo account's documents. On every MCP request validateToken decrypts the props, and the handler passes ctx.props.demo to serveMcp as the account to load. Nothing in the MCP request can name a different account.

props: { demo: <demo id> }library 1.2.4: AES-GCM 256, key wrapped with AES-KW

serversFor(): TOKEN

segment · lines 76–76View on GitHub

The token endpoint's path.

    tokenEndpoint: '/oauth/token',

The token endpoint MCP request

WhattokenEndpoint is /oauth/token. The library publishes <origin>/oauth/token as both token_endpoint and revocation_endpoint in the authorization server metadata. For grant_type=authorization_code it finds the grant from the code, since codes and tokens have the form <user id>:<grant id>:<32 random characters>. It checks the code's hash, the client, the redirect_uri, the resource indicator, and that the SHA-256 of code_verifier equals the stored S256 challenge. It then issues an access token (3,600 s) and a refresh token. For grant_type=refresh_token it rotates the refresh token: it issues a new one each time and still accepts the previous one. In both grants a scope parameter can only narrow the grant's scopes, and a request that names none of them gets invalid_scope. A POST with a token and no grant_type is a revocation (RFC 7009).

WhyPKCE is what makes a public client safe. Claude Code's client metadata says token_endpoint_auth_method none, so it has no secret, and an intercepted code is useless without the verifier only the client holds. A code is valid for as long as the grant's first KV write lasts (600 s) and works once; presenting it again revokes the whole grant. The user id in every token is the demo account's id (completeAuthorization's userId), so all the tokens of one account can be listed and revoked together.

token_endpoint: <origin>/oauth/tokencode_challenge_methods_supported: ["S256"]library 1.2.4: accessTokenTTL default 3,600 slibrary 1.2.4: code valid 600 s, oncelibrary 1.2.4: TOKEN_LENGTH = 32

Explained in Ep 2: The code exchange at the token endpoint, and PKCE's verifier From MCP deep dive, Ep 2: OAuth Deep Dive with an MCP Server (OAuth 2.1, PKCE)
Explained in Ep 3: Expiry and refresh: no new scope, rotation, the 30-day grant From MCP deep dive, Ep 3: MCP Authorization Deep Dive: Scopes, Step-Up and Token Exchange

api()

function · lines 114–116View on GitHub

The library's helpers over OAUTH_KV, for the demo app's own code outside the library's endpoints.

Called by appsOf() Listing and disconnecting apps grantsRoute() Listing and disconnecting apps oauthRoute(): /oauth/authorize The consent page revokeGrants() Listing and disconnecting appsCalls serversFor(): DISCOVERY The discovery documents

/** The library's helpers for the store, whichever origin asks: the store is one. */const api = (env: Env, origin = SITE): OAuthHelpers => serversFor(origin).authorization.getOAuthApi(env)

One store for every origin MCP request

Whatapi returns the OAuthHelpers of the authorization server for an origin, SITE by default: parseAuthRequest, beginConsent, completeAuthorization, listUserGrants, revokeGrant and the rest, bound to env so they read and write OAUTH_KV.

WhyThe KV keys contain no origin (grant:<demo id>:<grant id>, token:<demo id>:<grant id>:<hash>, client:<client id>), so helpers built for SITE read and write the same records as the servers built for any other origin on the same store. Callers that have no request origin therefore use the site's server: the demo page's Connected apps and Disconnect, the admin view of a demo account, and the idle purge's revokeGrants. Each grant still records its own resource, <origin>/mcp/demo, so its tokens validate only on that origin. The consent page passes its own origin, because parseAuthRequest refuses a request whose URL is not that issuer's authorize endpoint, and the library puts the issuer in the redirect's iss parameter.

default origin: SITE = https://joelstevick.com

oauthRoute(): TOKEN

segment · lines 169–172View on GitHub

The fall-through to the library's authorization server.

  // Everything else goes to the library's authorization server.  return authorization.fetch(request, env, context)}

Every other request goes to the library MCP request

WhatA request reaches authorization.fetch when it is not for the consent page, the MCP endpoint or its protected resource metadata, or the document store, is not a token-exchange grant, and was not refused by the address limit. The library answers the authorization server metadata (GET), the token endpoint and the registration endpoint, including their CORS preflight. Any other path, such as /oauth/anything, gets 404, because the role-based server has no default handler.

WhyApart from the token-exchange grant (Token exchange, RFC 8693), which the library cannot issue for another resource, the demo app implements none of the token protocol. Code exchange, PKCE verification, refresh rotation, revocation and the error codes therefore follow OAuth 2.1 as the library implements it, and the demo app's own code is limited to identifying the visitor and asking what they allow.

Explained in Ep 3: What the token endpoint returns: opaque bearer, expiry, refresh, scope From MCP deep dive, Ep 3: MCP Authorization Deep Dive: Scopes, Step-Up and Token Exchange