Why Your MCP Token Expires Mid-Run
Himesh Siriwardana·28 min read
All posts
- MCP Authorization: The Complete Developer Guide
- MCP and OAuth 2.1: What Actually Changed and Why It Matters
- Connecting an AI Agent to an OAuth-Protected MCP Server
- Connecting a LangGraph Agent to an OAuth-Protected MCP Server
- MCP Server Auth vs MCP Client Auth: Two Different Problems
- Why Your MCP Token Expires Mid-Run
- The Architect's Guide to React Authentication: Choosing a Flow, a Store and a Boundary
- React Authentication Best Practices: The 2026 Checklist
- Best Authentication Libraries for React in 2026
- Open Source and Self-Hosted Auth for React in 2026
- JWT-Based Authentication in React: Storage, Validation and the localStorage Question
- Passwordless Login in React: Passkeys, Magic Links and OTP
- OAuth 2.0 and OIDC in React: The Authorization Code Flow with PKCE, Explained
- React Authentication: The Complete Guide
On this page
- Why does a token that worked earlier fail now?
- Why isn't refreshing the token enough?
- The MCP SDK asks for a token before every request
- What does the application's token layer do?
- Prove the new token reaches the MCP server
- Whose token is it?
- What if two tool calls refresh at the same time?
- What about state between tool calls?
- Which lifecycle broke?
- Back to the approval that came too late
An agent calls an MCP tool. The server returns 200 OK. The next call works too. Then the agent pauses because someone needs to approve an action.
Twenty minutes later, the approval arrives. The agent resumes, calls another tool, and gets 401 Unauthorized.
The server hasn't changed, and neither has the MCP client. But the access token that worked twenty minutes ago has expired.
In Connecting a LangGraph Agent to an OAuth-Protected MCP Server, the MCP SDK handled token refresh for us. Its OAuthClientProvider stored the tokens, refreshed them when necessary, and retried requests with the new credentials.
That works when the MCP client manages OAuth. In a hosted application, the user often signs in through the application's own login flow. The application keeps their tokens alongside the session and gives the MCP client an access token.
That split leaves a gap. The application can get a fresh token, but the MCP client keeps using the one it was handed.
In this article, we'll close that gap, so every MCP request carries the user's current token, and the agent never touches a credential.
Why does a token that worked earlier fail now?
The user signs in and the application passes an access token to the MCP client. The MCP server accepts the first few requests. Then the agent waits long enough for the token to expire:
- Tool call 1POST /mcp
Authorization: Bearer access_token_1 - 200 OK
- the agent waits for approval, calls other tools, does more work
- Tool call 2POST /mcp
Authorization: Bearer access_token_1 - 401 Unauthorized
The second request uses the same token as the first. That's fine in a quick test, when both calls happen before expiry. It breaks in a longer run, where the agent may wait on an approval or spend time working with other tools.
Why isn't refreshing the token enough?
The application can use its refresh token to get another access token from the authorization server. But even after a successful refresh, the next MCP call can still return 401.
Here's a common way to construct an MCP transport:
const transport = new StreamableHTTPClientTransport(serverUrl, {
requestInit: {
headers: {
Authorization: `Bearer ${session.accessToken}`
}
}
});
${session.accessToken} is evaluated when the transport is created. The resulting header doesn't change when session.accessToken changes.
The application can be holding a fresh token while the transport continues sending the old one:
- Application
- access_token_1 expires
- Refresh
- access_token_2
MCP client- Authorization: Bearer access_token_1
- Next tool call
- 401 Unauthorized
The application has the new token, but the transport's header still contains the old one. Refreshing isn't enough when the MCP client never reads the refreshed value.
Instead, the transport needs to ask the application for a token when it's about to send a request. The agent can keep calling tools without handling OAuth itself.
The MCP SDK asks for a token before every request
The fixed header failed because the token was read once, when the transport was created. What we want is the opposite: the transport asks for the token each time it sends a request.
The MCP TypeScript SDK supports this through the transport's authProvider option.
Start with one method
The smallest authProvider has a single method, token(). The transport calls it before every request and puts whatever it returns in the Authorization header:
const transport = new StreamableHTTPClientTransport(serverUrl, {
authProvider: {
token: async () => session.accessToken
}
});
Compare this with the fixed header from earlier. The template string ran once. This function runs on every request, so it reads session.accessToken every time. When the application replaces the token, the next request picks up the new one.
The SDK calls this shape an AuthProvider.
Ask for a specific user's token
session in that example holds one user's token. A hosted application serves many users at once, and each of them has their own tokens.
So token() can't just read a variable. It has to answer a more specific question: whose token does this request need?
That means the provider needs two things:
- The user it's working for, so it knows whose token to ask for.
- Somewhere to ask, which can look up that user's tokens and refresh them when they're about to expire.
For the second, we'll use a TokenService. We'll build it in the next section. For now, it's enough to know it has a method called getAccessToken(userId), which returns that user's current token.
With both in hand, we can write a function that builds a provider for one user:
export function authProviderFor(
userId: string,
tokens: TokenService
): AuthProvider {
return {
token: () => tokens.getAccessToken(userId)
};
}
Here's how it works:
- Your application calls
authProviderFor()once, with the signed-in user's ID and the sharedTokenService. - The function returns a provider whose
token()remembers that user ID. - Before each MCP request, the transport calls
token(), which asksTokenServicefor that user's current token.
The provider never stores a token itself. It only knows which user it belongs to, so it always gets the latest token for that user.
Handle a token the server rejects anyway
getAccessToken() decides by the clock. It looks at when the token expires, and refreshes it if that time is close.
Most of the time, that's enough. But a token can stop working before its expiry time. For example:
- The authorization server revoked it early, for example because the user signed out everywhere.
- The MCP server's clock runs slightly ahead of yours, so it treats the token as expired sooner than you do.
The clock can't see either of those. The token looks fine, the request goes out, and the MCP server answers 401.
For that case, AuthProvider has a second, optional method, onUnauthorized(). Add it next to token():
return {
token: () => tokens.getAccessToken(userId),
onUnauthorized: async () => {
await tokens.refresh(userId);
}
};
Here's what happens when the server rejects a token:
- The transport sends the request, and the server answers
401. - The transport calls
onUnauthorized(), which asksTokenServiceto refresh the user's token, whatever its expiry time says. - The transport sends the same request again. Before it does, it calls
token(), which now returns the refreshed token.
The transport retries only once. If the refresh fails too, for example because the user's access was revoked, the error reaches your application. At that point, the user needs to sign in again.
Connect a client for one user
We now have a provider for one user. The last piece is an MCP client that uses it.
If you built the client in Connecting an AI Agent to an OAuth-Protected MCP Server, this part will look familiar. That client created its transport like this:
new StreamableHTTPClientTransport(serverUrl, {
authProvider: provider
});
There, provider was the SDK's OAuth provider, which ran the whole sign-in flow and kept the tokens itself. The LangGraph agent reused that same connection code.
Here, the application already has the tokens, so we pass our own provider in the same option:
new StreamableHTTPClientTransport(serverUrl, {
authProvider: authProviderFor(userId, tokens)
});
Everything else about the client stays the same. We'll wrap it in a function called connectAs(), so the rest of the application can ask for "an MCP client for this user" in one call. Here's what it does:
- Creates an MCP client with the same
versionNegotiationoption as before. - Creates a transport with that user's provider.
- Connects, and returns the client.
Put both functions in one file. Create mcp-auth.ts:
import {
Client,
StreamableHTTPClientTransport,
type AuthProvider
} from '@modelcontextprotocol/client';
import type { TokenService } from './token-service.js';
export function authProviderFor(
userId: string,
tokens: TokenService
): AuthProvider {
return {
// Runs before every MCP request.
token: () => tokens.getAccessToken(userId),
// Runs when the server answers 401. The transport then retries once.
onUnauthorized: async () => {
await tokens.refresh(userId);
}
};
}
export async function connectAs(
userId: string,
tokens: TokenService,
serverUrl: URL
) {
const client = new Client(
{
name: 'agent-app',
version: '1.0.0'
},
{
versionNegotiation: {
mode: 'auto'
}
}
);
const transport = new StreamableHTTPClientTransport(serverUrl, {
authProvider: authProviderFor(userId, tokens)
});
await client.connect(transport);
return client;
}
Every request a client from connectAs() sends now follows this path:
- The agent chooses a tool
- The MCP client prepares the request
- The transport calls
token() - The application returns the current token
- The request goes out with that token
The transport asks for a token just before it needs one. Whether that's the stored token or a fresh one is up to TokenService.
What does the application's token layer do?
Now for the TokenService that token() has been calling. It has three jobs:
- Load the user's stored tokens.
- Decide whether the access token is still good.
- Refresh it when it isn't.
We'll build it in that order, then put the pieces together in one file.
TokenService isn't part of the MCP SDK or LangChain. It's an example implementation, and so are the names it uses, such as StoredTokens, TokenStore, and ReauthorizationRequiredError. If your application already has a session or token layer, that layer can do the same job. All token() needs is a function that returns the user's current access token.
Where the tokens live
When the user signs in, your application receives an access token, a refresh token, and how long the access token lasts. That's what TokenService works with:
export interface StoredTokens {
accessToken: string;
refreshToken?: string;
expiresAt: number;
}
export interface TokenStore {
get(userId: string): Promise<StoredTokens | undefined>;
save(userId: string, tokens: StoredTokens): Promise<void>;
}
Here's what each one holds:
-
StoredTokensis one user's tokens.expiresAtis when the access token expires, as a timestamp in milliseconds. -
The authorization server doesn't send that timestamp. Its token response has an
expires_infield instead: how many seconds the access token is valid from now, such as3600for one hour. To getexpiresAt, add it to the current time when you receive the token:Date.now() + expires_in * 1000. -
TokenStoreis wherever your application already keeps session data, such as an encrypted database table.TokenServiceonly needs toget()a user's tokens andsave()new ones.
Decide whether the token is still good
getAccessToken() is the method token() calls before every MCP request:
async getAccessToken(userId: string) {
const tokens = await this.store.get(userId);
if (!tokens) {
throw new ReauthorizationRequiredError(userId);
}
if (tokens.expiresAt - Date.now() > this.expiryMarginMs) {
return tokens.accessToken;
}
const refreshed = await this.refresh(userId);
return refreshed.accessToken;
}
It works through three checks:
- If the user has no stored tokens, they need to sign in. It throws a
ReauthorizationRequiredError, an error class we'll define in a moment. - If the token has more than
expiryMarginMsleft, 30 seconds by default, it returns the stored token. - Otherwise, it refreshes first and returns the new token.
- MCP request about to be sent
- Does the stored token have more than 30 seconds left?
- yes
- Reuse it
no- Refresh it and save the result
- Authorization: Bearer current_token
Why refresh early? A token with one second left could expire on its way to the MCP server. The margin gives every request time to arrive.
Refresh the token
The refresh itself happens in runRefresh():
private async runRefresh(userId: string) {
const current = await this.store.get(userId);
if (!current?.refreshToken) {
throw new ReauthorizationRequiredError(userId);
}
const next = await this.refreshGrant(current.refreshToken);
if (!next) {
throw new ReauthorizationRequiredError(userId);
}
await this.store.save(userId, next);
return next;
}
Step by step:
- It loads the user's tokens again and checks there's a refresh token to use.
- It calls
refreshGrant, which exchanges the refresh token for new tokens. - It saves the new tokens, so the next
getAccessToken()call finds them.
Notice that TokenService doesn't talk to the authorization server itself. refreshGrant is a function you pass in, with this shape:
// Returns undefined when the authorization server rejects the refresh token.
export type RefreshGrant = (
refreshToken: string
) => Promise<StoredTokens | undefined>;
That keeps the service the same whichever authorization server you use. We'll write one shortly.
If there's no refresh token, or the authorization server rejects it, runRefresh() throws a ReauthorizationRequiredError:
export class ReauthorizationRequiredError extends Error {
constructor(readonly userId: string) {
super(`User ${userId} needs to sign in again`);
}
}
That error means the user's authorization has ended. Catch it where your application can send the user to sign in again. The agent can't fix it.
Refresh once per user
One method is left. getAccessToken() and onUnauthorized() both call refresh(), not runRefresh():
refresh(userId: string) {
// If this user's token is already being refreshed, wait for that.
let pending = this.refreshing.get(userId);
if (!pending) {
pending = this.runRefresh(userId).finally(() => {
this.refreshing.delete(userId);
});
this.refreshing.set(userId, pending);
}
return pending;
}
refreshing maps each user ID to the refresh that's currently running for them. If a second request needs a new token while the first is still refreshing, it waits for the same refresh instead of starting another. We'll see why that matters in What if two tool calls refresh at the same time?
Put it together
Create token-service.ts with everything above:
export interface StoredTokens {
accessToken: string;
refreshToken?: string;
expiresAt: number;
}
export interface TokenStore {
get(userId: string): Promise<StoredTokens | undefined>;
save(userId: string, tokens: StoredTokens): Promise<void>;
}
// Returns undefined when the authorization server rejects the refresh token.
export type RefreshGrant = (
refreshToken: string
) => Promise<StoredTokens | undefined>;
export class ReauthorizationRequiredError extends Error {
constructor(readonly userId: string) {
super(`User ${userId} needs to sign in again`);
}
}
export class TokenService {
private refreshing = new Map<string, Promise<StoredTokens>>();
constructor(
private store: TokenStore,
private refreshGrant: RefreshGrant,
// Refresh a little early, so a token can't expire in flight.
private expiryMarginMs = 30_000
) {}
async getAccessToken(userId: string) {
const tokens = await this.store.get(userId);
if (!tokens) {
throw new ReauthorizationRequiredError(userId);
}
if (tokens.expiresAt - Date.now() > this.expiryMarginMs) {
return tokens.accessToken;
}
const refreshed = await this.refresh(userId);
return refreshed.accessToken;
}
refresh(userId: string) {
// If this user's token is already being refreshed, wait for that.
let pending = this.refreshing.get(userId);
if (!pending) {
pending = this.runRefresh(userId).finally(() => {
this.refreshing.delete(userId);
});
this.refreshing.set(userId, pending);
}
return pending;
}
private async runRefresh(userId: string) {
const current = await this.store.get(userId);
if (!current?.refreshToken) {
throw new ReauthorizationRequiredError(userId);
}
const next = await this.refreshGrant(current.refreshToken);
if (!next) {
throw new ReauthorizationRequiredError(userId);
}
await this.store.save(userId, next);
return next;
}
}
Call the token endpoint
The last piece is a RefreshGrant that asks your authorization server for new tokens. Refreshing a token is standard OAuth, so the request looks the same with any compliant authorization server.
Let's look at the request before the code that sends it.
What the refresh request looks like
Your application sends a POST to the authorization server's token endpoint:
POST /oauth2/token HTTP/1.1
Authorization: Basic <base64 of client_id:client_secret>
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&refresh_token=<stored-refresh-token>&resource=http%3A%2F%2Flocalhost%3A3000%2Fmcp
In plain terms, this request says: here's who I am, here's the refresh token you gave me, and I want a new access token for the MCP server.
Each part has a job:
- The
Authorizationheader proves which application is asking, using its client ID and secret. grant_type=refresh_tokensays this is a refresh, not a new sign-in.refresh_tokenis the oneTokenServiceloaded from the store.resourceis the MCP server's identifier. The MCP specification asks clients to send it on token requests, refreshes included, so the new token is still meant for the MCP server.
What comes back
If the refresh token is still good, the authorization server returns new tokens:
{
"access_token": "<new-access-token>",
"refresh_token": "<new-refresh-token>",
"token_type": "Bearer",
"expires_in": 3600
}
expires_in is the same field from Where the tokens live, so we turn it into a new expiresAt. The refresh_token may be a new one, if the server rotates refresh tokens, or missing, if it doesn't.
If the refresh token expired or was revoked, the server answers 400 instead:
{
"error": "invalid_grant"
}
That one means the user has to sign in again.
Send it from code
Create refresh-access-token.ts:
import type { StoredTokens } from './token-service.js';
const tokenEndpoint = process.env.OAUTH_TOKEN_ENDPOINT!;
const clientCredentials = Buffer.from(
`${process.env.APP_CLIENT_ID}:${process.env.APP_CLIENT_SECRET}`
).toString('base64');
export async function refreshAccessToken(
refreshToken: string
): Promise<StoredTokens | undefined> {
const response = await fetch(tokenEndpoint, {
method: 'POST',
headers: {
Authorization: `Basic ${clientCredentials}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
// Keep the new access token bound to the MCP server.
resource: process.env.MCP_RESOURCE!
})
});
const body = await response.json();
if (body.error === 'invalid_grant') {
// The refresh token expired or was revoked.
return undefined;
}
if (!response.ok) {
throw new Error(`Token refresh failed: ${body.error}`);
}
return {
accessToken: body.access_token,
// Some servers rotate refresh tokens. Keep the newest one.
refreshToken: body.refresh_token ?? refreshToken,
expiresAt: Date.now() + body.expires_in * 1000
};
}
Here's how the function maps to the exchange above:
- It reads the token endpoint from
OAUTH_TOKEN_ENDPOINT, and builds theAuthorizationheader fromAPP_CLIENT_IDandAPP_CLIENT_SECRET. - It sends the request body with
grant_type,refresh_token, andresource. - If the server answers
invalid_grant, it returnsundefined, andTokenServiceturns that into aReauthorizationRequiredError. - If the server answers with any other error, such as a misconfigured client, it throws.
- Otherwise, it returns the new
StoredTokens, keeping the old refresh token if the server didn't send a new one.
The three environment variables come from your own setup:
OAUTH_TOKEN_ENDPOINTis listed astoken_endpointin your authorization server's metadata. With WSO2 Identity Platform, as in the earlier articles, it'shttps://api.asgardeo.io/t/<organization>/oauth2/token.APP_CLIENT_IDandAPP_CLIENT_SECRETbelong to the application you registered for your app's sign-in, not the MCP client application from the earlier articles. Because it holds a secret, that application must run on a server. Never put the secret in a browser app.
Before you rely on it, check your authorization server's setup:
- The application needs the refresh token grant enabled. Many authorization servers leave it off by default. In WSO2 Identity Platform, you'll find it in the allowed grant types on the application's Protocol tab.
- After a refresh, the token's
audclaim should still name your MCP server. - The user's original sign-in must have covered the MCP server and its scopes, such as
mcp:tools. A refresh can't add permissions the user never granted. If the server answersinsufficient_scope, the user needs to authorize again with more scopes. Refreshing won't help.
LangGraph never handles the access token. The application resolves it, and the MCP transport attaches it to the outgoing request.
Prove the new token reaches the MCP server
We can reproduce the failure and test the fix without an authorization server or a model key.
The plan is simple. We'll run a tiny MCP server whose tokens expire after two seconds, and log the token on every tool call. Then we'll call it twice through a fixed header, and twice through connectAs(), and compare what the server receives.
Set up the project
-
Create a project and install the dependencies:
mkdir mcp-token-refresh
cd mcp-token-refresh
npm init -y
npm pkg set type=module
npm install --save-exact @modelcontextprotocol/[email protected] @modelcontextprotocol/[email protected] @modelcontextprotocol/[email protected] zod@4
npm install --save-dev typescript tsx @types/node -
Create a
tsconfig.json:{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"types": ["node"],
"strict": true,
"skipLibCheck": true,
"noEmit": true
}
} -
Copy
token-service.tsandmcp-auth.tsfrom above into the project. The script doesn't needrefresh-access-token.ts.
Build the script
We'll build prove-refresh.ts one part at a time. Add each part to the end of the file.
-
Create
prove-refresh.tsand add the imports:import http from 'node:http';
import { setTimeout as sleep } from 'node:timers/promises';
import {
Client,
StreamableHTTPClientTransport
} from '@modelcontextprotocol/client';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';
import { connectAs } from './mcp-auth.js';
import {
TokenService,
type StoredTokens
} from './token-service.js';The script uses the MCP client and server packages, plus the
TokenServiceandconnectAs()you just copied. -
Add a stand-in authorization server:
// 1. A stand-in authorization server. Its tokens expire after 2 seconds.
let issued = 0;
const expiries = new Map<string, number>();
function issueTokens(): StoredTokens {
issued += 1;
const accessToken = `access_token_${issued}`;
const expiresAt = Date.now() + 2_000;
expiries.set(accessToken, expiresAt);
return {
accessToken,
refreshToken: `refresh_token_${issued}`,
expiresAt
};
}Every call to
issueTokens()returns a new, numbered token that's valid for two seconds.expiriesremembers when each one expires, so the MCP server can check it. -
Add the MCP server:
// 2. An MCP server that rejects expired tokens and logs what it receives.
const mcpHandler = toNodeHandler(
createMcpHandler(() => {
const server = new McpServer({ name: 'demo', version: '1.0.0' });
server.registerTool(
'add',
{
description: 'Add two numbers',
inputSchema: z.object({ a: z.number(), b: z.number() })
},
async ({ a, b }) => ({
content: [{ type: 'text', text: String(a + b) }]
})
);
return server;
})
);
const httpServer = http.createServer((req, res) => {
const token = req.headers.authorization?.replace('Bearer ', '');
const valid = (expiries.get(token ?? '') ?? 0) > Date.now();
if (req.headers['mcp-method'] === 'tools/call') {
console.log(` server got ${token}: ${valid ? '200' : '401'}`);
}
if (!valid) {
res.writeHead(401, {
'WWW-Authenticate': 'Bearer error="invalid_token"'
});
res.end();
return;
}
void mcpHandler(req, res);
});
httpServer.listen(3600);
const serverUrl = new URL('http://localhost:3600/mcp');It has one tool,
add. Before each request, it checks the token againstexpiries. For tool calls, it logs the token it received and whether it accepted it. An expired token gets a401.This is only a test double. It doesn't validate real OAuth tokens.
-
Add a helper that calls the
addtool:async function callAdd(client: Client) {
try {
await client.callTool({ name: 'add', arguments: { a: 2, b: 3 } });
} catch {
console.log(' the call failed');
}
}If the call fails, the helper logs it and carries on, so the script can continue to the next test.
-
Add the first test, with the token fixed in a header:
// 3. A token fixed in a header when the client is created.
console.log('Fixed header:');
const fixed = new Client(
{ name: 'fixed', version: '1.0.0' },
{ versionNegotiation: { mode: 'auto' } }
);
await fixed.connect(
new StreamableHTTPClientTransport(serverUrl, {
requestInit: {
headers: { Authorization: `Bearer ${issueTokens().accessToken}` }
}
})
);
await callAdd(fixed);
await sleep(2_500);
await callAdd(fixed);
await fixed.close();This client gets one token when it's created. It calls
add, waits until the token expires, and calls again. -
Add the second test, with the token resolved before every request:
// 4. The same calls, with the token resolved before every request.
console.log('Token hook:');
const store = new Map<string, StoredTokens>();
store.set('alice', issueTokens());
const tokens = new TokenService(
{
get: async userId => store.get(userId),
save: async (userId, next) => {
store.set(userId, next);
}
},
async () => issueTokens(),
500
);
const client = await connectAs('alice', tokens, serverUrl);
await callAdd(client);
await sleep(2_500);
await Promise.all([callAdd(client), callAdd(client)]);
await client.close();
console.log(`Tokens issued: ${issued}`);
httpServer.close();This client comes from
connectAs(), with aTokenServicebacked by a simpleMap. Its refresh grant isissueTokens(), and its margin is 500 milliseconds, because these tokens only live for two seconds.It calls
add, waits until the token expires, and then makes two calls at the same time.
Run it
-
Run the script:
node --import tsx prove-refresh.ts -
Check the output. You should see:
Fixed header:
server got access_token_1: 200
server got access_token_1: 401
the call failed
Token hook:
server got access_token_2: 200
server got access_token_3: 200
server got access_token_3: 200
Tokens issued: 3
There it is. The fixed-header client sent access_token_1 twice. The first request succeeded. The second got a 401, because the token had expired.
The other client started with access_token_2. After the pause, both of its calls sent access_token_3, the refreshed token, without creating a new MCP client.
The last line proves something else, too. Two calls needed a new token at the same moment, and only one refresh happened. Three tokens were issued in total, not four.
Whose token is it?
The example so far has one user. A hosted application may have many users running agents concurrently.
Suppose Alice and Bob each start a run, but the application keeps the active token in a module-level variable:
let currentAccessToken: string | undefined;
Every run in the same Node.js process shares that variable:
- Alice's run sets
currentAccessTokento Alice's token - Bob's run sets
currentAccessTokento Bob's token - Alice's next MCP request reads
currentAccessToken - Alice's request carries Bob's credential
Alice's next request could go out with Bob's access token. Depending on the permissions behind it, that's a cross-user security failure.
The userId argument in authProviderFor() prevents the transport from reading an arbitrary shared token. Each run creates an MCP client bound to its user, and token() always loads tokens for that user.
Here's how that looks in a full agent run. We'll put it in run-agent.ts, in two parts.
-
Create
run-agent.tsand set up what every run shares:import { loadMcpTools } from '@langchain/mcp-adapters';
import { createAgent } from 'langchain';
import { connectAs } from './mcp-auth.js';
import { TokenService } from './token-service.js';
import { tokenStore } from './token-store.js';
import { refreshAccessToken } from './refresh-access-token.js';
const tokens = new TokenService(tokenStore, refreshAccessToken);
const serverUrl = new URL(process.env.MCP_SERVER_URL!);There's one
TokenServicefor the whole application. It's safe to share, because it never holds "the current token". It stores tokens by user ID.token-store.tsis your application's ownTokenStore, backed by wherever it keeps sessions. -
Add
runAgentFor(), which runs the agent for one user:export async function runAgentFor(userId: string, question: string) {
const client = await connectAs(userId, tokens, serverUrl);
try {
const tools = await loadMcpTools('mcp', client);
const agent = createAgent({
model: process.env.MODEL!,
tools
});
return await agent.invoke({
messages: [{ role: 'user', content: question }]
});
} finally {
await client.close();
}
}
Your application takes the user ID from its authenticated session and passes it to runAgentFor(). From there:
connectAs()creates an MCP client tied to that user.loadMcpTools()turns the server's tools into LangChain tools that call through that client.createAgent()hands the tools to the model.- When the run ends,
client.close()releases the connection, even if the agent threw an error.
The run needs the user's identity, not the user's access token:
- MCP request
- The client's
token()knows the user ID TokenServiceloads that user's token- Refreshes it if needed
- Request sent with that user's token
Nothing puts the access token in LangGraph state, the prompt, or a checkpoint.
What if two tool calls refresh at the same time?
The proof script made two requests at once. That matters because agents often call tools in parallel.
If two requests for the same user discover an expiring token at the same time, both might try to refresh it.
With refresh-token rotation, a successful refresh can invalidate the previous refresh token. A second refresh using that old value might fail, or trigger reuse detection that revokes the grant. Two requests shouldn't race to refresh the same user's token.
TokenService.refresh() prevents it. The refreshing map holds one pending refresh per user, and any request that needs a new token while one is running waits for that same promise:
- Request A
- Token expiring
- Start the refresh
- Save the new token
- Send with the new token
Request B- Token expiring
- Find the refresh already running
- Wait for it
- Send with the same new token
That's why our test issued one replacement token for the two concurrent requests.
The map only covers one Node.js process. If your application runs on several instances, two of them can still refresh the same user's token at once. In that case, take a lock in shared storage, such as a row lock in the database that holds the tokens, and read the token again after you get the lock. Another instance may have refreshed it while you waited.
What about state between tool calls?
Not every tool failure after a pause comes from an expired token.
Consider an MCP server with two tools: initialize_workspace creates a workspace, and search_workspace expects that workspace to exist when it runs later.
- initialize_workspace()
- Success
- later
- search_workspace()
- workspace not initialized
Authentication succeeds, but the server can't find the workspace state created by the earlier call.
Since the 2026-07-28 revision of the MCP specification, the protocol has no sessions. Every request stands on its own, so a server can't tie state to a connection.
Instead of depending on connection state, the server can return a workspace ID and require it on later calls:
- initialize_workspace()
- workspace_id: ws_123
- later, on any request
- search_workspace(workspace_id: "ws_123", query: ...)
- Results
The handle travels through the agent's tool calls like any other argument. It doesn't depend on how the client manages connections.
Older servers that speak an earlier protocol revision may still keep state in a session, identified by an Mcp-Session-Id header. The SDK's transport remembers that ID for as long as you use the same client. Create a new client, and you start a new session.
For an older, session-based server, runAgentFor() also keeps the same MCP client throughout a run. For newer stateless servers, later calls must pass whatever explicit handle the server returned.
Either way, the MCP client can remain open longer than one access token. token() resolves a current credential whenever it sends a request.
Which lifecycle broke?
When an agent resumes after a pause, check two separate things:
- Credential lifetime: is this request carrying a valid token?
- State lifetime: does the server still have what an earlier tool call created?
A valid token won't restore missing server state, and preserving server state won't fix an expired token. The error helps narrow down which one you're dealing with.
If a later call returns 401 Unauthorized, follow the credential. Don't assume every 401 means an expired token:
- Did the application get a new token? Check that
refreshGrantran andsave()stored the result. - Did
token()return it? Log the token's expiry, never the token itself. - Did the request carry it? Look for a fixed
Authorizationheader inrequestInit.
If authentication succeeds but the server can't find something an earlier call created, follow the state:
- Does the server return a handle the agent can pass back?
- If it's an older server that relies on sessions, did the run create a new client between the calls?
If the refresh token is no longer usable, ReauthorizationRequiredError reaches the application. It needs to ask the user to sign in again rather than retrying inside the agent.
Back to the approval that came too late
Return to the agent waiting for approval. Twenty minutes pass, and the access token expires. When the approval arrives, the MCP client calls token() before its next request. TokenService refreshes the expired token and returns the new one.
The agent makes the same tool call it would have made twenty minutes earlier. It doesn't need a new MCP client or any OAuth logic in its prompt.
The responsibilities stay separate:
| Component | Responsibility |
|---|---|
| LangGraph agent | Chooses tools |
TokenService | Stores, reuses, and refreshes each user's tokens |
AuthProvider | Hands the current token to each MCP request |
| MCP server | Carries state between tool calls in explicit handles |
Here's the request path after the change:
- The agent chooses an MCP tool
- The run's MCP client prepares the request
token()asks for this user's token- still valid
- Reuse it
expiring- Refresh it, once
- The request goes out with the current token
- The tool runs
An access token can expire while an agent is waiting, but the next MCP request can still use a fresh one. The application manages tokens, and the agent keeps working with tools.
For the broader authorization flow, see MCP Authorization: The Complete Developer Guide.
On this page
- Why does a token that worked earlier fail now?
- Why isn't refreshing the token enough?
- The MCP SDK asks for a token before every request
- What does the application's token layer do?
- Prove the new token reaches the MCP server
- Whose token is it?
- What if two tool calls refresh at the same time?
- What about state between tool calls?
- Which lifecycle broke?
- Back to the approval that came too late