tutorials
Add OAuth 2.1 and PKCE to your MCP server
October 5, 2026

The Claude app will not connect to your MCP server with an API key. Its connector UI has no header field, only an OAuth flow, and the spec is scattered across four RFCs and the MCP authorization doc. Here is the whole flow, built by hand, then the short version.
If you wrote an MCP server and tested it with Claude Code, you probably passed a static Authorization: Bearer header in the client config and it worked on the first try. Then you tried to add the same server as a custom connector in the Claude desktop or web app, and there was nowhere to paste the token. The app does not do static bearer auth. It speaks OAuth 2.1 with discovery, and it expects your server to be the authorization server.
That is the gap this tutorial closes. We will build all six endpoints OAuth-for-MCP needs, on a single Cloudflare Worker, with the PKCE and Dynamic Client Registration pieces that the spec requires and most tutorials skip. Then, near the end, the shorter path.
Why does an MCP server need OAuth instead of a bearer token?
An MCP server needs OAuth because the Claude app's connector UI only supports the OAuth authorization-code flow, not a manually pasted token. Headless MCP clients (Claude Code, scripts, CI) can send a fixed Authorization: Bearer tbx_… header you generate once. The interactive apps cannot: there is no field for it. They discover your auth endpoints, register themselves, send the user through a consent screen, and exchange a code for a token. If your server is not an OAuth authorization server, the "Connect" button has nothing to talk to.
The MCP authorization spec leans entirely on existing OAuth specs rather than inventing anything:
- OAuth 2.1 (the consolidated draft): authorization-code grant with mandatory PKCE, no implicit flow.
- RFC 9728, OAuth 2.0 Protected Resource Metadata: how a resource server (your
/mcp) tells a client which authorization server protects it. - RFC 8414, Authorization Server Metadata: the machine-readable endpoint map.
- RFC 7591, Dynamic Client Registration: how a client registers itself with no out-of-band client-ID exchange.
The model never sees your database. It calls the MCP tools you exposed, and the token it carries is what authorizes those calls. OAuth is the front door; the bearer token is the key it hands back.
What endpoints does an OAuth-protected MCP server need?
Six endpoints, in two discovery documents plus four flow handlers:
GET /.well-known/oauth-protected-resource # RFC 9728: who protects /mcp
GET /.well-known/oauth-authorization-server # RFC 8414: endpoint metadata
POST /register # RFC 7591: dynamic client registration
GET /authorize # consent screen (needs a logged-in session)
POST /authorize # consent submit -> authorization code
POST /token # code + PKCE verifier -> access token
We will build them in that order, because that is the order a client hits them: discover, register, authorize, exchange.
Everything below runs on Cloudflare Workers with Hono for routing and KV for short-lived state. The same shapes work on any runtime; substitute your own router and a Redis or table-backed store for KV.
How do I publish OAuth discovery metadata for MCP?
Serve two JSON documents at well-known URLs. The first (RFC 9728) lives on the resource server and points clients at the authorization server. The second (RFC 8414) is the authorization server's endpoint map.
When the Claude app gets a 401 from your /mcp endpoint, it reads the WWW-Authenticate header, fetches the protected-resource metadata, follows authorization_servers to the auth-server metadata, and learns where to register and authorize. Here is both documents from one Worker:
import { Hono } from "hono";
const app = new Hono();
const origin = (c: { req: { url: string } }) => new URL(c.req.url).origin;
// RFC 9728: tells the client which auth server protects /mcp
app.get("/.well-known/oauth-protected-resource", (c) =>
c.json({
resource: `${origin(c)}/mcp`,
authorization_servers: [origin(c)],
scopes_supported: ["mcp:read", "mcp:send"],
bearer_methods_supported: ["header"],
}),
);
// RFC 8414: the auth server's endpoint map
app.get("/.well-known/oauth-authorization-server", (c) =>
c.json({
issuer: origin(c),
authorization_endpoint: `${origin(c)}/authorize`,
token_endpoint: `${origin(c)}/token`,
registration_endpoint: `${origin(c)}/register`,
scopes_supported: ["mcp:read", "mcp:send"],
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
}),
);
Two fields here are load-bearing. code_challenge_methods_supported: ["S256"] is how you advertise that PKCE is required and only the SHA-256 challenge method is accepted. token_endpoint_auth_methods_supported: ["none"] declares that your clients are public: they have no client secret, which is correct for the Claude app, so PKCE (not a secret) is what secures the exchange.
A common failure mode: clients fetch /.well-known/oauth-authorization-server from the origin root, not under a path prefix. If your Worker is mounted behind a router that strips or rewrites paths, the well-known route can 404 and the connector silently fails with "could not discover authorization server." Serve both documents from the bare origin.
How do I implement Dynamic Client Registration for MCP?
Accept a POST /register with the client's name and redirect URIs, validate the redirect hosts, store the client, and return a generated client_id. DCR (RFC 7591) exists because you cannot pre-register every assistant that might connect; the client registers itself at runtime.
const ALLOWED_REDIRECT_HOSTS = new Set([
"claude.ai",
"claude.com",
"localhost",
"127.0.0.1",
]);
function isAllowedRedirect(uri: string): boolean {
try {
const u = new URL(uri);
const secure = u.protocol === "https:" || u.hostname === "localhost" || u.hostname === "127.0.0.1";
return secure && ALLOWED_REDIRECT_HOSTS.has(u.hostname);
} catch {
return false;
}
}
function randomId(bytes = 18): string {
const buf = new Uint8Array(bytes);
crypto.getRandomValues(buf);
let bin = "";
for (const b of buf) bin += String.fromCharCode(b);
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
app.post("/register", async (c) => {
const body = await c.req.json().catch(() => null) as
| { client_name?: string; redirect_uris?: string[] }
| null;
const redirectUris = body?.redirect_uris ?? [];
if (!Array.isArray(redirectUris) || redirectUris.length === 0) {
return c.json({ error: "invalid_redirect_uri", error_description: "redirect_uris required" }, 400);
}
if (!redirectUris.every(isAllowedRedirect)) {
return c.json({ error: "invalid_redirect_uri", error_description: "redirect_uri host not allowed" }, 400);
}
const client = {
client_id: `mcpc_${randomId()}`,
client_name: body?.client_name ?? "MCP Client",
redirect_uris: redirectUris,
};
// Store in KV with a generous TTL (re-registration is cheap).
await c.env.KV.put(`oauth:client:${client.client_id}`, JSON.stringify(client), {
expirationTtl: 60 * 60 * 24 * 365,
});
return c.json(
{
client_id: client.client_id,
client_name: client.client_name,
redirect_uris: client.redirect_uris,
token_endpoint_auth_method: "none",
grant_types: ["authorization_code", "refresh_token"],
},
201,
);
});
The redirect-host allowlist is the most important security control in DCR. Without it, anyone can register a client that redirects authorization codes to a server they control. Pin the allowlist to the hosts you actually expect (claude.ai, claude.com, plus localhost for testing) and reject everything else with invalid_redirect_uri. Open registration with an unrestricted redirect is an open redirect with extra steps.
How do I build the authorize endpoint with PKCE?
Split it in two. GET /authorize validates the request and renders a consent screen for a signed-in user; POST /authorize records the user's decision and issues a single-use authorization code bound to a PKCE challenge. PKCE is mandatory: reject any request without an S256 code_challenge.
Here is the GET handler. It validates the registered client and its redirect URI before trusting the redirect, requires PKCE, and bounces an unauthenticated user through your own sign-in:
type Scope = "mcp:read" | "mcp:send";
// getSessionUser is your existing auth: resolve the logged-in user, or null.
app.get("/authorize", async (c) => {
const q = c.req.query();
const clientId = q.client_id ?? "";
const redirectUri = q.redirect_uri ?? "";
const state = q.state ?? "";
const codeChallenge = q.code_challenge ?? "";
const method = q.code_challenge_method ?? "";
const scope: Scope = q.scope?.includes("mcp:send") ? "mcp:send" : "mcp:read";
const raw = await c.env.KV.get(`oauth:client:${clientId}`);
if (!raw) return c.text("Unknown client_id. Re-register the connector.", 400);
const client = JSON.parse(raw) as { redirect_uris: string[]; client_name: string };
if (!client.redirect_uris.includes(redirectUri) || !isAllowedRedirect(redirectUri)) {
return c.text("redirect_uri mismatch.", 400);
}
// OAuth 2.1: PKCE is required, and we only accept S256.
if (!codeChallenge || method !== "S256") {
const u = new URL(redirectUri);
u.searchParams.set("error", "invalid_request");
u.searchParams.set("error_description", "PKCE S256 required");
if (state) u.searchParams.set("state", state);
return c.redirect(u.toString(), 302);
}
const user = await getSessionUser(c);
if (!user) {
// Not signed in: send through your app's sign-in, then return here.
const back = new URL(c.req.url);
const signin = new URL("/", origin(c));
signin.searchParams.set("next", back.pathname + back.search);
return c.redirect(signin.toString(), 302);
}
return c.html(renderConsent({ client, user, clientId, redirectUri, state, codeChallenge, scope }));
});
Two rules to internalize. First, validate redirect_uri against the registered values before you ever redirect to it, including the error redirects; an attacker-supplied redirect that you echo back is a hole. Second, reuse your existing session for the consent: the OAuth layer does not need its own identity system. The user is already logged into your app, so consent is just an "Allow" button.
The POST handler re-validates the client and redirect, then mints the code. The code is a random opaque string stored in KV with a short TTL, bound to the user, client, redirect, PKCE challenge, and scope:
app.post("/authorize", async (c) => {
const form = await c.req.formData();
const clientId = String(form.get("client_id") ?? "");
const redirectUri = String(form.get("redirect_uri") ?? "");
const state = String(form.get("state") ?? "");
const codeChallenge = String(form.get("code_challenge") ?? "");
const decision = String(form.get("decision") ?? "");
const scope: Scope = form.get("scope") === "mcp:send" ? "mcp:send" : "mcp:read";
const raw = await c.env.KV.get(`oauth:client:${clientId}`);
if (!raw) return c.text("Unknown client_id.", 400);
const client = JSON.parse(raw) as { redirect_uris: string[] };
if (!client.redirect_uris.includes(redirectUri) || !isAllowedRedirect(redirectUri)) {
return c.text("redirect_uri mismatch.", 400);
}
const back = new URL(redirectUri);
if (decision !== "allow") {
back.searchParams.set("error", "access_denied");
if (state) back.searchParams.set("state", state);
return c.redirect(back.toString(), 302);
}
const user = await getSessionUser(c);
if (!user) return c.text("Session expired, sign in again.", 401);
const code = `mcpa_${randomId(24)}`;
await c.env.KV.put(
`oauth:code:${code}`,
JSON.stringify({ userId: user.id, clientId, redirectUri, codeChallenge, scope }),
{ expirationTtl: 300 }, // 5 minutes is plenty to round-trip the exchange
);
back.searchParams.set("code", code);
if (state) back.searchParams.set("state", state);
return c.redirect(back.toString(), 302);
});
The state parameter is the client's CSRF token. You do not validate it (the client does), but you must echo it back unchanged on both the success and error redirects, or the client will reject the response.
How does PKCE actually verify at the token endpoint?
PKCE works by making the client commit to a secret up front and prove it at the end. The client generates a random code_verifier, sends code_challenge = base64url(SHA256(verifier)) with the authorization request, and sends the raw verifier with the token request. Your server recomputes the hash and compares. An attacker who intercepts the authorization code never saw the verifier, so the code is useless to them.
Here is the verification, which is just one digest and one comparison:
function b64url(bytes: Uint8Array): string {
let bin = "";
for (const b of bytes) bin += String.fromCharCode(b);
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
async function verifyPkce(verifier: string, challenge: string): Promise<boolean> {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
return b64url(new Uint8Array(digest)) === challenge;
}
Note the base64url encoding: no padding, + and / swapped for - and _. Getting this wrong is the single most common PKCE bug. If you use standard base64, the comparison fails every time and you get invalid_grant with no obvious cause.
How do I build the token endpoint?
The /token endpoint handles two grants. For authorization_code, look up the KV code, delete it immediately so it cannot be replayed, verify the redirect and PKCE, then mint an access token. For refresh_token, look up the stored refresh record and rotate it.
app.post("/token", async (c) => {
const form = await c.req.formData();
const grantType = String(form.get("grant_type") ?? "");
if (grantType === "authorization_code") {
const code = String(form.get("code") ?? "");
const verifier = String(form.get("code_verifier") ?? "");
const redirectUri = String(form.get("redirect_uri") ?? "");
const raw = await c.env.KV.get(`oauth:code:${code}`);
if (!raw) return tokenError(c, "invalid_grant", "Unknown or expired code");
// Single-use: burn the code before any other check can fail-and-retry.
await c.env.KV.delete(`oauth:code:${code}`);
const rec = JSON.parse(raw) as {
userId: string; redirectUri: string; codeChallenge: string; scope: Scope;
};
if (rec.redirectUri !== redirectUri) {
return tokenError(c, "invalid_grant", "redirect_uri mismatch");
}
if (!verifier || !(await verifyPkce(verifier, rec.codeChallenge))) {
return tokenError(c, "invalid_grant", "PKCE verification failed");
}
const accessToken = await mintAccessToken(c.env, rec.userId, rec.scope);
const refreshToken = await issueRefresh(c.env, rec.userId, rec.scope);
return tokenResponse(c, accessToken, refreshToken, rec.scope);
}
if (grantType === "refresh_token") {
const refreshToken = String(form.get("refresh_token") ?? "");
const key = `oauth:refresh:${await sha256Hex(refreshToken)}`;
const raw = await c.env.KV.get(key);
if (!raw) return tokenError(c, "invalid_grant", "Unknown refresh token");
await c.env.KV.delete(key); // rotate: old refresh is now dead
const rec = JSON.parse(raw) as { userId: string; scope: Scope };
const accessToken = await mintAccessToken(c.env, rec.userId, rec.scope);
const newRefresh = await issueRefresh(c.env, rec.userId, rec.scope);
return tokenResponse(c, accessToken, newRefresh, rec.scope);
}
return tokenError(c, "unsupported_grant_type", `Unsupported grant_type "${grantType}"`);
});
function tokenResponse(c: any, accessToken: string, refreshToken: string, scope: Scope) {
return c.json(
{
access_token: accessToken,
token_type: "Bearer",
expires_in: 60 * 60 * 24 * 90,
refresh_token: refreshToken,
scope,
},
200,
{ "Cache-Control": "no-store" },
);
}
function tokenError(c: any, error: string, description: string) {
return c.json({ error, error_description: description }, 400, { "Cache-Control": "no-store" });
}
Two subtleties that matter in production. Burn the code first: delete the KV code before you run the redirect and PKCE checks, so a failed attempt cannot be retried with the same code. Rotate refresh tokens: each refresh exchange should invalidate the old refresh token and issue a new one (storing only its SHA-256 hash, never the raw value), so a leaked refresh token has a short blast radius. Store the hash, not the token, exactly as you would store a password.
mintAccessToken is deliberately left for you, and that is the whole trick of the next section.
Can OAuth just wrap the bearer token my MCP server already validates?
Yes, and for a self-hosted, single-tenant server it is the cleanest design. Your /mcp endpoint already validates some opaque bearer token on every request. So make mintAccessToken produce that same kind of token. OAuth becomes a thin issuing layer: the access_token you return is something your existing verifyToken already understands. No second token model, no separate identity provider, no multi-tenant consent machinery.
In Tinbox, this is exactly how it works. The server is single-tenant and self-hosted, so the app is the authorization server. The whole OAuth module is a front end over the capability tokens (tbx_…) the inbox already issues:
/tokenmints atbx_…through the samecreateApiKeypath that the manual "create token" button uses, then binds a grant per inbox the user can access./mcpvalidates thattbx_…through the sameverifyApiKeyit uses for static-bearer (Claude Code) clients.- The consent screen reuses the existing signed-in session. There is no new login.
The scope maps to capability: mcp:send mints a write-scoped token (the agent can send mail); anything else mints read-only (search, read, summarize, draft, but no send). That distinction lives behind the explicit checkbox on the consent screen, so granting "send" is always a deliberate click. You can revoke any connected agent later from Settings, because each issued token is a real, listable, revocable key.
The result is that one MCP server serves both auth styles without forking the token logic: Claude Code passes a static tbx_… bearer, the Claude app walks the OAuth flow and gets back the same kind of tbx_…, and /mcp cannot tell the difference. That is the payoff of treating OAuth as an issuer rather than an identity system.
Don't forget the 401 that starts the flow
The whole flow only triggers if your /mcp endpoint tells unauthenticated clients where to begin. Return a 401 with a WWW-Authenticate header pointing at your protected-resource metadata:
app.all("/mcp", async (c) => {
const auth = c.req.header("authorization") ?? "";
const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
if (!token || !(await verifyToken(c.env, token))) {
return c.json({ error: "unauthorized" }, 401, {
"WWW-Authenticate":
`Bearer resource_metadata="${origin(c)}/.well-known/oauth-protected-resource"`,
});
}
// ...handle the JSON-RPC MCP request...
});
Without that header, the Claude app gets a bare 401 and gives up, because it has no pointer to your discovery documents. With it, the app fetches the metadata, registers, and walks the flow you just built.
The shorter path
If you would rather not hand-roll and maintain six OAuth endpoints, KV state machines, and PKCE base64url edge cases, this entire flow ships inside Tinbox. Running npx tinbox init <domain> deploys an MCP server on your own Cloudflare account with the OAuth 2.1 + PKCE + DCR endpoints already wired to your inbox's tokens, plus the static-bearer path for Claude Code. You point the Claude app at https://mail.<domain>/mcp, click Connect, approve the scopes, and you are done. The code is the same module sketched above, hardened and tested, running in your account rather than a vendor's.
For the connect-from-the-other-side walkthrough, see connect Claude to your inbox over MCP. If you want the static-token route for headless clients, that is covered in connecting Claude to your email in five minutes. For the broader edge-MCP picture, see building an MCP server on Cloudflare Workers, and for the design question behind exposing data to agents at all, MCP vs a REST API for agent access. Before you ship one, skim the things to know before you run an email MCP server and the reasons MCP beats a REST API for email agents.
Deploy this yourself: npx tinbox init <domain>, then read the MCP and tokens docs for the OAuth and bearer configuration. Your assistants connect to an inbox that lives entirely on your own Cloudflare account, with no per-email pricing and no third-party hop.
Frequently asked questions
Why does an MCP server need OAuth instead of a static bearer token?
Headless clients like Claude Code can send a static Authorization: Bearer header, but the Claude desktop and web app's custom-connector UI has no header field. It only speaks OAuth 2.1 with discovery and PKCE. To let an app user click Connect, sign in, and approve, your MCP server has to be an OAuth authorization server.
What endpoints does an OAuth-protected MCP server need?
Six: GET /.well-known/oauth-protected-resource (RFC 9728), GET /.well-known/oauth-authorization-server (RFC 8414), POST /register for Dynamic Client Registration (RFC 7591), GET and POST /authorize for the consent screen and code issuance, and POST /token to exchange the code for an access token.
Is PKCE required for MCP OAuth?
Yes. OAuth 2.1 makes PKCE mandatory for the authorization-code grant, and the MCP authorization spec follows it. Public clients like the Claude app have no client secret, so PKCE is what binds the authorization request to the token exchange. Advertise S256 in your metadata and reject any /authorize request without a code_challenge.
What is Dynamic Client Registration and why does MCP use it?
DCR (RFC 7591) lets a client register itself at runtime by POSTing its name and redirect URIs to your /register endpoint, which returns a client_id. MCP uses it because you cannot pre-register every assistant that might connect. The client discovers your registration endpoint from metadata and onboards with no manual client-ID exchange.
Can OAuth just wrap the bearer tokens my server already validates?
Yes, and for a self-hosted single-tenant server that is the simplest design. The /token endpoint mints the same kind of opaque bearer token your /mcp endpoint already verifies, so the access_token you return is a token your server understands natively. OAuth becomes a thin issuing layer, not a separate identity system.