DEV Community

Vladimir Terekhov
Vladimir Terekhov

Posted on

One Cloudflare Worker, two kinds of auth: a stateless MCP server with OAuth 2.1 and API keys

I wanted two kinds of clients to use the same MCP URL. Claude and ChatGPT add a remote server as a connector and expect to sign in with OAuth. Developer tools such as Claude Code, Codex and Cursor are happy with a bearer API key in a header. I did not want two endpoints, two sets of tools or a second Worker.

This is how it fits together in one Cloudflare Worker that also serves an Astro site. All code is copied from the repository, which is MIT licensed. The versions are Astro 7, @astrojs/cloudflare 14, @modelcontextprotocol/server 2.4.0 and @cloudflare/workers-oauth-provider 1.2.4.

One Worker, three jobs

The Worker entry is short. Astro's fetch handler goes in as the default handler, and the OAuth provider sits in front of it.

// src/worker.ts
const astro: ExportedHandler<Env> = { fetch: handle };

export default {
  fetch(request, env, context) {
    return handleOAuthRequest(request, env, context, astro);
  },
  async scheduled(_controller, env) {
    // ... OAuth cleanup retries, then the daily 30-day data cleanup
  },
} satisfies ExportedHandler<Env>;
Enter fullscreen mode Exit fullscreen mode

handleOAuthRequest builds an OAuthProvider from the library. That class is the one-Worker shape: requests under apiRoute go to apiHandler with the verified token, the provider answers its own endpoints (/oauth/token, /oauth/register, the /.well-known/ documents), and everything else goes to defaultHandler, which is the Astro site. The consent page at /oauth/authorize is an ordinary server-rendered Astro page.

The library's README now recommends splitting the authorization server and the resource server into two Workers joined by a Service Binding. It still fully supports OAuthProvider for a Worker that is both. I have one resource and one app, so I kept one Worker.

Passing the Astro handler in as a parameter also helps testing. Worker-level tests run in workerd with @cloudflare/vitest-plugin, but they cannot load src/worker.ts because it pulls in Astro's virtual modules. The tests call handleOAuthRequest directly with a stub default handler:

// test/worker/oauth.test.ts
async function dispatch(request: Request) {
  return handleOAuthRequest(request, env, createExecutionContext(), defaultHandler);
}
Enter fullscreen mode Exit fullscreen mode

Storage is split by job: D1 for app data, R2 for uploaded files, and a KV namespace bound as OAUTH_KV, which the provider requires.

A stateless MCP endpoint

The MCP side keeps no session. Every request builds a fresh server for the authenticated account and hands the request to the SDK:

// src/server/mcp/handler.ts
const handler = createMcpHandler(() => createPairpollMcpServer(db, accountId, request.url));
return handler.fetch(request);
Enter fullscreen mode Exit fullscreen mode

createMcpHandler in SDK 2.4.0 serves the 2026-07-28 protocol revision from that per-request factory and, by default, falls back to stateless serving for 2025-era clients. Stateless means no Durable Object and no session table. Each tool call is one HTTP exchange that reads and writes D1. The tools call the same server functions as the REST API, so the MCP server has no logic of its own.

One thing the SDK leaves to you: its handler does no Origin or Host validation. Its docs say to put that in front. Mine is three lines before the handler is built:

// src/server/mcp/handler.ts
const origin = request.headers.get("Origin");
if (origin !== null && origin !== new URL(request.url).origin) {
  return jsonError(403, "invalid_origin", "Send this request from the same origin.");
}
Enter fullscreen mode Exit fullscreen mode

The OAuth provider

Here is the core of the configuration, trimmed to the parts that matter:

// src/server/oauth.ts
return {
  apiRoute: "/mcp",
  apiHandler: { /* checks scope, then calls the MCP handler */ },
  defaultHandler,
  authorizeEndpoint: "/oauth/authorize",
  tokenEndpoint: "/oauth/token",
  clientRegistrationEndpoint: "/oauth/register",
  scopesSupported: [MCP_SCOPE],
  requiredScopes: [MCP_SCOPE],
  resourceMetadata: {
    resource: mcpResource,
    authorization_servers: [origin],
    resource_name: "Pairpoll MCP",
  },
  clientIdMetadataDocumentEnabled: true,
  // resolveExternalToken and tokenExchangeCallback below
};
Enter fullscreen mode Exit fullscreen mode

What each line buys:

  • Client registration. clientRegistrationEndpoint turns on RFC 7591 dynamic client registration. clientIdMetadataDocumentEnabled turns on Client ID Metadata Documents, where the client_id is an HTTPS URL the client controls. The MCP 2026-07-28 revision prefers CIMD and deprecates DCR for new work, but clients still use DCR, so I enabled both. CIMD needs the global_fetch_strictly_public compatibility flag in wrangler.jsonc, because the server fetches the client's document.
  • PKCE. The library accepts only S256 for public clients, as MCP requires. Confidential clients may skip PKCE in the library, so the consent page calls a small requireS256 check on every request and refuses anything else.
  • Resource indicators. Every grant and access token is bound to one registered resource, here https://pairpoll.com/mcp. The token response includes that resource, and a token is accepted only on the route its audience covers.
  • Hashed tokens. The provider stores tokens, codes and client secrets in KV only as hashes. The props I attach to a grant are encrypted with a key that only the token holder can unwrap.

I added two things around the provider. Registration and token requests are rate limited per IP in D1, and the token endpoint refuses bodies over 8 KB before the library parses them.

The 401 challenge

A client that knows nothing about the server starts with an unauthenticated request. This is the live response:

$ curl -si -X POST https://pairpoll.com/mcp -H "Content-Type: application/json" -d '{}'
HTTP/2 401
www-authenticate: Bearer realm="OAuth", resource_metadata="https://pairpoll.com/.well-known/oauth-protected-resource/mcp", scope="mcp:tools"
Enter fullscreen mode Exit fullscreen mode

The provider writes that header. The client follows resource_metadata to the RFC 9728 document:

{"resource":"https://pairpoll.com/mcp","authorization_servers":["https://pairpoll.com"],"scopes_supported":["mcp:tools"],"bearer_methods_supported":["header"],"resource_name":"Pairpoll MCP"}
Enter fullscreen mode Exit fullscreen mode

From there it reads /.well-known/oauth-authorization-server, which lists the endpoints, code_challenge_methods_supported: ["S256"] and client_id_metadata_document_supported: true.

One detail caught my eye in the docs: requiredScopes is advertised, not enforced. The handler has to check the scope itself, so apiHandler does:

// src/server/oauth.ts
if (oauthContext.props.access === "oauth" && !oauthContext.auth.scope.includes(MCP_SCOPE)) {
  return insufficientScope(oauthContext.auth, [MCP_SCOPE]);
}
Enter fullscreen mode Exit fullscreen mode

API keys on the same endpoint

Existing users have API keys that start with ppk_. The provider has a hook for credentials it did not issue:

// src/server/oauth.ts
async resolveExternalToken({ request, env }) {
  const auth = await authenticate(env.DB, request);
  if (!auth || auth.kind !== "api_key") return null;
  return {
    props: { accountId: auth.accountId, access: "api_key" } satisfies OAuthGrantProps,
    audience: mcpResource,
  };
},
Enter fullscreen mode Exit fullscreen mode

The library runs this only after its own token lookup fails, and never for a token in its own userId:grantId:secret format. So an expired OAuth token is answered as invalid and never falls through to the API key check. The callback must return an audience, which is the local resource where the key is accepted.

The library docs are frank that accepting API keys like this sits outside the MCP authorization profile. That is a trade I made on purpose: an API key in a header is what Claude Code, Codex and Cursor configs expect, and the key is minted by this same app, not passed through to another API.

Both paths end in the same function with an account ID. The access prop tells it whether to apply OAuth-only checks, such as the scope check above.

Why there is a D1 table next to KV

KV is eventually consistent and has no atomic insert. Two things needed stronger guarantees than that.

First, an authorization code must work once, even under concurrent exchanges. A test fires two exchanges of the same code at once and expects exactly one 200 and one 400. The provider's tokenExchangeCallback claims the grant in D1, where the insert is atomic:

// src/server/oauth-grants.ts
const { meta } = await db.prepare(`
  INSERT INTO oauth_grant_states (account_id, grant_id, code_exchanged_at)
  VALUES (?, ?, ?)
  ON CONFLICT (account_id, grant_id) DO NOTHING
`).bind(accountId, grantId, Date.now()).run();
return meta.changes === 1;
Enter fullscreen mode Exit fullscreen mode

Second, disconnecting an app must take effect at once. Every MCP call with an OAuth token reads the grant ID out of the token and checks the D1 row for revoked_at. Revoking writes D1 first and marks the row cleanup_pending, then revokes the grant in KV. If the KV call fails, the daily cron retries it. Deleting an account goes through the same path for every connected app.

The consent page uses D1 too. When it shows the Approve button, it stores a hash of the consent handle with the signed-in account and a ten-minute expiry. Approving deletes that row with DELETE ... RETURNING, so a consent can be used once, by the account that saw it.

Tool annotations

Each tool has a title and explicit hints. Claude's connector directory asks for them, and clients can use them to decide when to ask the user before calling a tool.

// src/server/mcp/tools.ts
server.registerTool("open_poll", {
  ...oauthTool,
  title: "Open a poll",
  annotations: { readOnlyHint: false, destructiveHint: true },
  description: "Open a draft after 2 to 16 files are ready. Opening freezes its settings and files and returns the voter share link.",
  inputSchema: z.object({ pollId }),
}, ...);
Enter fullscreen mode Exit fullscreen mode

Opening a poll deletes nothing, but it freezes the poll for good, so I marked it destructive. oauthTool adds _meta.securitySchemes with the mcp:tools scope to every tool.

Chat apps cannot attach files

This shaped the tool list more than anything else. A poll needs 2 to 16 images or videos, and chat apps cannot pass an attached file to a connector. I also did not want the server to fetch files from arbitrary URLs, because that opens it to abuse.

So create_poll makes an empty draft, and a separate tool returns a browser link to that draft's upload page:

// src/server/mcp/tools.ts
description: "Return the browser page for adding local files to a draft poll. Use this because MCP chat clients cannot pass attached images or videos to Pairpoll, and Pairpoll does not fetch remote URLs.",
Enter fullscreen mode Exit fullscreen mode

The server's instructions say the same in one line: create a draft, send the user to the upload link, then open the poll. The link goes through the normal sign-in if the browser is signed out. The model reads the tool description, so putting the reason there means it explains the extra step instead of trying to work around it.

What surprised me

  • Token rate limits and shared IPs. I first limited token requests to 120 an hour per IP. That was too low: hosted connectors such as Claude and ChatGPT refresh tokens for many users from a few shared addresses. The limit is now 3,000 an hour, with a comment saying why.
  • The Astro adapter adds bindings. By default @astrojs/cloudflare adds a KV binding for Astro sessions and an Images binding. session: false and imageService: "compile" in astro.config.mjs keep them out, so the only KV namespace is the one OAuth needs.
  • Astro 7 notices coding agents. When it detects one, astro dev runs in the background. npx astro dev --ignore-lock keeps it in the foreground.
  • OAuth needs a public URL to test properly. I postponed OAuth until after the first deploy. Locally I test API keys against astro dev and the OAuth flow against the built Worker in workerd, then once more in production with a test client.

What I left out

  • Two Workers. The split shape is the library's recommendation, but one resource did not justify it.
  • More than one scope. There is one scope, mcp:tools. Every tool needs the same access, so per-tool scopes would add consent screens and nothing else.
  • Sessions. No Durable Objects and no session IDs. Each request stands alone.
  • Fetching files from URLs. Covered above.
  • An interactive UI inside the chat. The tools return JSON text and structured content only.
  • ChatGPT's app directory. Its review needs a test login without email or magic links, and Pairpoll signs in with an email link only. Anyone can still add the server as a custom connector.

The project

The app is Pairpoll, a free poll where voters pick the better of two images or videos until their top 1, 3 or 5 is settled, and the creator gets each voter's list plus an overall ranking. The code is at https://github.com/BuildShipGrowRepeat/pairpoll and the site is https://pairpoll.com.

Top comments (0)