MCP authentication: OAuth vs API keys, explained
Building an MCP server that works is pretty easy these days. Shipping one that is secure and works within your organization's governance can be more work than you expect. Part of the problem is that most writing on MCP authentication blurs three different questions:
Authentication is who or what is calling. An API key and an OAuth token both answer it, with very different strength: a shared key proves only that the caller has the secret, a token says which person or service it was issued to.
Authorization is what that caller may do. Scopes, roles and claims live here, and MCP deliberately leaves it to the server.
Governance is whether you can see every server, control who reaches which tool and prove what happened later. Identity, authorization, audit, lifecycle and discovery all sit here. None of these surfaces is new for an engineering org; they just hadn't been pointed at MCP yet.
That blur is why the "OAuth vs API keys" debate never settles. A shared API key answers the first question weakly and the other two not at all. OAuth answers the first well and gives you the raw material for the second, but governance is still yours to build.
This post separates those questions, shows what the MCP spec actually requires, and walks through one FastMCP server secured in three stages, from a shared key to OAuth to per-tool roles with an audit log. All the code is in the companion example, and every terminal screenshot below comes from running it.
What the MCP spec actually says
The MCP authorization spec defines OAuth 2.1 for HTTP transports and says nothing about API keys. The parts that matter for this post are short.
- Authorization is optional. A local STDIO server should take credentials from its environment, not run an OAuth flow.
- The MCP server is a resource server. It validates tokens; it doesn't issue them. An identity provider such as Keycloak, Okta or Entra ID does that.
- Discovery is standard. The server publishes Protected Resource Metadata (RFC 9728), so a client that gets a 401 can find the authorization server on its own.
- Tokens are bound to one server. Clients send a
resourceparameter (RFC 8707), and servers must reject tokens issued for anyone else. This is what stops a token minted for one server from being replayed against another. - Client registration changed. Client ID Metadata Documents are now the preferred way for a client to identify itself, Dynamic Client Registration is kept for backwards compatibility, and pre-registration is still allowed. More on why that matters below.
In FastMCP 4.2 and later, those roles map onto a few classes. JWTVerifier checks tokens you issue yourself. RemoteAuthProvider, and providers built on it such as KeycloakAuthProvider, point clients at an identity provider that handles registration itself. OAuthProxy and OIDCProxy sit in front of providers that can't, such as GitHub and Google.
One server, three stages
The companion example is a FastMCP server over a synthetic analytics warehouse with eight tools: list_metrics, get_metric, top_events, get_revenue, lookup_account, export_user_events, delete_user and whoami. The last one reports who the server thinks is calling, which turns out to be the most useful tool in a security demo. If you can't ask the server who it thinks you are, you can't debug any of the rest.
tools.py is identical in every stage. The security work lives in auth.py, server.py and the audit middleware. Stage 3 also changes db.py, a small fix for the optional hosted database mode described later. Each stage is its own folder, so diff -ru stage-1-api-key/src stage-3-authz/src shows all of it.
Three panels comparing what the server knows in stage 1 (one shared key), stage 2 (OAuth with Keycloak) and stage 3 (roles, scope and an audit log)
Who gets which tools in stage 3: Alice (analyst), Fran (finance), Adam (admin and eu-data) and nightly-report-bot (analyst, client credentials) map through their Keycloak realm roles to tool groups; every signed-in caller gets list_metrics and whoami
Stage 1: API keys, when they're fine and when they aren't
API keys deserve a fair shake, because they're everywhere for good reasons. One header, no browser flow, works from any client or script, nothing to host. For an internal server with a handful of known callers, low-risk tools and one trust boundary, a key is often enough.
FastMCP's StaticTokenVerifier maps one key to one identity:
import os
from fastmcp.server.auth.providers.jwt import StaticTokenVerifier
def build_auth() -> StaticTokenVerifier:
key = os.environ["ANALYTICS_API_KEY"]
return StaticTokenVerifier(tokens={key: {"client_id": "shared-api-key", "scopes": []}})StaticTokenVerifier is for development only, but the shape of the problem doesn't change if you mint a JWT for a shared key instead. Here's what the server can tell you when Alice and Bob both use it.
Stage 1 terminal output: a 401 without a key, identical whoami answers for Alice and Bob, all eight tools visible including delete_user, and three log lines that all say client_id shared-api-key
Without a key the server returns a 401 with a Bearer challenge, so it isn't open. With the key, Alice and Bob are the same caller, both see all eight tools, and the delete goes through. The log shows three calls from shared-api-key. Nothing records who deleted user 42, and the only way to cut off one person is to rotate the key for everyone.
That gives a simple test. If you ever need to answer "which person did this" or "revoke one caller", a shared key can't do it.
Stage 2: OAuth, and where it hurts for agents
Stage 2 puts Keycloak in front of the server. The server holds no secrets any more; it trusts tokens Keycloak signs, and it rejects any token not issued for it:
from fastmcp.server.auth.providers.keycloak import KeycloakAuthProvider
def build_auth() -> KeycloakAuthProvider:
return KeycloakAuthProvider(
realm_url="http://localhost:8080/realms/analytics-demo",
base_url=SERVER_URL,
audience=SERVER_URL, # reject tokens issued for other servers
required_scopes=["openid", "analytics:read"],
)
Stage 2 terminal output: alice and adam each get their own subject ID, the nightly-report-bot gets a service identity, alice still sees 8 of 8 tools and deletes a user, and the log names every caller
Now every caller is somebody. Alice and Adam carry their own subject IDs and usernames, issued by Keycloak. The nightly report job uses the client credentials flow and gets a named service identity of its own, so a scheduled job no longer borrows a person's key. The log now names every caller.
And Alice can still delete a user. She sees all eight tools, because nothing on the server uses what the token says about her. Authenticated is not the same as authorized.
OAuth gives you real things here: tokens tied to a user and an audience, short lifetimes, scopes that can be challenged and stepped up at runtime, and revocation at the identity provider. Its usual sign-in flow assumes a person at a browser, and agents strain that assumption in two ways. A scheduled job has no person behind it, so it needs a flow without a browser and an identity of its own, which is what the client credentials flow gave the nightly report job. And an agent working on someone's behalf is neither that person nor a plain service, a harder problem we'll come back to.
OAuth costs more to run than a key. It's also far better at saying who did what, and it gives the server the raw material, in the token's claims, to decide what each caller may do. Stage 3 uses that material.
Client registration: who is the app?
OAuth identifies two things: the person, and the app acting for them. An identity provider only issues tokens to apps it knows. An MCP client and server have usually never met, so the app has to introduce itself. The spec allows three ways.
| Method | How the app introduces itself | Where the demo uses it | Trade-off |
|---|---|---|---|
| Client ID Metadata Documents (CIMD) | The client ID is an HTTPS URL; the identity provider fetches the document at that URL at sign-in | Claude Code, via the example's .mcp.json | Identity tied to a domain, one record per URL; needs a public URL, and provider support is new |
| Dynamic Client Registration (DCR) | The client posts its details and gets a new random client ID | The scripted logins in stages 2 and 3 | No setup, but the provider can't check the name the client claims, and every sign-in adds a client record |
| Pre-registration | An admin creates the client and hands out an ID and secret | nightly-report-bot (client credentials) | Right for a known service; doesn't scale to every AI client |
The current spec recommends CIMD. The diagram below shows what happens when Claude Code connects to the stage 3 server.
Sequence diagram: Claude Code gets a 401, reads the server's protected resource metadata and Keycloak's metadata, authorizes with its claude.ai URL as the client ID, Keycloak fetches the metadata document and checks the domain policy, the user signs in and consents, and Claude Code calls the tool with a token bound to the server
Admins can allow or block apps by domain: the demo realm accepts client IDs on claude.ai and rejects others. Users get a consent screen naming an app they can verify, instead of whatever name a client typed into a registration request. And the app has a stable identity you can put in logs. In the demo, whoami returns a random UUID like c6701373-… for a DCR client and https://claude.ai/oauth/claude-code-client-metadata for Claude Code.
Connecting Claude Code needs nothing more than this in the server's folder:
{
"mcpServers": {
"analytics": { "type": "http", "url": "http://localhost:8000/mcp" }
}
}On the Keycloak side, CIMD is an experimental feature. It needs Keycloak 26.7 or later, started with --features=cimd, plus a client policy that says which domains to trust:
"clientPolicies": {"policies": [{
"name": "mcp-cimd",
"enabled": true,
"conditions": [{"condition": "client-id-uri",
"configuration": {"client-id-uri-scheme": ["https"],
"client-id-uri-allow-permitted-domains": ["claude.ai"]}}],
"profiles": ["mcp-cimd"]
}]}On Keycloak 26.6, Claude Code silently falls back to DCR (keycloak/keycloak#49730). The stage 3 README covers one more Keycloak gotcha: CIMD clients get no realm roles unless a scope maps them.
FastMCP needs nothing special for any of this. RemoteAuthProvider passes the identity provider's metadata through as is, so if Keycloak advertises CIMD, clients use it. For providers that don't support CIMD, OAuthProxy and OIDCProxy accept CIMD clients themselves, on by default. On the client side it's OAuth(client_metadata_url=...). See FastMCP's Keycloak, remote OAuth, OAuth proxy CIMD and client-side CIMD docs.
Lead with CIMD where you can, and keep DCR as the fallback for setups that can't turn the feature on. DCR isn't wrong; the demo's own scripts use it, because a local script has no public URL to publish a metadata document at.
Stage 3: authorization, audit and a second layer
Stage 3 puts the token's claims to work. Each tool gets a rule saying which Keycloak roles may call it, which is what finally stops Alice's delete from stage 2:
def has_role(*roles: str) -> AuthCheck:
"""Caller holds at least ONE of these roles. (require_roles alone means ALL of them.)"""
checks = [require_roles(r, extract=keycloak_roles) for r in roles]
return lambda ctx: any(c(ctx) for c in checks)
TOOL_AUTH = {
"list_metrics": None,
"whoami": None,
"get_metric": has_role("analyst", "finance", "admin"),
"top_events": has_role("analyst", "finance", "admin"),
"get_revenue": has_role("finance", "admin"),
"lookup_account": has_role("admin"),
"export_user_events": has_role("admin"),
"delete_user": has_role("admin"),
}Roles are a Keycloak concept, not part of OAuth, which is why require_roles gets an extractor that reads Keycloak's realm_access.roles claim. The server wires the table in, along with a server-wide scope check and the audit middleware:
mcp = FastMCP("analytics", auth=build_auth(),
middleware=[AuditMiddleware(), server_wide, EURegionGuard()])
for fn in TOOLS:
mcp.tool(fn, auth=TOOL_AUTH[fn.__name__])The result is that each caller sees a different server: Alice gets four tools, Fran five and Adam all eight. A tool a caller may not use is absent from tools/list, so the assistant never learns it exists. Calling it by name anyway fails with "not found or not authorized", which doesn't confirm the tool is there. No hand-written 403s.
Stage 3 tools table: alice sees four tools, fran five including get_revenue, and adam all eight
Every tool call in stage 3 passes five checks: token check, audit, server scope, an argument check for EU data, and per-tool roles, then reaches the database through a read-only or read/write connection
Every tool call passes five checks on its way to the data. Two are worth a closer look. A role table can't express a rule that depends on a call's arguments, such as "EU data needs the eu-data role", so that one is a small middleware:
class EURegionGuard(Middleware):
async def on_call_tool(self, context, call_next):
args = context.message.arguments or {}
if context.message.name == "get_metric" and args.get("region") == "EU":
roles = get_access_token().claims.get("realm_access", {}).get("roles", [])
if "eu-data" not in roles:
raise AuthorizationError("EU data requires the eu-data role")
return await call_next(context)The audit middleware runs after the token check and before the authorization checks, so it records every authorization denial. A request with no valid token gets a 401 before it reaches the audit log. Each line says who called, with which roles, which tool, the arguments, and whether it was allowed:
{
"timestamp": "2026-11-23T20:16:30+00:00",
"username": "alice",
"roles": ["offline_access", "analyst"],
"tool": "get_revenue",
"arguments": { "start_month": "2025-01-01", "end_month": "2025-06-30" },
"outcome": "denied",
"reason": "AuthorizationError: Authorization failed for tool 'get_revenue': not found or not authorized"
}The last layer isn't in FastMCP at all. The example stores its data in DuckDB, an embedded analytics database. The read tools open a read-only connection, and only delete_user gets a read/write one. If a rule is wrong and a read tool tries to write, the database refuses. In the example's optional MotherDuck mode, which runs the same database as a hosted service, the split uses a read scaling token for reads and a short-lived read/write token for delete_user.
Stage 3 terminal output: alice's direct call to get_revenue is denied, adam deletes a user, the report bot reads three rows, the audit summary lists the denial, and a write on the read-only connection fails
FastMCP decides who may call a tool. The database connection limits what the tool can do, even when a rule is wrong. Defense in depth sounds abstract until you watch the second layer catch something.
The middle path: service identities and held credentials
Production setups often end up with both keys and OAuth, so it's worth describing the hybrid instead of forcing a pick. People sign in with OAuth through the company identity provider and SSO. Automation uses service accounts and client-credentials tokens, scoped and short-lived, so a log line still names a non-human identity, as the nightly report job does in the demo. Upstream API keys stay out of laptops: callers authenticate once to a gateway, and the gateway holds and injects the upstream credentials.
One gap is still open: an agent acting for a person and an agent acting as itself are different identities, and today's options each cover half of it. Delegated scopes keep the person's identity, so the log names Alice, but the agent is tied to her session and can do anything her scopes allow. A service account gives the agent its own identity and narrow scopes, but the log no longer says whose request it was. What you want is a token that carries both, with the person as the subject and the agent as the actor. OAuth token exchange (RFC 8693) defines an act claim for exactly that, but few identity providers or MCP clients issue those tokens today.
Governance: what OAuth alone doesn't give you
Go back to the five governance surfaces and mark which ones the demo covered. Identity is covered by OAuth, and only weakly by keys. Authorization is partly covered: FastMCP gives you require_scopes, require_roles, AuthMiddleware and tool visibility, and stage 3 shows how far that goes on one server. Audit took a middleware we wrote ourselves. Lifecycle (how a server is approved, promoted, rolled back and retired) and discovery (a registry of what exists, who owns it and what is approved) aren't covered at all, and they can't be from inside a single server.
That's the line between a framework and a control plane. One server can enforce its own rules. Run forty servers across ten teams and you're copying the same role table, audit middleware and token checks into each of them, while nobody can see the whole picture. Those teams need one place for tool-level access with separate discover, use and manage permissions, per-call audit, and a registry, tied to the identity provider the company already runs. A system prompt that tells an agent not to call delete_user is guidance. A rule in front of the tool is enforcement.
Which to use
| Scenario | Use | Why | Add for governance |
|---|---|---|---|
| Local STDIO server, one user | Credentials from the environment | The spec skips OAuth for STDIO | Nothing beyond the machine boundary |
| Internal remote server, few known callers, low risk | API key or bearer token | Simple and sufficient | Per-caller keys, rotation, logging |
| Remote server used by many people through AI clients | OAuth 2.1 with SSO, CIMD for client registration | Per-user identity, consent, revocation | Scopes, role checks, an audit trail |
| Automation or scheduled agents | Service account with client-credentials tokens | A non-human identity in the logs | Narrow scopes, short lifetimes, a tool allowlist |
| Server in front of a provider without CIMD or DCR | OAuthProxy or OIDCProxy | Clients register with the proxy | The same scope and audit controls |
| Many servers across teams | OAuth through a gateway | One identity and policy layer | Registry, tool-level access control, central audit |
You can watch all of this happen on your own laptop. Clone PrefectHQ/examples, go to fastmcp/servers/mcp-auth-analytics, and run the stages in order, one folder each: make stage1 in stage-1-api-key/ shows what a shared key can't tell you, make up and then make stage2 in stage-2-oauth/ gives every caller a name, and make stage3 in stage-3-authz/ gives Alice, Fran and Adam three different servers. Then run make serve in stage-3-authz/, open Claude Code in that folder and sign in as Fran. whoami comes back with Claude Code's claude.ai client ID and her five tools, and her EU query is refused. The diff from stage 2 to stage 3 is about a hundred lines, and it's the difference between knowing who called and controlling what they could do.
Those hundred lines protect one server. When you have forty, FastMCP Gateway moves identity, tool-level access and audit to one place in front of all of them.