Skip to main content
On this page

An MCP client can connect to a server, list its tools, and call them. But something still has to decide which tool to call, and with what arguments.

That's the job of an agent. It hands the tools to a model, and the model chooses.

When the MCP server is protected with OAuth, a new question comes up: where does the access token go? It shouldn't go anywhere near the model. In this article, we'll build a LangGraph agent in TypeScript that calls a protected MCP tool, and prove the model never sees the token.

How the pieces fit together​

Before the agent can use any tools, it needs an MCP client that's allowed to call the server.

In Connecting an AI Agent to an OAuth-Protected MCP Server, we built that client with the official MCP TypeScript SDK. Its heart is a function called connect(). It tries to connect, and when the server answers 401, it sends you to WSO2 Identity Platform to sign in, catches the browser on its way back, and connects again with an access token. We'll add the same function to this project.

On top of that client, we'll use two LangChain libraries:

  • @langchain/mcp-adapters: turns the tools an MCP server advertises into LangChain tools.
  • langchain: its createAgent() builds an agent on LangGraph that can select and call those tools.

Each layer has one job:

LayerResponsibility
connect()Gets authorization when needed and returns a connected MCP client
loadMcpTools()Lists the server's tools through that client and converts them into LangChain tools
createAgent()Gives the tools to a model, which decides when to call them

@langchain/mcp-adapters is built on the same @modelcontextprotocol/client package, and loadMcpTools() accepts an MCP Client we've connected ourselves. So OAuth happens once, in our own code, before the agent exists.

How the agent reaches a protected tool
  1. connect() returns an authorized MCP client
  2. loadMcpTools() lists and converts the tools
  3. createAgent() gives the tools to the model
  4. ModelChooses the add tool
  5. The MCP client sends the call with the access token

The model sees tool names, descriptions, arguments, and results. It never sees the access token.

What you need before you start​

We'll build a small Express MCP server with a single add tool, running at http://localhost:3000/mcp, and protect it with WSO2 Identity Platform. The server code is in this article. The authorization server setup happens in the WSO2 Identity Platform Console.

Before you continue, make sure you have:

  1. A WSO2 Identity Platform organization. Your organization's base URL looks like https://api.asgardeo.io/t/<organization>.
  2. An MCP client application in the WSO2 Identity Platform Console, created from the MCP Client Application template, with http://127.0.0.1:3030/callback as its authorized redirect URL and JWT as its access token type. See Register our MCP client.
  3. The MCP server registered as a resource with the identifier http://localhost:3000/mcp and the scope mcp:tools, the application authorized to use it, and a user with a role that grants the scope. See Configure access to the MCP resource.
  4. An API key for a model provider. We'll use OpenAI. You can create a key under API keys in the OpenAI Platform.

If any of these are new to you, Connecting an AI Agent to an OAuth-Protected MCP Server walks through each Console step. It also builds the server and the OAuth client code one piece at a time, and explains every line.

Set up the project​

We'll use Node.js 22 or newer.

  1. Create a project and install the dependencies:

    mkdir langgraph-mcp-agent
    cd langgraph-mcp-agent

    npm init -y
    npm pkg set type=module

    # The MCP client and the agent
    npm install --save-exact @modelcontextprotocol/[email protected] [email protected] @langchain/[email protected] @langchain/[email protected] @langchain/[email protected] @langchain/[email protected] [email protected]

    # The protected MCP server
    npm install --save-exact @modelcontextprotocol/[email protected] @modelcontextprotocol/[email protected] @modelcontextprotocol/[email protected] @asgardeo/[email protected] express zod@4

    npm install --save-dev typescript tsx @types/node @types/express

    Here's what the packages are for:

    • The first command installs the MCP client SDK and the LangChain libraries. @langchain/openai connects LangChain to OpenAI's models, and open opens the sign-in page in your browser.
    • The second installs the MCP server SDK, its Express integration, and @asgardeo/mcp-express, which validates WSO2 Identity Platform tokens.

    If you'd rather use another model provider, install its LangChain package instead of @langchain/openai, such as @langchain/anthropic.

  2. Create a tsconfig.json:

    {
    "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "types": ["node"],
    "strict": true,
    "skipLibCheck": true,
    "noEmit": true
    }
    }

    This tells your editor about Node.js, so it recognizes globals such as process.

  3. Create a .env file:

    BASE_URL=https://api.asgardeo.io/t/<organization>
    MCP_RESOURCE=http://localhost:3000/mcp
    MCP_SERVER_URL=http://localhost:3000/mcp
    MCP_CLIENT_ID=<your-public-client-id>
    MCP_SCOPE=mcp:tools
    OAUTH_ISSUER=https://api.asgardeo.io/t/<organization>/oauth2/token
    MODEL=openai:gpt-5-mini
    OPENAI_API_KEY=<your-openai-api-key>

    Replace <organization> with your organization name. If you followed the MCP client guide, the first six values are the same as in that project's .env.

    The server reads two values:

    • BASE_URL: your organization's base URL. The server loads WSO2 Identity Platform's signing keys from it.
    • MCP_RESOURCE: the server's resource identifier. It must match the identifier you registered under Resources > MCP Servers.

    The MCP client reads four:

    • MCP_SERVER_URL: where the client connects. Here it's the same URL as MCP_RESOURCE.
    • MCP_CLIENT_ID: the client ID from your MCP client application's Protocol tab.
    • MCP_SCOPE: the scope you created for the MCP server. Our server doesn't advertise one, so without this value the client requests none and the server rejects the token.
    • OAUTH_ISSUER: your organization's issuer. The client only hands its client ID to an authorization server with this exact issuer.

    The agent reads the last two:

    • MODEL: the model, in the provider:model format createAgent() understands.
    • OPENAI_API_KEY: your OpenAI API key, which @langchain/openai reads from the environment.

Keep the API key out of anything you commit or share.

Create the protected MCP server​

Our MCP server exposes one tool, add, and only runs it for requests that carry a valid WSO2 Identity Platform access token. It's the same server we built in Connecting an AI Agent to an OAuth-Protected MCP Server. If you already have it, start it from that project and skip to Add the OAuth client code.

  1. Create server.ts:

    server.ts
    import { McpAuthServer } from '@asgardeo/mcp-express';
    import { createMcpExpressApp } from '@modelcontextprotocol/express';
    import { toNodeHandler } from '@modelcontextprotocol/node';
    import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
    import * as z from 'zod/v4';

    const handler = createMcpHandler(() => {
    const server = new McpServer({
    name: 'test-server',
    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 app = createMcpExpressApp();
    const mcpHandler = toNodeHandler(handler);

    const baseUrl = process.env.BASE_URL!;
    const resource = process.env.MCP_RESOURCE!;

    const auth = new McpAuthServer({
    baseUrl,
    issuer: `${baseUrl}/oauth2/token`,
    resource,
    audience: resource,
    });

    // Publish the OAuth discovery metadata.
    app.use(auth.router());

    // Validate the access token before the MCP handler runs.
    app.all('/mcp', auth.protect(), (req, res) => {
    void mcpHandler(req, res, req.body);
    });

    app.listen(3000, 'localhost', error => {
    if (error) {
    throw error;
    }

    console.log('MCP server running at http://localhost:3000/mcp');
    });

    Here's what each part does:

    • createMcpHandler() builds a fresh McpServer for each request and registers the add tool, with its description and input schema.
    • McpAuthServer comes from @asgardeo/mcp-express. It needs your organization's baseUrl, the token issuer, the resource identifier it publishes, and the audience every token must carry. Without audience, it would accept any token your organization signed, even one meant for a different API.
    • auth.router() publishes the Protected Resource Metadata that tells clients which authorization server to use.
    • auth.protect() validates the access token on every request to /mcp before the MCP handler runs. A missing or invalid token gets 401.
    • The app.listen() callback checks error, because Express 5 passes startup errors, such as port 3000 already being in use, to the callback instead of throwing them.

    The MCP client guide builds this server in stages, if you want the longer explanation.

  2. Open a terminal in the project directory and start the server:

    node --env-file=.env --import tsx server.ts

    You should see:

    MCP server running at http://localhost:3000/mcp

    @asgardeo/mcp-express reads BASE_URL as soon as it loads, so always start the server with --env-file=.env.

  3. Leave this terminal running. We'll call it the server terminal.

  4. Open a second terminal in the same directory and check that the server rejects requests without a token:

    curl -i -X POST http://localhost:3000/mcp \
    -H 'Content-Type: application/json' \
    -d '{}'

    The response starts with:

    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: Bearer resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource"

    That 401 is what will start the sign-in when our client connects.

Add the OAuth client code​

The agent needs an MCP client that's already authorized. That takes three small files:

  1. oauth-provider.ts stores what the MCP SDK needs during sign-in, including the tokens.
  2. callback-server.ts catches the browser when it returns from the sign-in page.
  3. mcp-connection.ts uses both to return an authorized MCP client.

We'll go through them briefly. The MCP client guide explains each one in detail.

The OAuth provider​

The MCP SDK runs the OAuth protocol for us: discovery, PKCE, the token exchange, and attaching the token to requests. It calls back into a provider object whenever it needs to read or save something.

Create oauth-provider.ts:

oauth-provider.ts
import { randomUUID } from 'node:crypto';

import open from 'open';
import type {
OAuthClientProvider,
OAuthClientInformationContext,
OAuthDiscoveryState
} from '@modelcontextprotocol/client';

type Tokens = NonNullable<
Awaited<ReturnType<OAuthClientProvider['tokens']>>
>;

export class LocalOAuthProvider implements OAuthClientProvider {
readonly redirectUrl =
'http://127.0.0.1:3030/callback';

readonly clientMetadata = {
client_name: 'Example MCP Client',
redirect_uris: [this.redirectUrl],
application_type: 'native' as const,
scope: process.env.MCP_SCOPE
};

private storedTokens?: Tokens;
private verifier?: string;
private discovery?: OAuthDiscoveryState;

lastState?: string;

constructor(
private readonly clientId: string,
private readonly issuer: string
) {}

clientInformation(
context?: OAuthClientInformationContext
) {
if (context && context.issuer !== this.issuer) {
return undefined;
}

return {
client_id: this.clientId,
issuer: this.issuer
};
}

tokens() {
return this.storedTokens;
}

saveTokens(tokens: Tokens) {
this.storedTokens = tokens;
}

state() {
this.lastState = randomUUID();
return this.lastState;
}

saveCodeVerifier(value: string) {
this.verifier = value;
}

codeVerifier() {
if (!this.verifier) {
throw new Error('Missing PKCE verifier');
}

return this.verifier;
}

saveDiscoveryState(value: OAuthDiscoveryState) {
this.discovery = value;
}

discoveryState() {
return this.discovery;
}

async redirectToAuthorization(url: URL) {
if (url.protocol !== 'https:') {
throw new Error(
'Expected an HTTPS authorization URL'
);
}

console.log('\nOpening your browser to sign in. If nothing opens, visit:\n');
console.log(url.href);

// If no browser can be opened, the printed URL still works.
await open(url.href).catch(() => {});
}
}
  • clientMetadata describes our client, including the scope it requests.
  • clientInformation() returns our client ID, but only to the issuer we expect.
  • state(), saveCodeVerifier(), and saveDiscoveryState() hold the temporary values for one authorization attempt.
  • saveTokens() and tokens() keep the tokens in memory, so each run starts with a fresh sign-in.
  • redirectToAuthorization() opens the authorization URL in your browser, and prints it too, in case no browser can be opened.

The callback listener​

After you sign in, WSO2 Identity Platform sends the browser to http://127.0.0.1:3030/callback. Something has to be listening there.

Create callback-server.ts:

callback-server.ts
import { createServer, type ServerResponse } from 'node:http';

const TIMEOUT_MS = 5 * 60 * 1000;

// Wait for the authorization server to send the browser back to our redirect URL.
export function waitForCallback(
redirectUrl: string,
expectedState: string | undefined
): Promise<URLSearchParams> {
const redirect = new URL(redirectUrl);

return new Promise((resolve, reject) => {
const server = createServer((req, res) => {
const url = new URL(req.url ?? '/', redirect);

if (url.pathname !== redirect.pathname) {
res.writeHead(404).end();
return;
}

const params = url.searchParams;
const error = params.get('error');

if (error) {
finish(res, 400, 'Authorization failed. You can close this tab.');
reject(new Error(
`Authorization failed: ${params.get('error_description') ?? error}`
));
return;
}

if (!expectedState || params.get('state') !== expectedState) {
finish(res, 400, 'Invalid authorization response.');
reject(new Error('OAuth state mismatch'));
return;
}

if (!params.get('code')) {
finish(res, 400, 'Invalid authorization response.');
reject(new Error('Missing authorization code'));
return;
}

finish(res, 200, 'Authorization complete. You can close this tab.');
resolve(params);
});

// Give up if the user never finishes signing in.
const timeout = setTimeout(() => {
server.close();
reject(new Error('Timed out waiting for authorization'));
}, TIMEOUT_MS);

function finish(res: ServerResponse, status: number, message: string) {
res.writeHead(status, { 'Content-Type': 'text/plain' }).end(message);
clearTimeout(timeout);
server.close();
}

// For example, another program is already using the port.
server.on('error', error => {
clearTimeout(timeout);
reject(error);
});

server.listen(Number(redirect.port), redirect.hostname);
});
}

waitForCallback() accepts one request on the callback path. It rejects the response if the authorization server reported an error, if the state doesn't match, or if there's no code. Then it shuts down. It also gives up after five minutes, and fails straight away if the port is taken.

The connection​

The last file ties them together. connect() tries to connect, and if the server answers 401, it runs the browser sign-in and connects again with the token.

Create mcp-connection.ts:

mcp-connection.ts
import {
Client,
StreamableHTTPClientTransport,
UnauthorizedError
} from '@modelcontextprotocol/client';

import { waitForCallback } from './callback-server.js';
import { LocalOAuthProvider } from './oauth-provider.js';

const serverUrl = new URL(
process.env.MCP_SERVER_URL!
);

export const provider = new LocalOAuthProvider(
process.env.MCP_CLIENT_ID!,
process.env.OAUTH_ISSUER!
);

function createClient() {
return new Client(
{
name: 'example-client',
version: '1.0.0'
},
{
versionNegotiation: {
mode: 'auto'
}
}
);
}

function createTransport() {
return new StreamableHTTPClientTransport(
serverUrl,
{ authProvider: provider }
);
}

function isAuthenticationRequired(error: unknown) {
return (
error instanceof UnauthorizedError ||
(
error instanceof Error &&
'code' in error &&
error.code === 'CLIENT_HTTP_AUTHENTICATION'
)
);
}

export async function connect() {
const client = createClient();
const transport = createTransport();

// 1. Try to connect. Without a token, the server answers 401.
try {
await client.connect(transport);
return client;
} catch (error) {
if (!isAuthenticationRequired(error)) {
throw error;
}
}

// 2. The provider has opened the authorization URL. Wait for the user.
console.log('\nWaiting for you to sign in...');

const params = await waitForCallback(
provider.redirectUrl,
provider.lastState
);

// 3. Exchange the authorization code for tokens.
await transport.finishAuth(params);
await client.close();

// 4. Reconnect. The new transport sends the access token.
const authorizedClient = createClient();
await authorizedClient.connect(createTransport());

return authorizedClient;
}

The four numbered comments are the whole flow:

  1. The first connection fails with an authentication error. By then, the SDK has discovered the authorization server and the provider has opened the authorization URL in your browser.
  2. We wait for the browser to come back.
  3. finishAuth() exchanges the code for tokens and saves them through the provider.
  4. A new client connects, and this time the SDK attaches the access token.

The SDK reports "authentication required" either as an UnauthorizedError or as an error with the code CLIENT_HTTP_AUTHENTICATION, so isAuthenticationRequired() checks for both.

We export connect() for the agent, and provider so we can inspect its token later.

Build the agent​

We'll build agent.ts in two steps. First, we'll load the server's tools and check that OAuth works. Then we'll hand those tools to a model.

Load the MCP tools​

  1. Create agent.ts and add:

    agent.ts
    import { loadMcpTools } from '@langchain/mcp-adapters';

    import { connect } from './mcp-connection.js';

    async function main() {
    const client = await connect();

    try {
    const tools = await loadMcpTools('example', client);

    console.log(
    'Loaded MCP tools:',
    tools.map(tool => tool.name)
    );
    } finally {
    await client.close();
    }
    }

    main().catch(error => {
    console.error('Agent failed:', error);
    process.exitCode = 1;
    });

    Here's what it does:

    • connect() returns an authorized MCP client. If there's no token yet, it runs the browser sign-in first.
    • loadMcpTools('example', client) asks the server for its tools through that client and converts each one into a LangChain tool, keeping its name, description, and input schema. The first argument is a name for the server. The library uses it in error messages, and can add it as a prefix to tool names when you connect several servers.
    • The finally block closes the MCP connection when we're done.
  2. Make sure the server is still running in the server terminal.

  3. In the second terminal, run:

    node --env-file=.env --import tsx agent.ts

    The client tries to connect, gets the 401, and opens the WSO2 Identity Platform sign-in page in your browser. It also prints the URL:

    Opening your browser to sign in. If nothing opens, visit:

    https://api.asgardeo.io/t/<organization>/oauth2/authorize?response_type=code&client_id=...

    Waiting for you to sign in...

    The terminal stops here. That's expected: the client is waiting for the browser to come back to http://127.0.0.1:3030/callback, and it waits up to five minutes.

  4. If the browser doesn't open, open the printed URL yourself. In most terminals, you can Cmd-click or Ctrl-click it.

  5. Sign in as the user you assigned the mcp:tools role to, and approve the consent screen if WSO2 Identity Platform shows one.

    The browser lands on the callback and shows:

    Authorization complete. You can close this tab.

Back in the terminal, the client exchanges the code for a token, reconnects, and loads the tools:

Loaded MCP tools: [ 'add' ]

There's no model involved yet. But we've proved the hard part: the client signed in, got a token the server accepts, and turned the server's tools into LangChain tools.

Hand the tools to a model​

Now let's give those tools to an agent.

  1. At the top of agent.ts, add:

    import { createAgent } from 'langchain';
  2. Inside the try block, after the console.log() that prints the tool names, add:

    const agent = createAgent({
    model: process.env.MODEL!,
    tools
    });

    const result = await agent.invoke({
    messages: [
    {
    role: 'user',
    content: 'Use the available tool to add 52 and 19.'
    }
    ]
    });

    console.log(result.messages.at(-1)?.content);

    Here's what the new code does:

    • createAgent({ model, tools }) builds a LangGraph agent. model is the MODEL value from .env, and tools are the LangChain tools we just loaded. The model reads their names and descriptions to decide whether to call one.
    • agent.invoke() runs the agent with one user message. When the model decides to call add, the converted tool sends the call through our MCP client, with the access token attached, and the result goes back to the model.
    • result.messages holds the whole conversation. Its last entry, result.messages.at(-1), is the model's final answer.

Your agent.ts should now look like this:

agent.ts
import { loadMcpTools } from '@langchain/mcp-adapters';
import { createAgent } from 'langchain';

import { connect } from './mcp-connection.js';

async function main() {
const client = await connect();

try {
const tools = await loadMcpTools('example', client);

console.log(
'Loaded MCP tools:',
tools.map(tool => tool.name)
);

const agent = createAgent({
model: process.env.MODEL!,
tools
});

const result = await agent.invoke({
messages: [
{
role: 'user',
content: 'Use the available tool to add 52 and 19.'
}
]
});

console.log(result.messages.at(-1)?.content);
} finally {
await client.close();
}
}

main().catch(error => {
console.error('Agent failed:', error);
process.exitCode = 1;
});

Why doesn't the agent need its own OAuth setup?​

You might expect the agent library to take an OAuth configuration of its own. @langchain/mcp-adapters can: its connection settings accept an authProvider, the same interface our LocalOAuthProvider implements.

But the transport can't finish the sign-in on its own. Something still has to catch the browser on its way back and call finishAuth(). Our connect() handles the 401, the browser round trip, and the reconnect. Handing loadMcpTools() a client that's already authorized keeps all of that in one place, and keeps the agent code about agents.

Run the agent​

  1. Make sure the server is still running in the server terminal.

  2. In the second terminal, run the agent again:

    node --env-file=.env --import tsx agent.ts
  3. Sign in when your browser opens. Tokens live in memory, so each run asks again.

This time, the agent takes over after the tools load:

Loaded MCP tools: [ 'add' ]
52 + 19 = 71.

The wording of the last line depends on the model. The number shouldn't.

Behind that one line, the model chose the add tool, filled in a and b, and our MCP client sent the call to the protected server with the access token attached. The server checked the token's signature, issuer, and audience before running the tool. Every tool call in the run reuses that same authorized connection.

Prove the model never sees the token​

We've said the token stays out of the agent. Let's check.

The check needs two things: the access token, and everything the model saw.

The access token lives in provider, the LocalOAuthProvider we created in mcp-connection.ts. After you sign in, the MCP SDK saves the tokens through its saveTokens() method, and reads them back with tokens() whenever it sends a request. So the provider is the one place in our code that holds the token.

Everything the model saw is in result.messages, the conversation the agent returns.

If the token never appears in that conversation, the model never saw it.

  1. In agent.ts, import the provider alongside connect():

    import { connect, provider } from './mcp-connection.js';
  2. After the line that prints the final answer, add:

    const accessToken = provider.tokens()?.access_token;

    console.log(
    'Token in agent messages:',
    accessToken !== undefined &&
    JSON.stringify(result.messages).includes(accessToken)
    );

    Here's what the check does:

    • provider.tokens()?.access_token asks the provider for the tokens the SDK saved and picks out the access token.
    • JSON.stringify(result.messages) turns the whole conversation into one string: your prompt, the model's tool call, the tool's result, and the final answer.
    • .includes(accessToken) searches that string for the token.
    • accessToken !== undefined && makes sure we actually have a token to search for. Without it, a missing token would be searched for as the text undefined.

    The line prints true if the token appears anywhere in the conversation, and false if it doesn't.

  3. With the MCP server still running, run the agent again and sign in when your browser opens. The last line should read:

    Token in agent messages: false

There it is. The token lives in the provider and travels in the Authorization header. It never enters the conversation.

Remove the check from agent.ts when you're done.

Keep credentials out of agent state​

That separation is worth protecting as the application grows.

LangGraph can save an agent's state in checkpoints, so conversations and interrupted runs can continue later. Anything in messages ends up in those checkpoints, in your traces, and possibly in your logs.

So the rule is simple: tokens, refresh tokens, callback parameters, and client secrets never go into a prompt, a tool result, or agent state. They stay with the OAuth provider and its storage.

A hosted service adds one more concern: user isolation.

Our provider is a single object holding one person's token. That's fine for a local tool you run yourself. A shared agent service must not reuse one MCP client, or one token store, for everyone.

For each request, the application should:

  1. Identify the signed-in user.
  2. Select that user's credentials for the intended MCP server.
  3. Connect an MCP client with those credentials.

Test it with two users to confirm that one user's authorization can't be reused by the other.

What changes when the agent is hosted?​

Our waitForCallback() listens on 127.0.0.1 on the machine running the agent. That works because you're sitting at that machine.

A LangGraph service running in the cloud has no browser to open and no user at the keyboard. When it needs authorization, it has to:

  1. Send the authorization URL to the right user, through the application's own frontend.
  2. Receive the callback at an HTTPS endpoint.
  3. Store the tokens against that user.
  4. Continue the pending work.

LangGraph has an interrupt-and-resume model that can pause a run. It won't wire up OAuth for you, though. You decide how the pause links to the user, the run, and the callback, and what happens if the user never comes back.

Also keep OAuth consent apart from approving an individual tool call. A user can authorize your application to manage their calendar and still want to approve each cancellation. LangGraph's human-in-the-loop features help with the second. They don't replace the first.

WorkflowResponsible layer
Obtain or renew permission to access an MCP serverApplication's OAuth integration (connect() and the provider)
Discover and call MCP toolsMCP client and loadMcpTools()
Decide which tool to useLangGraph agent
Ask a human to approve a sensitive tool callApplication's agent execution policy

Test the integration boundaries​

Once the example runs, test what happens when its assumptions stop holding.

TestExpected behavior
A new user connects without stored authorizationThe application gets that user's authorization before loading protected tools.
A token expiresThe client refreshes it if it has a refresh token; otherwise the application asks the user to sign in again.
A tool requires a scope the user didn't grantThe application reports insufficient authorization and returns control to the user. The model can't grant itself permissions.
The MCP server is unavailable during a tool callThe failure is treated as a network problem, not an authorization problem, with no unbounded retries.
Two users run agents in the same processEach uses their own credentials, with no cross-user token reuse.
A run is checkpointedThe checkpoint contains conversation state, not tokens.
A tool requires approval before a destructive actionThe approval policy applies even though OAuth authorization already exists.

The agent layer doesn't replace server-side checks. Keep testing audience validation and resource indicators at the MCP server, as in the MCP client guide's verification sections.

Where to go next​

Our agent started with a client that had already solved OAuth. loadMcpTools() turned the server's tools into something a model can call, and createAgent() let the model choose.

OAuth happened once, before the agent existed. The model chose the tool, and the token stayed in the Authorization header, where it belongs.

That holds for a short run. A long one is different: the access token can expire while the agent is still working. Why Your MCP Token Expires Mid-Run looks at what breaks when that happens and how to design around it.