Skip to main content

AI13 min read

LangChain MCP Auth: Bearer Tokens, OAuth 2.1, Per-User

MCPAdapter delegates auth to fastmcp.Client: pass a bearer token, "oauth" or an httpx.Auth; use ClientGroup per server and a graph factory for per-user tokens.

For an stdio server running on our own machine, authentication usually isn't a problem, because the server is already on our computer and runs as our user. Remote MCP servers are a different story. Whether it's GitHub, Sentry or an internal CRM, almost all of them want to know who we are. The good news is that MCPAdapter doesn't ask us to learn anything new for authentication. It leaves the job entirely to FastMCP: we give the credential to a fastmcp.Client, and we give that client to the adapter.

In the earlier articles of the series we covered MCPAdapter and transports, tool management and connection management. In this final article we focus on authentication: from a static token to the full OAuth flow, and from there to multi-server and multi-user scenarios.

Scope of this article: We touch on custom auth handlers in LangSmith Agent Server only in relation to per-user MCP authorization. We'll cover Agent Server and deployment separately in upcoming articles.

The core rule: auth lives on the client

In the old langchain-mcp-adapters package, auth and headers lived inside the connection config. Now we give the credential to a fastmcp.Client and hand that client to the adapter:

credential ──► fastmcp.Client(url, auth=...) ──► MCPAdapter(client) ──► list_tools()

The auth parameter of Client accepts three kinds of values:

auth value What happens When?
A string (e.g. "sk-...") Added to the Authorization header as a bearer token Service accounts, API keys, CI/CD
The literal "oauth" Full OAuth 2.1 flow (discovery, dynamic registration, browser, token exchange) Interactive apps acting on behalf of a user
An httpx.Auth object Authentication is fully delegated to that object BearerAuth, OAuth, custom schemes

Which one to pick:

Scenario Recommended approach
One server, we already have a token Bearer token
The server issues its own credentials, a user will log in OAuth 2.1
One agent, several servers needing different credentials Per-server auth (ClientGroup)
In a deployment, every run on behalf of the calling user Per-user auth

Bearer token

The simplest scenario: the server verifies a token we provisioned upfront, and we send it in the Authorization: Bearer <token> header. No discovery, browser or refresh step.

import os

from fastmcp.client import Client
from langchain.mcp import MCPAdapter


async def load_tools_with_bearer(url: str) -> list:
    token = os.environ["CRM_MCP_TOKEN"]
    async with MCPAdapter(Client(url, auth=token)) as adapter:
        return await adapter.list_tools()

In this example:

  • We pass the token without the Bearer prefix; FastMCP adds it.
  • We read the token from an environment variable instead of hardcoding it. A simple habit, but it keeps secrets out of the repository.
  • Bearer tokens only make sense for HTTP-based transports; for stdio servers, credentials are usually passed to the subprocess through env.

If we prefer to be explicit, we can use FastMCP's BearerAuth class instead of a string; the behavior is the same:

from fastmcp.client.auth import BearerAuth

client = Client(url, auth=BearerAuth(token=token))

When connecting to several servers with MCPConfig, each entry can take the same auth key:

config = {
    "mcpServers": {
        "crm": {"url": "https://crm.example.com/mcp", "auth": os.environ["CRM_TOKEN"]},
        "docs": {"url": "https://docs.example.com/mcp"},
    }
}
async with MCPAdapter(config) as adapter:
    tools = await adapter.list_tools()

Custom schemes: headers and httpx.Auth

Some servers expect a custom header such as X-API-Key instead of a bearer token. For that we can set headers on the transport instead of using auth:

from fastmcp.client.transports import StreamableHttpTransport

transport = StreamableHttpTransport(
    "https://api.example.com/mcp",
    headers={"X-API-Key": os.environ["API_KEY"]},
)
async with MCPAdapter(transport) as adapter:
    tools = await adapter.list_tools()

If we need more dynamic logic, such as signing requests or reading the token from a vault on every request, we can write our own httpx.Auth class. Since recent FastMCP releases use httpx2 in their HTTP layer, the example imports it:

import httpx2


class VaultTokenAuth(httpx2.Auth):
    """Reads a fresh token from a vault on every request."""

    def __init__(self, read_token):
        self.read_token = read_token

    def auth_flow(self, request):
        request.headers["Authorization"] = f"Bearer {self.read_token()}"
        yield request


client = Client("https://api.example.com/mcp", auth=VaultTokenAuth(read_from_vault))

auth_flow is a generator: it modifies the request and yields it. If needed, it can inspect the response (e.g. on a 401), refresh the token and resend the request. FastMCP's BearerAuth and OAuth classes implement the same interface.

OAuth 2.1

For a server that manages its own credentials, passing auth="oauth" is enough. FastMCP runs the full OAuth 2.1 flow:

async def load_tools_with_oauth(url: str) -> list:
    async with MCPAdapter(Client(url, auth="oauth")) as adapter:
        return await adapter.list_tools()

What happens behind the scenes:

1. Token check        : is there a valid token for this server in token_storage?
2. Server discovery   : /.well-known/oauth-protected-resource → authorization server
                        /.well-known/oauth-authorization-server → endpoints
3. Client registration: skip if client_id is set; otherwise CIMD or dynamic registration (RFC 7591)
4. Local callback     : temporary server at http://localhost:<port>/callback
5. Browser            : the user logs in and grants the scopes
6. Token exchange     : authorization code + PKCE → access token (+ refresh token)
7. Token storage      : written to token_storage
8. Authorized requests: Authorization header added automatically
9. Refresh            : the refresh token renews an expired access token

The notable concept here is Dynamic Client Registration. In classic OAuth, we first have to create an application in the authorization server and get a client_id. In MCP, the client can register itself at runtime, so we don't need to pre-provision a client identity. That's what lets an agent connect to an MCP server it has never seen before.

Persisting tokens

By default tokens are held in memory, so the browser step repeats every time the application restarts. To avoid that, we build an OAuth provider with a token_storage:

import os
from pathlib import Path

from cryptography.fernet import Fernet
from fastmcp.client import Client
from fastmcp.client.auth import OAuth
from key_value.aio.stores.filetree import (
    FileTreeStore,
    FileTreeV1CollectionSanitizationStrategy,
    FileTreeV1KeySanitizationStrategy,
)
from key_value.aio.wrappers.encryption import FernetEncryptionWrapper

token_dir = Path("~/.my-agent/oauth-tokens").expanduser()
token_dir.mkdir(parents=True, exist_ok=True)

file_store = FileTreeStore(
    data_directory=token_dir,
    key_sanitization_strategy=FileTreeV1KeySanitizationStrategy(token_dir),
    collection_sanitization_strategy=FileTreeV1CollectionSanitizationStrategy(token_dir),
)
encrypted_storage = FernetEncryptionWrapper(
    key_value=file_store,
    fernet=Fernet(os.environ["OAUTH_STORAGE_ENCRYPTION_KEY"]),
)

oauth = OAuth(scopes=["read"], token_storage=encrypted_storage)
client = Client("https://example.com/mcp", auth=oauth)

async with MCPAdapter(client) as adapter:
    tools = await adapter.list_tools()

In this example:

  • FileTreeStore keeps tokens in a directory tree on disk; other AsyncKeyValue backends such as Redis or DynamoDB work too.
  • FernetEncryptionWrapper encrypts the stored tokens. Using encrypted storage in production is very important; an MCP client can accumulate tokens for many servers over time, and a compromised token store means access to all of them.
  • When OAuth is used through Client(auth=...), we don't need to pass mcp_url; the transport provides the server address.

The most commonly used OAuth parameters:

Parameter What it does
scopes OAuth scopes to request (list or space-separated string)
token_storage AsyncKeyValue backend for storing tokens; defaults to memory
client_name Client name shown in dynamic registration (default "FastMCP Client")
client_id Pre-registered client ID; when set, dynamic registration is skipped entirely
client_secret Secret for pre-registered confidential clients
issuer The authorization server that registered client_id; the secret is sent only to it
client_metadata_url URL-based client identity (CIMD)
callback_port / callback_host Port and host of the local callback server
callback_timeout How long to wait for the browser callback (default 300 seconds)

When passing a client_secret, also passing issuer is a good habit. The MCP server tells the client which authorization server to use; without issuer, a malicious or compromised server could name its own authorization server and collect our secret. With issuer set, the client checks this match before any credentials leave it.

FastMCP also ships providers for common identity providers such as Auth0, WorkOS and Okta; the flow the client runs is the same across all of them.

I also want to point out one thing here. When we use auth="oauth", a browser opens and a small callback server starts on our machine. That works great in desktop apps and during development. But it doesn't work for applications running on a server without a screen. In those cases we need the per-user approach we'll talk about below, or machine-to-machine authentication (client credentials).

Per-server authentication

When an agent talks to several servers, each may want a different credential: one OAuth, another a static token. In that case we give each server its own connection with a ClientGroup and set auth per client:

import os

from fastmcp.client import Client
from fastmcp.client.group import ClientGroup
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter


async def agent_with_per_server_auth(billing_url: str, docs_url: str):
    group = ClientGroup(
        {
            "billing": Client(billing_url, auth="oauth"),
            "docs": Client(docs_url, auth=os.environ["DOCS_TOKEN"]),
        }
    )
    async with MCPAdapter(group) as adapter:
        tools = await adapter.list_tools()  # billing_..., docs_...
        return create_agent("openai:gpt-6.1-sol", tools)

In this example:

  • The billing server authenticates with the OAuth flow, the docs server with a static token.
  • Since each member holds its own connection, credentials never get mixed; billing's token is never sent to docs.
  • Tool names still come prefixed as {server}_{tool}.

For simple fleets the auth key in MCPConfig entries also works. But since members may also be on different protocol eras, ClientGroup is the safer choice as credentials diverge.

Per-user authentication

The most important question in a deployment is: on whose behalf does the agent connect to the MCP server? If we use one shared service account, every user can see everything that account can see. The right approach is for each run to reach the MCP server as the user who started it.

The pattern has two halves:

  1. Authenticate the caller at LangSmith Agent Server. A custom auth handler resolves the incoming request to a user identity, which each run can read off its runtime.
  2. Mint or exchange a credential for that user. Inside the graph factory we read the user's identity and build the MCP client with a per-user token, so the connection carries that user's permissions.

For the first half, we define an auth handler on Agent Server. We'll go through the details in the Agent Server article; for now the skeleton looks like this:

# auth.py
from langgraph_sdk import Auth

auth = Auth()


@auth.authenticate
async def authenticate(authorization: str | None) -> Auth.types.MinimalUserDict:
    user_id = await verify_session(authorization)  # our own verification logic
    return {"identity": user_id}

The second half is a user-aware version of the graph factory we saw in the connections article:

# agent.py
from fastmcp.client import Client
from fastmcp.client.auth import BearerAuth
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter

CONFIG = {
    "mcpServers": {
        "docs": {"url": "https://example.com/mcp"},
    }
}


async def make_graph(runtime):
    user = runtime.user.identity if runtime.user is not None else "anonymous"
    auth = BearerAuth(token_for(user))  # per-user token
    async with MCPAdapter(Client(CONFIG, auth=auth)) as adapter:
        tools = await adapter.list_tools()
        return create_agent("openai:gpt-6.1-sol", tools)

In this example:

  • make_graph is called on every run and reaches the identity of the user who started that run through runtime.user.
  • token_for(user) stands in for whatever the deployment already has: an OAuth gateway that exchanges the session for a per-user token, or a fastmcp.client.auth provider that runs the authorization-code flow per identity.
  • As a result the MCP server sees every request as the real user and applies its own permission checks accordingly. The agent can't reach data the user can't reach.

Isolating the cache per user

There's an easy-to-miss risk with per-user auth: the cache. A server may return different tool lists to different users (for example, tools visible only to admins). If a shared cache doesn't separate users, one user could see another user's cached tool list.

That's why cached responses need to be partitioned by the verified identity:

from fastmcp.client import Client
from fastmcp.client.auth import BearerAuth
from mcp.client.caching import CacheConfig

# SHARED_STORE: a store shared by all replicas, e.g. a KeyValueResponseCacheStore on Redis


async def make_graph(runtime):
    user = runtime.user.identity if runtime.user is not None else "anonymous"
    cache = CacheConfig(store=SHARED_STORE, partition=f"user:{user}", target_id="docs")
    client = Client(CONFIG, auth=BearerAuth(token_for(user)), cache=cache)
    async with MCPAdapter(client) as adapter:
        tools = await adapter.list_tools()
        return create_agent("openai:gpt-6.1-sol", tools)

Here partition is derived from the identity Agent Server verified, not from the request body or the server URL. When the identity changes, a new client is built; since the factory runs on every run, this happens naturally.

Security checklist

I wanted to collect the security points that came up across the whole series in one place:

Topic Recommendation
Secrets Don't hardcode tokens; use environment variables or a vault
Token store Store OAuth tokens encrypted (FernetEncryptionWrapper)
client_secret Always pass it together with issuer
Scopes Request only the permissions needed via scopes
On whose behalf? Per-user tokens in deployments instead of a shared account
Cache Partition shared caches by verified identity
Targets Remember that string targets can only be URLs (first article)
Destructive tools Human-in-the-loop approval driven by annotations (second article)

Wrapping up

In this article we saw that MCPAdapter doesn't teach us a new way of doing authentication. We give the credential to a fastmcp.Client, and we give the client to the adapter. A string for a simple token, "oauth" for servers where the user needs to log in, and our own httpx.Auth class for more specific needs are enough. When working with several servers, ClientGroup lets us keep each server's credentials separate. And when we go live, running every request on behalf of the user who made it saves us from the risks of everyone sharing a single account.

With this article we've completed the LangChain MCP series. All articles in the series:

  1. LangChain MCP Tutorial: Connect Agents with MCPAdapter
  2. LangChain MCP Tools: Outputs, Metadata, HITL, Elicitation
  3. LangChain MCP Connections: MCPConfig, ClientGroup, Caching
  4. LangChain MCP Auth: Bearer Tokens, OAuth 2.1, Per-User (this article)

Human-in-the-loop, LangGraph interrupts and Agent Server deployment, which we only touched on in this series, will be the subjects of upcoming articles. See you in the next article.

Sources

The langchain.mcp API described here is in beta, and FastMCP's authentication details may change between releases. It's a good habit to verify the details for the version you're using against the official documentation.

  • langchain
  • mcp
  • authentication
  • oauth
  • python

← Back to all posts