How to Add OAuth to an MCP Server (So Claude Can Connect by URL)
Short answer: to let Claude, ChatGPT or Cursor connect to your MCP server by URL, the server has to do five things. Answer unauthenticated requests with a 401 that points to its metadata. Publish two small metadata documents. Let clients register themselves. Run the authorization code flow with PKCE. Issue tokens bound to your MCP endpoint. Miss any one of them and the client never shows a sign-in button. It just says it couldn't connect.
I recently built a read-only MCP server that gives Claude access to a team's Google Chat, deployed on Vercel. Everything below comes from that build, including the parts that took the longest to get right.
Why OAuth, and Not an API Key?
A local MCP server runs on your laptop and can read a key from an environment variable. A remote MCP server is different: many people connect to it from their own Claude account.
Shared API keys are the wrong tool for that:
- Everyone gets the same access. There's no "this user can only see their own data".
- The key ends up pasted into chats and config files.
- Revoking one person means rotating the key for everyone.
With OAuth, each user signs in through the browser, approves what the connector can do, and the server acts as that user. In my case the user signs in with Google, and the server reads only the chats that person can already see.
The Flow in One Picture
| Step | Who | What happens |
|---|---|---|
| 1 | Claude → MCP server | Calls /mcp with no token |
| 2 | MCP server | Replies 401 with a WWW-Authenticate header pointing to its metadata |
| 3 | Claude | Reads the protected resource metadata, finds the authorization server |
| 4 | Claude | Reads the authorization server metadata, finds the endpoints |
| 5 | Claude → /oauth/register | Registers itself (dynamic client registration) |
| 6 | Browser → /oauth/authorize | User signs in and approves, with PKCE |
| 7 | Claude → /oauth/token | Swaps the code for an access token and refresh token |
| 8 | Claude → /mcp | Calls tools with Authorization: Bearer … |
The MCP authorization spec builds on standard OAuth RFCs. You don't need to read all of them, but you do need each piece.
Step 1: The 401 Challenge
This is the step most broken servers get wrong. If /mcp returns a plain 401 (or worse, a 500), the client has nowhere to go.
function challenge(presentedToken: boolean) {
const parts = [
`resource_metadata="${issuer}/.well-known/oauth-protected-resource"`,
`scope="chat.read"`,
];
if (presentedToken) parts.unshift(`error="invalid_token"`);
return new Response(JSON.stringify({ error: "unauthorized" }), {
status: 401,
headers: { "WWW-Authenticate": `Bearer ${parts.join(", ")}` },
});
}
Two details matter:
resource_metadatatells the client where to start.error="invalid_token"only when a token was sent but is bad or expired. That's the signal for the client to refresh instead of starting over.
Step 2: Two Metadata Documents
Protected resource metadata (RFC 9728) at /.well-known/oauth-protected-resource says "this is the resource, and this is who issues tokens for it":
{
"resource": "https://your-server.example.com/mcp",
"authorization_servers": ["https://your-server.example.com"],
"scopes_supported": ["chat.read"],
"bearer_methods_supported": ["header"]
}
Authorization server metadata (RFC 8414) at /.well-known/oauth-authorization-server lists the endpoints and what they support: response_types_supported: ["code"], code_challenge_methods_supported: ["S256"], token_endpoint_auth_methods_supported: ["none"], and the registration_endpoint.
The mistake that cost me time: the issuer and resource URLs must match byte for byte everywhere. A trailing slash in one place, or deriving the URL from the request's Host header on a platform with several domains, and the client quietly rejects the metadata. Set the public URL once, from an environment variable, and build every URL from it.
Step 3: Dynamic Client Registration
Users connect by pasting a URL. Nobody is going to create a client ID for them by hand, so the client registers itself at /oauth/register (RFC 7591) and sends its name and redirect URIs.
Validate those redirect URIs strictly. That's where attacks come in:
- Allow
httpsURLs, plushttponly on loopback (localhost,127.0.0.1) for desktop apps. - Reject
javascript:,data:,file:and anything with a#fragment. - On later requests, require an exact match. The one exception: loopback redirects may change port (RFC 8252 §7.3), because desktop clients pick a free port each time.
Step 4: Authorize, With PKCE
At /oauth/authorize, check everything before showing any sign-in page:
- The
client_idis one you issued, and theredirect_urimatches what it registered. response_typeiscode.- There is a
code_challengeand the method isS256. Refuseplain. MCP clients are public clients with no secret, so PKCE (RFC 7636) is what stops a stolen code from being used. - Any
resourceparameter (RFC 8707) matches your MCP endpoint.
Then send the user to sign in. In my server that's Google: I pass the pending request through Google's
state parameter, check the returned email against an allow-list and confirm the user actually granted the read-only scopes, then redirect back to the client with a short-lived code. Always include the iss parameter on that redirect (RFC 9207); it protects against mix-up attacks.Step 5: The Token Endpoint
/oauth/token handles two grant types:
authorization_code: check the code belongs to this client, the redirect URI matches, andSHA-256(code_verifier)equals the stored challenge (compare in constant time). Then issue tokens.refresh_token: check the refresh token belongs to the same client, then issue a fresh pair.
Short-lived access tokens (I use one hour) and longer refresh tokens keep the blast radius small if a token leaks.
Doing It Without a Database
Most guides assume a database for clients, codes and tokens. On a serverless platform that's one more thing to run and secure, so I didn't use one.
Every client ID, pending request, code and token is a small JSON payload sealed with AES-256-GCM using a server secret. Only the server can create or read one, tampering breaks the authentication tag, and each payload carries its own expiry and a "kind" so an access token can never be used as a refresh token.
The trade-off is honest: you can't revoke one token early. Revoking the user's Google grant cuts off everything at once, and access tokens expire within an hour anyway. For a read-only connector that was the right call. For anything that writes data, I'd add a small revocation list.
Mistakes That Stop the Sign-In Button From Appearing
| Symptom | Usual cause |
|---|---|
| "Couldn't connect", no sign-in | /mcp returns 401 without WWW-Authenticate, or returns 500 |
| Metadata fetched, then nothing | Issuer or resource URL differs by a slash or a domain |
| Registration fails | Redirect URI validation too strict for loopback ports |
| Sign-in works, token exchange fails | PKCE check wrong, or redirect_uri compared loosely in one place and strictly in another |
| Works once, fails an hour later | No error="invalid_token" on expired tokens, so the client never refreshes |
| Browser clients fail | Missing CORS headers on the metadata and token endpoints |
The Checklist
- [ ]
/mcpanswers unauthenticated calls with401+WWW-Authenticate: Bearer resource_metadata="…" - [ ]
/.well-known/oauth-protected-resourceand/.well-known/oauth-authorization-serverpublished - [ ] One public URL from config; issuer and resource identical everywhere
- [ ] Dynamic client registration with strict redirect validation
- [ ] PKCE
S256required;plainrefused - [ ]
resourceparameter checked;issreturned on the redirect - [ ] Short-lived access tokens, refresh flow working
- [ ] Read-only tools by default; scopes checked on every call
Related
- MCP Server vs API (and A2A): What's the Difference?
- Case study: a secure MCP platform that lets Claude create company documents
Need an MCP server your team can connect to safely? This is how I build them, or book a 15-minute call.
Frequently asked questions
Does an MCP server need OAuth?
A local MCP server that runs on your own machine does not. A remote MCP server that people connect to by URL from Claude, ChatGPT or Cursor should use OAuth, so each user signs in with their own account instead of sharing an API key.
What does an MCP client need to see before it shows a sign-in button?
A 401 response from the MCP endpoint with a WWW-Authenticate header that points to the server's protected resource metadata. From there the client finds the authorization server, registers itself, and opens the sign-in page.
What is dynamic client registration in MCP?
Dynamic client registration (RFC 7591) lets an MCP client register itself with your authorization server automatically, so users can connect by pasting a URL without anyone creating a client ID by hand.
Is PKCE required for MCP OAuth?
Yes. MCP clients are public clients with no secret, so PKCE with the S256 method is what stops a stolen authorization code from being exchanged for a token.
Can an MCP server do OAuth without a database?
Yes. Client registrations, authorization codes and tokens can be encrypted and signed payloads that only the server can read, so there is nothing to store. The trade-off is that individual tokens cannot be revoked before they expire.
Want to work together?
I help businesses build AI automation solutions that deliver real results.
Get in Touch