All guides
Updated
Reading
14 min
By
Anlyon Team

How MCP server authentication works: OAuth 2.1, client registration and API keys

How a remote MCP server signs a client in: OAuth 2.1, protected resource metadata, client registration and API-key headers, and what breaks in practice.

  • mcp
  • mcp servers
  • oauth
  • authentication
  • credentials
  • end users

Short answer: a remote MCP server authenticates a client with OAuth 2.1. The server answers the first request with 401 and a pointer to its metadata, the client finds the authorization server, gets a client ID, sends the user through a browser sign-in with PKCE, and then sends the access token as a Bearer header on every request.

That is the flow the MCP specification defines. In practice you will also meet servers that take an API key in a header, and local servers that read a key from their environment. This guide covers all three, what goes wrong with each, how a per-user credential differs from a developer's own key, and where Anlyon fits. Specification details are from the 2026-07-28 revision, read on 2026-11-13.

TL;DR

  • Authorization is optional in MCP. HTTP servers should use the OAuth 2.1 flow. Stdio servers should read credentials from the environment.
  • The server must publish OAuth protected resource metadata (RFC 9728). The client must use it to find the authorization server.
  • A client gets its ID in one of three ways: pre-registration, a Client ID Metadata Document, or Dynamic Client Registration, which is now deprecated.
  • The client must use PKCE and must name the server in a resource parameter. The server must accept only tokens issued for it.
  • The specification covers one user and one client. An agent that acts for many users needs per-user token storage, refresh and revocation on top.

How does authorization work for a remote MCP server?

The specification gives each party an OAuth role. The MCP server is the resource server. The MCP client is the OAuth client. A separate authorization server signs the user in and issues tokens. It can be part of the MCP server or another service.

The flow, step by step:

  1. The client calls the server with no token. The server answers 401 Unauthorized with a WWW-Authenticate header.

    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource",
                             scope="files:read"
    
  2. The client fetches the protected resource metadata. It uses the URL in the header. With no header, it tries the well-known URI for the server's path, such as /.well-known/oauth-protected-resource/mcp, then the one at the root. The document must list at least one entry in authorization_servers.

  3. The client fetches the authorization server's metadata. It tries the OAuth 2.0 metadata endpoint (/.well-known/oauth-authorization-server), then OpenID Connect discovery. This document names the authorization and token endpoints and says what the server supports.

  4. The client gets a client ID. See the next section.

  5. The client opens a browser for an authorization code flow with PKCE. The request carries a code_challenge and a resource parameter that names the MCP server, such as resource=https%3A%2F%2Fmcp.example.com.

  6. The user signs in and consents. The authorization server redirects back with a code.

  7. The client exchanges the code for an access token, and often a refresh token. It sends the code_verifier and the same resource parameter.

  8. The client calls the MCP server with the token in the Authorization header, on every request.

    POST /mcp HTTP/1.1
    Host: mcp.example.com
    Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
    

The rules that carry the security, each a MUST in the specification:

RuleWho it bindsWhy it exists
Implement protected resource metadata (RFC 9728)ServerThe client learns the authorization server from the server it is calling, not from a guess
Use PKCE, with S256, and refuse to proceed if the authorization server does not advertise itClientA stolen authorization code is useless without the verifier
Send the resource parameter (RFC 8707) on the authorization and token requestsClientThe token is issued for this one MCP server
Accept only tokens issued for this serverServerA token for another service cannot be replayed here
Never pass the client's token through to an upstream APIServerThe upstream call needs its own token, issued by the upstream's authorization server
Send the token in the Authorization header, never in the query stringClientQuery strings end up in logs and histories
Serve authorization endpoints over HTTPS, with redirect URIs on HTTPS or localhostAuthorization server and clientCodes and tokens are not sent in the clear

When a token lacks a scope a tool needs, the server answers 403 with error="insufficient_scope" and the scopes required. The client then runs the flow again for the wider set. The specification calls this step-up authorization.

What is OAuth 2.1, and why does MCP use it?

OAuth 2.1 is an IETF draft that folds OAuth 2.0 and a decade of security guidance into one document. The MCP specification cites draft 13. Compared with OAuth 2.0 as most people learned it:

  • PKCE is required for the authorization code flow, for every client.
  • The implicit grant and the password grant are gone.
  • Redirect URIs are compared by exact string match.
  • Bearer tokens are not sent in query strings.
  • Refresh tokens for public clients must be sender-constrained or rotated.

MCP clients are mostly public clients: a desktop app or a CLI that cannot keep a secret. OAuth 2.1 is written for that case. MCP adds the pieces a client needs to connect to a server it has never seen: metadata discovery, the resource parameter and a way to register without a human filling in a form.

How does an MCP client register with an authorization server?

A client that connects to arbitrary servers has no client ID for most of them. The specification lists three ways to get one and the order to try them in.

MethodHow it worksStatus in the 2026-07-28 revision
Pre-registrationThe client ships with a client ID for that authorization server, or the user registers an OAuth app and pastes its ID inClients SHOULD support static client credentials. Use it first when you have it
Client ID Metadata DocumentThe client ID is an HTTPS URL. The authorization server fetches a JSON document from that URL with the client's name and redirect URIsClients and authorization servers SHOULD support it. The server advertises client_id_metadata_document_supported
Dynamic Client Registration (RFC 7591)The client posts its metadata to a registration endpoint and receives a client IDMAY be supported. Deprecated, kept for authorization servers without metadata documents
Ask the userThe client prompts for client detailsThe fallback when nothing else is available

A Client ID Metadata Document looks like this:

{
  "client_id": "https://app.example.com/oauth/client-metadata.json",
  "client_name": "Example MCP Client",
  "redirect_uris": ["http://127.0.0.1:3000/callback"],
  "grant_types": ["authorization_code"],
  "response_types": ["code"],
  "token_endpoint_auth_method": "none"
}

The client_id inside the document must match the URL it is served from. The authorization server validates the redirect URI in each request against the list. Source: client registration.

Do MCP servers have to use OAuth? What about API keys?

No. The specification says authorization is optional, and it treats the transports differently:

Server typeWhat the specification saysWhat you will meet
Remote, HTTP transport, with OAuthSHOULD conform to the authorization specificationThe flow above. The client holds an access token for the MCP server
Remote, HTTP transport, with an API keyNot defined by the specificationA static key or token in a header, usually Authorization: Bearer <key>, set in the client's config
Local, stdio transportSHOULD NOT use the OAuth flow, and instead retrieve credentials from the environmentA key in the env block of the client's config, read by the server process

A header-key server is simple and works with any client that can send a header. What you give up is everything the OAuth flow provides: a key has no audience binding, usually no expiry, and no consent screen that says what it can do. Whoever holds the config file holds the key.

In Claude Code, a header-key server is configured like this, with the key read from the environment and not written into the file:

{
  "mcpServers": {
    "tracker": {
      "type": "http",
      "url": "https://mcp.example.com/mcp",
      "headers": { "Authorization": "Bearer ${TRACKER_API_KEY}" }
    }
  }
}

What goes wrong in practice?

The flow is well specified. Most trouble is at its edges.

A client that cannot register. The authorization server has no registration endpoint and does not accept metadata documents, and the client shipped with no ID for it. The specification's last resort is asking the user for client details, which means someone registers an OAuth app with the vendor by hand. Check which methods a server's authorization server supports before you depend on it.

One token for everyone. A token belongs to the person who signed in. A coding agent on your laptop acting as you is the case the flow was designed for. A hosted agent that serves a thousand customers with the one token its developer created is not: every customer's request runs as the developer's account, and the provider's audit log shows one user.

Tokens stored in the open. The specification requires clients to store tokens securely. In practice tokens and keys sit in JSON config files and shell environments, where any process the agent starts can read them. See AI agent secrets management.

Refresh that fails quietly. Access tokens are meant to be short-lived, and the client may not get a refresh token at all: the specification says clients must not assume one is issued. For public clients the authorization server must rotate refresh tokens, so two processes that refresh at the same moment can leave one of them holding a dead token. An agent that runs unattended needs a single place that refreshes, and a way to ask the user to sign in again.

Revocation nobody wired up. The authorization pages of the specification define no revocation step. Ending access is the authorization server's business: the user removes the app at the provider, or your system calls the provider's revocation endpoint. Deleting your copy of a token does not end the grant.

A proxy in the middle. A gateway or proxy between the client and the server is a second OAuth relationship, and it must not forward the client's token upstream. The specification also requires an MCP proxy that uses a static client ID with a third-party authorization server to get the user's consent for each dynamically registered client, to prevent confused deputy attacks. If you are evaluating one, see what to look for in an MCP gateway.

How do per-end-user credentials differ from a developer's own key?

This is the question behind most searches for "AI agent authentication". There are two different jobs, and they need different credentials.

A developer's own credentialA credential per end user
Who signed inYou, onceEach of your users, once each
Whose account a call usesYoursThat user's
Who chooses the user for a callNobody: there is oneYour server, from its own session. Never the model
Where the token livesYour MCP client or configA server-side store, encrypted, one row per user and provider
RefreshYour client does itYour backend does it, for every user, without a browser
When someone leavesYou remove one appThat user's tokens are revoked and deleted, and the others keep working
Blast radius of a leakEverything your account can doOne user's account

The MCP authorization flow gives you the left column. The right column is application work the specification leaves to you: a connect flow per user, a confirm step so a forwarded sign-in link cannot attach one person's account to another, storage, refresh and deletion. The build checklist for per-user OAuth covers each of those.

One rule matters more than the rest. The model must not be able to pick the user. If a tool has a userId argument, a prompt injection can change it. Bind the user on your server, before the model is involved.

Where does Anlyon fit?

Anlyon sits on both sides of MCP authorization. It is an MCP server your agent signs in to, and it is the client that signs in to other MCP servers so your agent does not hold their tokens.

Your agent signs in to Anlyon

The hosted server at https://api.anlyon.com/mcp follows the flow above. It answers the first request with 401 and a WWW-Authenticate header that names its protected resource metadata, at https://api.anlyon.com/.well-known/oauth-protected-resource/mcp. The client registers itself and opens a browser. On the consent screen you choose the workspace, the environment and the permissions the client gets. Access tokens last 15 minutes, and the client refreshes them.

claude mcp add --transport http anlyon https://api.anlyon.com/mcp

A server or CI job can send an Anlyon API key as the bearer instead. Either way the credential the agent holds is an Anlyon one. It can ask for the actions you allowed, and the provider credentials stay in Anlyon. Details: MCP servers in the docs.

Anlyon signs in to the remote MCP server

Register a remote server with Anlyon and it holds that server's credential.

For a server that signs people in with OAuth:

anlyon mcp add https://mcp.example.com/mcp --oauth --name tracker

Anlyon reads the server's sign-in metadata. For the client ID it brings its own client on a verified vendor's server, and registers a client where the server allows it. If neither applies, you register a client with the vendor and pass --client-id.

For a server that takes a key in a header, store the key in the console's Secrets with the server's host as its allowed host, and register the server with a reference:

anlyon mcp add https://mcp.example.com/mcp --name tracker \
  --header "Authorization: Bearer {{secret:TRACKER}}"

The header holds a reference, and the token stays in Anlyon. The model never sees a credential.

Each of your users signs in with their own account

For a server that uses OAuth, your server creates a connect link for the user signed in to your app, confirms the connection when they come back, and makes calls with a client bound to that user:

const result = await anlyon
  .forUser(user.id)
  .actions.invoke('tracker-list_issues', { project: 'WEB' });

The call uses that user's own account at the server. Anlyon keeps the token and refreshes it, and neither your app nor the agent ever holds it. Your server names the user, and the tools a model gets have no user field, so a prompt cannot switch users. A call for a user who has not connected is refused before anything is sent. When a user leaves, one call erases them: their connections are deleted and their pending approvals cancelled.

The steps and the callback code are in how to put a remote MCP server behind Anlyon.

What this does not cover

  • Local servers. Only remote servers over Streamable HTTP, or the older SSE transport, at an https address. A stdio server keeps its key in its own environment.
  • Calls that skip Anlyon. A tool your agent calls directly is not routed through Anlyon and is not governed by it. If the server is still in the agent's own config with its own token, that route is open.
  • What a token may do at the vendor. Scopes and permissions are the vendor's. Anlyon decides which adopted tools a call may reach and whether it waits for approval. It does not narrow a token.
  • Sign-in at every vendor. A server whose authorization server accepts neither Anlyon's client nor registration needs a client you register with that vendor.

Frequently asked questions

How does MCP OAuth work?
A remote MCP server answers an unauthenticated request with 401 and a WWW-Authenticate header that points to its protected resource metadata. The client reads which authorization server to use, obtains a client ID, runs an OAuth 2.1 authorization code flow with PKCE in the browser, and then sends the access token as a Bearer header on every request.
Does an MCP server have to use OAuth?
No. The MCP specification makes authorization optional. A server on an HTTP transport should follow the OAuth-based flow when it supports authorization, and a stdio server should take credentials from its environment instead. Many remote servers also accept a static API key in a header, which the specification does not define.
What is OAuth 2.1?
OAuth 2.1 is an IETF draft that consolidates OAuth 2.0 and its security best practices into one document. It requires PKCE for the authorization code flow, drops the implicit and password grants, requires exact redirect URI matching and keeps bearer tokens out of query strings. The MCP specification builds its authorization on it.
Is Dynamic Client Registration required for MCP?
No. In the 2026-07-28 revision it is optional and deprecated, kept for older authorization servers. The specification's preferred order is a pre-registered client ID, then a Client ID Metadata Document, then Dynamic Client Registration, then asking the user to enter client details.
How should an AI agent authenticate when it acts for many users?
With one credential per user, held on the server side and chosen by your application, not by the model. A single shared token makes every user's request run as one account. Each user should sign in to the provider once, and the agent's calls for that user should use that user's token.

Let your agent act for your users, safely.

A few lines of server code, then send a user a connect link. Nothing to host.

$ claude mcp add --transport http anlyon https://api.anlyon.com/mcp