Protect your MCP server
For: a developer who serves an MCP server and wants authtempo to sign in its callers.
What it does: core mints the access tokens. requireMcpAuth lets a request reach a tool only with a valid token for the MCP resource.
Before you start
Section titled “Before you start”- An auth app that runs authtempo on a Cloudflare Worker. A getting started tutorial makes one.
- Read Be the OAuth and OIDC provider for MCP clients. This guide uses that provider.
- Node 22.18 or newer for the tools of the project.
- Turn on
oauthin the config of the auth app.- Set
oauth.resourcesto the URL of the MCP route, such ashttps://app.example.com/mcp. - Set
oauth.scopesto{ "mcp:tools": "Use the tools of this app" }, or to your own text. - Set
oauth.registrationto{ dynamic: false }. Dynamic registration is off by default since plan 12e. The MCP authorization revision calls it deprecated. - Set
oauth.fetchtoguardedFetch({ resolve: dohResolve(fetch), fetch }). A client then registers by the URL of its metadata document. - Core implements the metadata document draft -02, and accepts the documents of -00 that MCP 2026-07-28 pins.
- Set
- Mount
auth.wellKnown(request)for every path that starts with/.well-known/at the origin root. - Wrap the handler of the
/mcproute inrequireMcpAuthof@authtempo/verify/mcp.- Pass the
authof core as the source when the MCP route is in the same Worker as the auth app. - Pass
resourcewith the same URL asoauth.resources, andscopes: ["mcp:tools"].
- Pass the
The example app examples/mcp-server does these steps. Its config of core sets each option of step 1, with the reason beside it.
import { createD1Adapter, createD1Limiter } from "@authtempo/adapter-d1";import { type Auth, createAuth, type MailPort } from "@authtempo/core";import { dohResolve, guardedFetch } from "./fetch.js";
/** The bindings and vars of wrangler.jsonc, and the secret of `wrangler secret put AUTH_SECRET`. */export interface Env { DB: D1Database; BASE_URL: string; AUTH_SECRET: string;}
/** The resource of the MCP route: the `aud` of its access tokens. */export function mcpResource(env: Env): string { return `${env.BASE_URL}/mcp`;}
/** The scope that every call to a tool of this server needs. */export const MCP_SCOPE = "mcp:tools";
/** The auth app: sign-in, the OAuth provider for MCP clients, and the access tokens. */export function makeAuth(env: Env, mail: MailPort): Auth { return createAuth({ baseURL: env.BASE_URL, secret: env.AUTH_SECRET, trustedOrigins: [env.BASE_URL], storage: createD1Adapter(env.DB), // The owned limiter counts in D1, so every isolate shares one count. // The default limiter counts per isolate, and is for tests only. limiter: createD1Limiter(env.DB), mail, // An OAuth access token is a JWT that core signs, so oauth needs jwtMint. // The defaults: EdDSA, and a life of 15 minutes. jwtMint: {}, oauth: { // The one resource: the MCP route. A token for it is good at /mcp only. resources: [mcpResource(env)], // The consent page shows this text for the scope. scopes: { [MCP_SCOPE]: "Use the tools of this server" }, // No RFC 7591 registration: the MCP authorization revision calls it // deprecated. A client registers by the URL of its metadata document. registration: { dynamic: false }, // Core fetches a metadata document at a URL that a stranger chose. The // guarded fetch refuses a host with a private address (src/fetch.ts). // Pass the global fetch bare: a call with a receiver throws on workerd. fetch: guardedFetch({ resolve: dohResolve(fetch), fetch }), }, });}The Worker mounts the metadata documents, the auth routes, and the wrapped MCP route.
import type { MailPort } from "@authtempo/core";import { requireMcpAuth } from "@authtempo/verify/mcp";import { type Env, MCP_SCOPE, makeAuth, mcpResource } from "./auth.js";import { mcpHandler } from "./mcp.js";
export type { Env } from "./auth.js";
/** * Your mail transport. Core calls `send` once per mail: a magic link, an * email code, a reset link. Replace the body with a call to your mail * provider. Until then a sign-in request answers 500, so a deploy with no * mail fails at once and not in silence. */export const mail: MailPort = { async send() { throw new Error("my-app: no mail transport; replace mail.send in src/index.ts"); },};
/** What the app takes from outside. The test passes a mail port that keeps the mails. */export interface Deps { mail: MailPort;}
/** The app: the auth routes, the OAuth metadata, and the MCP route. */export function createApp(env: Env, deps: Deps) { const auth = makeAuth(env, deps.mail); // The source is core's auth in this same Worker: it reads the token with // no fetch, so the Worker never fetches its own host. const mcp = requireMcpAuth(auth, mcpHandler, { resource: mcpResource(env), scopes: [MCP_SCOPE], }); return { auth, async fetch(request: Request): Promise<Response> { const { pathname } = new URL(request.url); // The metadata documents live at the origin root, where an MCP client looks. if (pathname.startsWith("/.well-known/")) return auth.wellKnown(request); if (pathname.startsWith("/auth/")) return auth.handle(request); if (pathname === "/mcp") return mcp(request); return new Response("not found", { status: 404 }); }, };}
// One app per isolate. The bindings stay the same for the life of the isolate.let app: ReturnType<typeof createApp> | null = null;const appOf = (env: Env) => (app ??= createApp(env, { mail }));
export default { fetch(request: Request, env: Env): Promise<Response> { return appOf(env).fetch(request); }, // The cron trigger of wrangler.jsonc runs this. It deletes the rows that no flow can use. async scheduled(_controller: ScheduledController, env: Env, ctx: ExecutionContext) { ctx.waitUntil(appOf(env).auth.api.sweepExpired()); },} satisfies ExportedHandler<Env>;The MCP route is a seam over the MCP SDK. It is the one file that imports the SDK, and it serves the tool whoami.
/** * The seam to the MCP SDK (@modelcontextprotocol/server 2.3.1). This is the * one file of the app that imports the SDK. It has two calls: `whoami` is * the answer of the one tool, and `mcpHandler` serves one request. Another * SDK plugs into the same two calls. */import type { McpCaller } from "@authtempo/verify/mcp";import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
/** The answer of the tool `whoami`: who calls, from which client, with which scopes. */export function whoami(caller: McpCaller): { userId: string; clientId: string; scopes: string[] } { return { userId: caller.userId, clientId: caller.clientId, scopes: [...caller.scopes] };}
/** * Serves one MCP request for a caller that `requireMcpAuth` let through. * One server for each request, with no session: the "stateless" legacy * option answers the 2025-era requests from the same factory. */export function mcpHandler(request: Request, caller: McpCaller): Promise<Response> { const handler = createMcpHandler( () => { const server = new McpServer( { name: "my-app", version: "0.0.0" }, { capabilities: { tools: {} } }, ); server.registerTool( "whoami", { title: "Who am I", description: "Answers the token subject, the client id, and the scopes of the caller.", }, async () => { const answer = whoami(caller); return { content: [{ type: "text" as const, text: JSON.stringify(answer) }], structuredContent: answer, }; }, ); return server; }, { legacy: "stateless" }, ); return handler.fetch(request);}The guarded fetch refuses a metadata host with a private address.
/** * The guarded fetch for client metadata documents (`oauth.fetch` of core). * * A client id of an MCP client can be the https URL of its metadata document, * so core fetches a URL that a stranger chose. This fetch refuses a host whose * name resolves to a private address (server-side request forgery). * * Four platform facts, read 2026-10-17: * - A Worker fetches by URL, not by IP address * (developers.cloudflare.com/workers/platform/known-issues/, "Fetch to IP addresses"). * No page says that Workers refuse a name that resolves to a private address. * So the app owns this guard, and the guard does not rely on the platform. * - A fetch to the Worker's own host, without the flag global_fetch_strictly_public, * goes to the zone's origin and skips every Worker on the URL. With the flag, it can * loop back to the same Worker * (developers.cloudflare.com/workers/configuration/compatibility-flags/, read 2026-10-17). * So a Verifier with a JWKS URL on its own host is the one case that the flag changes. * This example sets no global_fetch_strictly_public, and core refuses its own host as a client id. * - A Worker cannot fetch an address that Cloudflare owns: error 1024 * (developers.cloudflare.com/workers/observability/errors/, read 2026-10-17). * No page says that a deployed Worker can fetch https://cloudflare-dns.com/dns-query. * An owner-run probe must show it before the stack is published. * - The DoH JSON format "has no formal RFC and its schema is not guaranteed to be stable" * (developers.cloudflare.com/changelog/post/2026-07-28-improved-record-display-format/, * read 2026-10-17). That change touches other record types, not A or AAAA. A changed * `data` form fails closed here: a text that is no address is not public. A move to * the DoH wireformat (RFC 8484) waits for the probe. * * The gap: the name can answer another address at the connect than at this check * (DNS rebinding). Workers give no way to pin the address of a fetch. So core's own * host rules, `redirect: "manual"`, the 10-second timeout, and the 8 KB cap stay the * first line, and this check is the second. */
/** What the guard needs: a name lookup and the fetch that sends the request. */export interface GuardDeps { /** Every A and AAAA answer of a name. An empty list means no address. The signal ends the lookup. */ resolve(name: string, signal?: AbortSignal): Promise<string[]>; fetch: typeof fetch;}
/** * The private IPv4 classes. They are the blocks of RFC 6890 section 2.2.2 with * "Global: False" (read 2026-10-17). Multicast (RFC 5771) is one too, and * RFC 6890 does not list it. * The 6to4 relay 192.88.99.0/24 is the one RFC 6890 block with "Global: True". * One line for each class. */const PRIVATE_V4: readonly (readonly [base: string, bits: number])[] = [ ["0.0.0.0", 8], // "This host on this network" ["10.0.0.0", 8], // Private-Use ["100.64.0.0", 10], // Shared Address Space (carrier-grade NAT) ["127.0.0.0", 8], // Loopback ["169.254.0.0", 16], // Link Local, with the cloud metadata address 169.254.169.254 ["172.16.0.0", 12], // Private-Use ["192.0.0.0", 24], // IETF Protocol Assignments ["192.0.2.0", 24], // Documentation, TEST-NET-1 (RFC 5737) ["192.168.0.0", 16], // Private-Use ["198.18.0.0", 15], // Benchmarking ["198.51.100.0", 24], // Documentation, TEST-NET-2 (RFC 5737) ["203.0.113.0", 24], // Documentation, TEST-NET-3 (RFC 5737) ["224.0.0.0", 4], // Multicast (RFC 5771) ["240.0.0.0", 4], // Reserved, with the limited broadcast 255.255.255.255];
/** The IPv4 address as an unsigned 32-bit number, or null. Only four decimal parts, no leading zero. */function parseV4(text: string): number | null { const parts = text.split("."); if (parts.length !== 4) return null; let value = 0; for (const part of parts) { if (!/^(0|[1-9][0-9]{0,2})$/.test(part)) return null; const n = Number(part); if (n > 255) return null; value = value * 256 + n; } return value;}
function isPrivateV4(address: number): boolean { return PRIVATE_V4.some(([base, bits]) => { const start = parseV4(base); if (start === null) return true; const size = 2 ** (32 - bits); return Math.floor(address / size) === Math.floor(start / size); });}
/** The IPv6 address as eight 16-bit groups, or null. A dotted IPv4 tail is allowed. */function parseV6(text: string): number[] | null { if (!/^[0-9a-fA-F:.]+$/.test(text)) return null; let body = text; const tail: number[] = []; if (body.includes(".")) { const at = body.lastIndexOf(":"); const v4 = parseV4(body.slice(at + 1)); if (v4 === null) return null; tail.push(Math.floor(v4 / 65536), v4 % 65536); body = body.slice(0, at + 1); // "::ffff:" keeps no trailing colon; "::" stays as it is. if (!body.endsWith("::")) body = body.slice(0, -1); } const groupsOf = (s: string): number[] | null => { if (s === "") return []; const out: number[] = []; for (const g of s.split(":")) { if (!/^[0-9a-fA-F]{1,4}$/.test(g)) return null; out.push(Number.parseInt(g, 16)); } return out; }; const halves = body.split("::"); if (halves.length > 2) return null; if (halves.length === 1) { const all = groupsOf(body); return all !== null && all.length + tail.length === 8 ? [...all, ...tail] : null; } const head = groupsOf(halves[0] ?? ""); const rest = groupsOf(halves[1] ?? ""); if (head === null || rest === null) return null; const missing = 8 - head.length - rest.length - tail.length; if (missing < 1) return null; return [...head, ...new Array<number>(missing).fill(0), ...rest, ...tail];}
/** The IPv4 address of two 16-bit groups is private. */function v4Private(hi: number, lo: number): boolean { return isPrivateV4(hi * 65536 + lo);}
/** True when groups `from` to `to - 1` are all zero. */function zeros(g: readonly number[], from: number, to: number): boolean { return g.slice(from, to).every((x) => x === 0);}
/** * The private IPv6 classes. Sources, read 2026-10-17: RFC 6890 section 2.2.3, and the RFC * on each line. A form that holds an IPv4 address is decided by that address, because a * translator can reach it. One line for each class. */const PRIVATE_V6: readonly ((g: readonly number[]) => boolean)[] = [ (g) => zeros(g, 0, 6) && v4Private(g[6] ?? 0, g[7] ?? 0), // ::/96 IPv4-compatible (RFC 4291), with :: and ::1 (g) => zeros(g, 0, 5) && g[5] === 0xffff && v4Private(g[6] ?? 0, g[7] ?? 0), // ::ffff:0:0/96 IPv4-mapped (RFC 4291) (g) => zeros(g, 0, 4) && g[4] === 0xffff && g[5] === 0 && v4Private(g[6] ?? 0, g[7] ?? 0), // ::ffff:0:0:0/96 IPv4-translated (RFC 2765) (g) => g[0] === 0x64 && g[1] === 0xff9b && zeros(g, 2, 6) && v4Private(g[6] ?? 0, g[7] ?? 0), // 64:ff9b::/96 NAT64 (RFC 6052) (g) => g[0] === 0x2002 && v4Private(g[1] ?? 0, g[2] ?? 0), // 2002::/16 6to4 (RFC 3056) (g) => g[0] === 0x100 && zeros(g, 1, 4), // 100::/64 Discard-Only (RFC 6666) (g) => g[0] === 0x2001 && g[1] === 0xdb8, // 2001:db8::/32 Documentation (RFC 3849) (g) => ((g[0] ?? 0) & 0xfe00) === 0xfc00, // fc00::/7 Unique-Local (RFC 4193) (g) => ((g[0] ?? 0) & 0xffc0) === 0xfe80, // fe80::/10 Link-Local (RFC 4291) (g) => ((g[0] ?? 0) & 0xffc0) === 0xfec0, // fec0::/10 site-local, deprecated (RFC 3879) (g) => ((g[0] ?? 0) & 0xff00) === 0xff00, // ff00::/8 Multicast (RFC 4291)];
function isPrivateV6(groups: readonly number[]): boolean { return PRIVATE_V6.some((rule) => rule(groups));}
/** * True when the address is in no private class. A text that is no IPv4 or * IPv6 address is not public: the guard refuses what it cannot read. */export function isPublicAddress(address: string): boolean { const v4 = parseV4(address); if (v4 !== null) return !isPrivateV4(v4); if (!address.includes(":")) return false; const v6 = parseV6(address); return v6 !== null && !isPrivateV6(v6);}
/** DNS record types of the dns-json answer (RFC 1035 and RFC 3596). */const TYPE_A = 1;const TYPE_AAAA = 28;
/** * A lookup of the A and AAAA answers through Cloudflare's DNS over HTTPS * (`https://cloudflare-dns.com/dns-query` with `accept: application/dns-json`). * With no Node compat, a Worker has no other name lookup: `node:dns` needs nodejs_compat * (developers.cloudflare.com/changelog/post/2025-01-28-nodejs-compat-improvements/, read 2026-10-17). */export function dohResolve( fetchFn: typeof fetch,): (name: string, signal?: AbortSignal) => Promise<string[]> { const failed = () => new Error("the DNS lookup of the client metadata host failed"); const ask = async ( name: string, type: "A" | "AAAA", code: number, signal: AbortSignal | undefined, ): Promise<string[]> => { const url = new URL("https://cloudflare-dns.com/dns-query"); url.searchParams.set("name", name); url.searchParams.set("type", type); const res = await fetchFn(url, { headers: { accept: "application/dns-json" }, redirect: "manual", ...(signal ? { signal } : {}), }); if (res.status !== 200) { await res.body?.cancel(); throw failed(); } let body: unknown; try { body = await res.json(); } catch { throw failed(); } if (typeof body !== "object" || body === null) return []; const answer = (body as { Answer?: unknown }).Answer; if (!Array.isArray(answer)) return []; // A CNAME line has another type. Its target's address comes as its own line. return answer .filter((a): a is { type: number; data: string } => { const r = a as { type?: unknown; data?: unknown }; return r.type === code && typeof r.data === "string"; }) .map((a) => a.data); }; return async (name, signal) => { const [a, aaaa] = await Promise.all([ ask(name, "A", TYPE_A, signal), ask(name, "AAAA", TYPE_AAAA, signal), ]); return [...a, ...aaaa]; };}
/** The lookup, or a rejection when the caller's signal aborts first (core's 10-second timeout). */function untilAbort<T>(work: Promise<T>, signal: AbortSignal | null): Promise<T> { if (signal === null) return work; if (signal.aborted) return Promise.reject(signal.reason); return new Promise<T>((resolve, reject) => { signal.addEventListener("abort", () => reject(signal.reason), { once: true }); work.then(resolve, reject); });}
/** * A fetch for `oauth.fetch` that sends a request only to an https host whose * every address is public. Wire it as `guardedFetch({ resolve: dohResolve(fetch), fetch })`. */export function guardedFetch(deps: GuardDeps): typeof fetch { // Take the members once. A call as `deps.fetch(...)` passes `deps` as `this`, and the // global fetch of workerd throws "Illegal invocation" for that receiver. const { resolve, fetch: send } = deps; return async (input, init) => { const request = new Request(input, init); const url = new URL(request.url); if (url.protocol !== "https:") throw new Error("the client metadata URL must be https"); // A trailing dot names the same host. Brackets hold an IPv6 literal. const host = url.hostname.replace(/\.$/, "").replace(/^\[(.*)\]$/, "$1"); const literal = parseV4(host) !== null || host.includes(":"); const addresses = literal ? [host] : await untilAbort(resolve(host, request.signal), request.signal); if (addresses.length === 0) throw new Error("the client metadata host has no address"); if (!addresses.every(isPublicAddress)) throw new Error("the client metadata host resolves to a private address"); // Core sets redirect manual too (spec 8.13). A redirect must not lead past this check. return send(new Request(request, { redirect: "manual" })); };}The same-Worker source
Section titled “The same-Worker source”The auth of core reads the token in the same Worker. It fetches no key set, so the Worker never fetches its own host.
The Cloudflare page on compatibility flags, read 2026-10-17, gives two cases for a fetch to the Worker’s own host:
- Without the flag
global_fetch_strictly_public, the fetch goes to the origin of the zone and skips every Worker on the URL. - With the flag, the fetch can loop back to the same Worker.
So a Verifier with a JWKS URL on its own host is the one case that the flag changes. The example sets no global_fetch_strictly_public.
A server that is not the auth app passes a Verifier of createVerifier as the source. The verify MCP entry lists both sources.
The guarded fetch
Section titled “The guarded fetch”- The URL must be
https:. Anhttp:URL throws before any lookup. - The name resolves through DNS over HTTPS. Each A and AAAA answer must be public.
- One private answer refuses the host, also when the other answers are public. A name with no answer throws.
- The private IPv4 classes are the blocks of RFC 6890 with no global reach, plus multicast.
- The private IPv6 classes are
::1,::,fc00::/7,fe80::/10,fec0::/10,ff00::/8,100::/64, and2001:db8::/32. - An IPv6 form that holds an IPv4 address counts as that IPv4 address. These forms are
::/96,::ffff:0:0/96,::ffff:0:0:0/96,64:ff9b::/96, and2002::/16. - Other blocks of
2001::/23are not refused. - The request goes with
redirect: "manual", as core also sets it. - A name can answer another address at the connect than at the check. Workers give no way to pin the address. Core’s host rules, its 10-second timeout, and its 8 KB cap stay the first line.
The 401 and the 403
Section titled “The 401 and the 403”The route https://app.example.com/mcp with scopes: ["mcp:tools"] answers these headers:
| The request | Status | WWW-Authenticate |
|---|---|---|
| No bearer | 401 | Bearer resource_metadata="https://app.example.com/.well-known/oauth-protected-resource/mcp", scope="mcp:tools" |
| A bearer that is not a valid token for this resource | 401 | Bearer error="invalid_token", resource_metadata="https://app.example.com/.well-known/oauth-protected-resource/mcp", scope="mcp:tools" |
A valid token without mcp:tools |
403 | Bearer error="insufficient_scope", scope="mcp:tools", resource_metadata="https://app.example.com/.well-known/oauth-protected-resource/mcp" |
A source that fails gives 503 with no body, never 401. A request under the DPoP scheme gets a DPoP challenge too. The verify MCP entry lists those answers.
More of the provider
Section titled “More of the provider”Plan 12e adds these to the provider. Each one has a section in the provider guide.
- Confidential clients. A client may hold a secret or sign a client assertion with its key. A public client still sends PKCE on every code.
- A metadata document with
private_key_jwtand its keys is a confidential client. - DPoP. A bound access token reaches the route as
Authorization: DPoPwith a proof of its key. - Token introspection, for a resource server that must know whether a token is live now.
- The app’s own sign-in route,
oauth.signInURL, in place of core’s sign-in page. - A refresh reuse window,
oauth.refreshReuseSeconds. It is off by default: a refresh token sent twice ends its family. - Pairwise subjects.
whoamianswers the token subject, which is the pairwise subject for a pairwise client.
The consent page and the connected apps page are in the provider guide too.
If it fails
Section titled “If it fails”invalid_token: the token is expired, of another resource, or not an OAuth access token. The client must get a new token.insufficient_scope: the token lacksmcp:tools, or a tool threwMcpScopeError. The client must ask for the scopes of the challenge.invalid_client: the client id is unknown. Withdynamic: false, a client id must be the URL of a metadata document that the guarded fetch accepts.- The error “the DNS lookup of the client metadata host failed” means that the resolver did not answer, or did not answer JSON. With
dynamic: false, no client can register then. - Core logs each refusal of the guard as “the fetch failed or timed out”. The log line does not give the reason.