An MCP server on Workers with D1
For: a developer who wants an MCP server whose callers sign in with authtempo.
What it does: authtempo init writes a Worker on D1 with one MCP tool, whoami. An MCP client signs a person in, gets an access token, and calls the tool.
Before you start
Section titled “Before you start”- Node 22.18 or newer, and pnpm 12.8.1.
- The
@authtempopackages are on npm. Add the CLI to your app withpnpm add -D @authtempo/cli, and run each command aspnpm exec authtempo …. The CLI reference lists each command. - The CLI, built in the repo. Run it from this repo tells how.
- A Cloudflare account, for the deploy and the MCP client at the end.
- A domain on Cloudflare, for the route of the Worker. Workers on D1 has the deploy steps.
- In the folder
examplesof the clone, write the app into the foldermy-mcp.
authtempo init my-mcp --stack mcp-server- In
examples/my-mcp, run the next steps that the command prints, up topnpm dev. They install the packages, copy.dev.vars.exampleto.dev.vars, and migrate the local D1 database. - Write a secret of 32 characters or more into
AUTH_SECRETof.dev.vars. Make it withopenssl rand -base64 32. Then runpnpm dev. - Read
src/auth.ts. It turns on the OAuth provider with one resource, the scopemcp:tools, no dynamic registration, and the guarded fetch.
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 }), }, });}- Read
src/index.ts. It mounts the metadata documents, the auth routes, and the MCP route.requireMcpAuthlets a request reach the tool only with a token for/mcpthat holdsmcp:tools.
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>;- Read
src/mcp.ts. It is the one file that imports the MCP SDK. The toolwhoamianswers the token subject, the client id, and the scopes of the caller. The token subject is the user id for a public client, and the pairwise subject for a pairwise client.
/** * 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);}- Run the test. It plays the MCP client on a local D1 database.
pnpm turbo run test --filter=my-appThe test signs a person in by magic link. Then it sends the authorize request with the URL of a client metadata document and PKCE, allows the consent, and exchanges the code. Last, it calls whoami with the access token.
- In
wrangler.jsonc, add a route or a custom domain for your origin, and setBASE_URLto that origin. Theworkers.devaddress is off, so the Worker has no other address. - Deploy the Worker as in steps 7 to 13 of Workers on D1.
- In your MCP client, add the server URL, such as
https://app.example.com/mcp. The app has no dynamic registration, so the client must have a client metadata document. - Let the client connect. The first request gets 401, with the URL of the resource metadata in
WWW-Authenticate. - Sign in by magic link on the page that the client opens, and allow the client on the consent page.
- Ask the client to call the tool
whoami.
The test passes. After step 13 the tool answers the token subject, the URL of the client metadata document as the client id, and mcp:tools. The client of this guide is public, so the token subject is your user id.