Connecting an AI Agent to an OAuth-Protected MCP Server
Himesh Siriwardana·38 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
- The problem the tutorials skip
- Why static headers are not enough
- The authProvider parameter that connects the pieces
- Delegating to the MCP SDK's OAuth provider
- How does the authorization server know our client?
- Consent inside an agent run
- Where do the tokens live?
- Putting the client together
- Verifying the resource indicator
- What breaks in production
- Taking this into an agent application
Connecting an AI agent to a public MCP server is fairly straightforward. We give the client a server URL, retrieve the available tools, and make them available to the agent.
But what happens when the server needs the user's permission before allowing access?
Imagine we're building an AI assistant that can search documents in a user's workspace. The MCP server exposes a search_documents tool, but those documents aren't public. The user needs to sign in and authorize our application before it can search them.
We could obtain an access token ourselves and attach it to every request. That might get us through the first call. But what happens when the token expires, another user connects, or the server needs additional permissions?
Our application needs to manage authorization, not just attach a token.
In this article, we'll build a TypeScript MCP client, see what happens when a server requires authentication, and connect to an OAuth-protected MCP server using the official MCP SDK.
We'll start with a small test server that doesn't require an identity provider. Once the basic connection works, we'll introduce OAuth discovery, registration, PKCE, browser consent, and token management.
We covered the underlying protocol in MCP Authorization: The Complete Developer Guide. Here, we'll focus on what happens inside the client.
The problem the tutorials skip
Most introductory MCP examples start with a server that doesn't require authentication.
The client connects, discovers some tools, and calls one. There's no user sign-in or authorization flow to worry about.
Let's start there too, so we have something working before introducing OAuth.
Create a simple MCP client
We'll use the official MCP TypeScript SDK v2.4.0 and Node.js 22 or newer.
-
Create a project and install the client SDK:
mkdir oauth-mcp-client
cd oauth-mcp-client
npm init -y
npm pkg set type=module
npm install --save-exact @modelcontextprotocol/[email protected]
npm install --save-dev typescript tsx @types/nodeThe v2 SDK separates the client and server packages. If you've seen examples importing from
@modelcontextprotocol/sdk/client, those use the older v1 package. -
Create a
tsconfig.jsonin the project directory:{
"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. -
Create
client.ts:import {
Client,
StreamableHTTPClientTransport
} from '@modelcontextprotocol/client';
const client = new Client({
name: 'example-client',
version: '1.0.0'
});
const transport = new StreamableHTTPClientTransport(
new URL('http://localhost:3000/mcp')
);
try {
await client.connect(transport);
const { tools } = await client.listTools();
console.log(tools.map(tool => tool.name));
} finally {
await client.close();
}
This client connects to an MCP server over Streamable HTTP, retrieves the available tools, and prints their names.
The only thing we're missing is a server to connect to.
Testing without an existing MCP server
We need an MCP server to test our client against. Rather than configuring an existing server, let's create a small one ourselves.
Our server will expose a single tool called add. It accepts two numbers and returns their sum. We won't need authentication for this first example.
-
Install the MCP server SDK, the Express integration, and Zod:
npm install --save-exact \
@modelcontextprotocol/[email protected] \
@modelcontextprotocol/[email protected] \
@modelcontextprotocol/[email protected] \
express \
zod@4
npm install --save-dev @types/expressWe need three MCP packages here:
@modelcontextprotocol/serverimplements the MCP functionality.@modelcontextprotocol/expressprovides the Express integration.@modelcontextprotocol/nodeconnects the MCP handler to Node.js HTTP requests.
@types/expressgives your editor the types for Express'sreqandres. -
Create a file named
server.ts: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);
app.all('/mcp', (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'
);
}); -
Start the server:
npx tsx server.tsYou should see:
MCP server running at http://localhost:3000/mcpLeave this terminal running.
Here's what each part of server.ts does:
McpServerregisters ouraddtool, with its description, input schema, and implementation. When the client callsadd, the server receives two numbers and returns their sum.createMcpHandler()handles MCP requests. It creates a fresh server instance for each request, so we don't need to maintain MCP sessions. This follows the stateless model supported by the July 2026 MCP specification.createMcpExpressApp()creates an Express application with JSON body parsing and localhost DNS rebinding protection already set up.toNodeHandler()connects Express's/mcproute to the MCP handler.- The
app.listen()callback checkserror. Express 5 passes startup errors, such as port 3000 already being in use, to this callback instead of throwing them. Without the check, the server prints a success line and exits.
Connect our client
Now let's return to the client.ts we created earlier.
We'll make one change to enable automatic protocol version negotiation. This allows the client to use the newer MCP protocol when supported while remaining compatible with older servers.
-
Replace the contents of
client.tswith:import {
Client,
StreamableHTTPClientTransport
} from '@modelcontextprotocol/client';
const client = new Client(
{
name: 'example-client',
version: '1.0.0'
},
{
versionNegotiation: {
mode: 'auto'
}
}
);
const transport = new StreamableHTTPClientTransport(
new URL('http://localhost:3000/mcp')
);
try {
await client.connect(transport);
const { tools } = await client.listTools();
console.log(tools.map(tool => tool.name));
} finally {
await client.close();
}The
StreamableHTTPClientTransporthandles communication with our HTTP endpoint. Once connected,listTools()retrieves the tools advertised by the server. -
Open another terminal in the same project directory and run:
npx tsx client.ts
The client should retrieve our add tool:
[ 'add' ]
Call the tool
We've confirmed that the client can discover the tool. Now let's invoke it.
-
Add the following code immediately after the
console.log()statement, before thefinallyblock:const result = await client.callTool({
name: 'add',
arguments: {
a: 5,
b: 10
}
});
console.log(result.content);The client sends the tool name and arguments to the MCP server. The server executes the tool and returns the result.
-
Run the client again:
npx tsx client.ts
We should see output similar to:
[ 'add' ]
[ { type: 'text', text: '15' } ]
Our client has connected to an MCP server, discovered its available tools, and invoked one.
We haven't used an AI model or agent framework yet. Those can sit above this client and decide which tools to call. The MCP client remains responsible for communicating with the server.
For now, we have a working connection we can experiment with. Next, let's see what happens when the server requires authentication.
Why static headers are not enough
Our MCP client currently connects to the server without authentication. That's fine for the add tool, but imagine the server exposes tools that access private documents.
Let's modify our local server to require an access token and see how the client behaves.
Require an access token
We're going to add an Express middleware that checks for an access token before passing the request to the MCP handler.
-
Open the
server.tsfile we created earlier. -
Find this code near the bottom:
const app = createMcpExpressApp();
const mcpHandler = toNodeHandler(handler);
app.all('/mcp', (req, res) => {
void mcpHandler(req, res, req.body);
}); -
Replace that block with:
const app = createMcpExpressApp();
const mcpHandler = toNodeHandler(handler);
// Check the access token before processing MCP requests.
app.use('/mcp', (req, res, next) => {
const authorization = req.headers.authorization;
if (authorization !== 'Bearer demo-token') {
res.setHeader('WWW-Authenticate', 'Bearer');
res.status(401).send('Unauthorized');
return;
}
next();
});
app.all('/mcp', (req, res) => {
void mcpHandler(req, res, req.body);
});Leave the rest of
server.tsunchanged.
The middleware checks the Authorization header on every request to /mcp. If the token is missing or doesn't match demo-token, the server returns 401 Unauthorized.
If the token matches, Express passes the request to the MCP handler.
We're using a hardcoded token only for this experiment. This isn't real OAuth token validation, and we shouldn't use this approach in a production server.
Test the protected server
-
Stop the running server by pressing
Ctrl+Cin its terminal. -
Restart it:
npx tsx server.ts -
Open another terminal in the project directory and run our existing client:
npx tsx client.tsThe connection should fail with an authorization error. Our client is still connecting without credentials, but the server now requires an access token.
-
Inspect the response directly using
curl:curl -i -X POST http://localhost:3000/mcp \
-H 'Content-Type: application/json' \
-d '{}'The server should return an HTTP response beginning with:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer
The request body isn't a valid MCP message, but that doesn't matter for this test. Our authentication middleware rejects the request before the MCP handler processes it.
We've now confirmed that the server requires authentication.
Supply a token from the client
Let's update the client to send the token our test server expects.
-
Open
client.ts. -
Find the transport initialization:
const transport = new StreamableHTTPClientTransport(
new URL('http://localhost:3000/mcp')
); -
Replace it with:
const transport = new StreamableHTTPClientTransport(
new URL('http://localhost:3000/mcp'),
{
requestInit: {
headers: {
Authorization: 'Bearer demo-token'
}
}
}
);We're using
requestInitto supply an HTTP header that the transport includes when making requests to the MCP server. -
Save
client.tsand run it again:npx tsx client.ts
This time, the connection should succeed, and you should see the tool list and the result again:
[ 'add' ]
[ { type: 'text', text: '15' } ]
The client sends demo-token, the server accepts it, and the MCP handler processes the requests.
We've successfully made an authenticated MCP connection.
What happens if the token is wrong?
Let's try one more test.
-
In
client.ts, change the authorization header to:Authorization: 'Bearer wrong-token' -
Save the file and run the client again:
npx tsx client.tsThe connection should fail with an authorization error. The server doesn't accept the supplied token, so it refuses to process the MCP request.
-
Restore the original value if you want to repeat the successful test:
Authorization: 'Bearer demo-token'
Why can't we keep using this approach?
For our local example, supplying a static token works.
But consider an application that connects to a document server on behalf of different users. Three problems show up:
- The user still needs to authorize access. Someone must obtain the access token from an authorization server, and a hardcoded header doesn't explain how that happens.
- Access tokens expire. Our application needs to refresh credentials when permitted, or ask the user to authorize again.
- Different users need different credentials. If Alice and Bob use the same application, we can't send Alice's access token when Bob calls a tool.
There's nothing wrong with supplying a token when another component already manages authorization. But when our application needs to establish authorization itself, a static header isn't enough.
We need the client to discover the authorization server, let the user sign in, obtain credentials, and manage those credentials for subsequent requests.
That's what we'll implement next.
Keep this server.ts. We'll soon replace its hardcoded token check with real OAuth token validation, and it will start publishing the metadata clients need to find the authorization server.
The authProvider parameter that connects the pieces
The official MCP TypeScript SDK lets us supply an OAuthClientProvider to the HTTP transport instead of manually managing the authorization header.
For example:
const transport = new StreamableHTTPClientTransport(
serverUrl,
{
authProvider: provider
}
);
This is an illustration of the integration we'll build later, not code to add to client.ts yet. We haven't created serverUrl or provider in our application.
When we implement OAuth, we'll create an oauth-provider.ts file containing the provider and update client.ts to use it.
The provider supplies application-specific behavior, including credential storage and the browser authorization handoff. The SDK handles the OAuth protocol operations.
Our current server won't work with this flow because it only checks for the hardcoded demo-token. Before using authProvider, we'll configure a real OAuth-protected MCP endpoint.
Delegating to the MCP SDK's OAuth provider
The MCP SDK already handles much of the OAuth flow.
It can:
- discover the authorization server's metadata;
- build authorization requests that use PKCE;
- support the MCP client registration mechanisms;
- exchange authorization codes for tokens;
- refresh tokens when a refresh token is available.
Our application needs to provide the information and interactions that are specific to its environment.
For example, the OAuthClientProvider interface defines methods for retrieving client information, storing tokens, saving PKCE values, and directing users to the authorization page.
We'll implement these methods in oauth-provider.ts after configuring our authorization server.
There's no code to change in our project at this stage. First, let's examine how OAuth discovery works so we know what our protected MCP server needs to expose.
Discover the authorization server
A protected MCP server publishes Protected Resource Metadata. When a client receives 401 Unauthorized, it uses that metadata to find the authorization server responsible for issuing access tokens. Our server doesn't publish it yet. We'll add it shortly.
The next discovery document comes from the authorization server itself. It describes where the client should send the user to authorize access and where it can exchange an authorization code for tokens.
We shouldn't implement these endpoints in server.ts. Our Express application is the MCP protected resource, not the OAuth authorization server.
For the rest of this tutorial, we'll use WSO2 Identity Platform to handle user authentication, consent, and token issuance. We'll also use its MCP authorization SDK to secure our existing Express server.
Configure WSO2 Identity Platform
- Sign in to your WSO2 Identity Platform organization. If you don't have one yet, create one. You'll need its Console to register an OAuth application and configure API authorization.
- Note your organization's base URL. It has this format:
https://api.asgardeo.io/t/<organization>
Our Express server will continue exposing the add tool at:
http://localhost:3000/mcp
That URL is our MCP resource identifier. The server will only accept access tokens issued for it.
We use localhost here, not 127.0.0.1. The client sends the resource identifier to WSO2 Identity Platform in the resource parameter, and its firewall blocks authorization requests whose resource contains a raw IP address such as 127.0.0.1: you'd get a 403 page instead of the sign-in screen. The redirect URL isn't affected, so it can stay http://127.0.0.1:3030/callback.
For this local experiment, we're using a loopback HTTP endpoint. A remotely accessible MCP server should use HTTPS.
Add the server configuration
-
Return to the project directory containing
server.tsandclient.ts. -
Create a
.envfile there with your organization's base URL and the MCP resource identifier:BASE_URL=https://api.asgardeo.io/t/<organization>
MCP_RESOURCE=http://localhost:3000/mcp -
Replace
<organization>with your organization name.
The server reads both values at startup. We'll add the client's values to the same file later.
Install the WSO2 MCP authorization SDK
-
Stop the MCP server if it's still running.
-
Install the WSO2 MCP Express SDK:
npm install @asgardeo/[email protected]
The package provides Express middleware for MCP authorization: token validation, and the metadata routes clients use for discovery.
It reads BASE_URL from the environment as soon as it's imported, and stops with BASE_URL is missing if the value isn't set. That's why we created .env first.
Update the Express MCP server
-
Open
server.ts. Keep thecreateMcpHandler()implementation and the registeredaddtool unchanged. -
At the top of the file, add:
import { McpAuthServer } from '@asgardeo/mcp-express'; -
Find the block at the bottom of the file where we created the Express application and added the
demo-tokenmiddleware, and replace that whole block with: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');
});
The demo-token middleware is gone. auth.router() publishes the discovery metadata, and auth.protect() validates tokens.
Each option has a specific job:
baseUrl: your organization's base URL. The SDK loads the signing keys from{baseUrl}/oauth2/jwks.issuer: the value WSO2 Identity Platform puts in the token'sissclaim. For an organization, that's its token endpoint URL.resource: the resource identifier the server publishes in its Protected Resource Metadata.audience: theaudvalue a token must carry. Without it, the SDK accepts any token your organization signed, including one issued for a different API.
We haven't changed the MCP handler or the tool. Express still forwards authorized requests to the same handler.
The difference is that every request to /mcp now passes through auth.protect() first.
Start the server
Start the server with the environment loaded:
node --env-file=.env --import tsx server.ts
You should see:
MCP server running at http://localhost:3000/mcp
Leave this terminal running.
Test the authorization challenge
-
Open another terminal in the same project directory.
-
Send a request without an access token:
curl -i -X POST http://localhost:3000/mcp \
-H 'Content-Type: application/json' \
-d '{}'The server rejects it with
401 Unauthorizedand an OAuth bearer challenge:HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource" -
The
resource_metadatavalue is where a client goes next. Request it:curl http://localhost:3000/.well-known/oauth-protected-resourceThe response identifies our MCP resource and the authorization server that issues tokens for it:
{
"resource": "http://localhost:3000/mcp",
"authorization_servers": ["https://api.asgardeo.io/t/<organization>/oauth2/token"],
"bearer_methods_supported": ["header"]
} -
Check that
resourcematchesMCP_RESOURCEexactly. The resource identifier must stay the same throughout authorization and token validation.
Inspect the authorization server metadata
The Protected Resource Metadata named one authorization server:
https://api.asgardeo.io/t/<organization>/oauth2/token
That value is the authorization server's issuer identifier. A client uses it to find the authorization server's own metadata, defined in RFC 8414.
The metadata URL is built by inserting /.well-known/oauth-authorization-server between the host and the issuer's path:
https://api.asgardeo.io/.well-known/oauth-authorization-server/t/<organization>/oauth2/token
Request it, replacing <organization> with your organization name:
curl https://api.asgardeo.io/.well-known/oauth-authorization-server/t/<organization>/oauth2/token
The response is a long JSON document. These are the fields an MCP client relies on:
{
"issuer": "https://api.asgardeo.io/t/<organization>/oauth2/token",
"authorization_endpoint": "https://api.asgardeo.io/t/<organization>/oauth2/authorize",
"token_endpoint": "https://api.asgardeo.io/t/<organization>/oauth2/token",
"jwks_uri": "https://api.asgardeo.io/t/<organization>/oauth2/jwks",
"code_challenge_methods_supported": ["S256", "plain"]
}
Check three things:
issuermatches the value inauthorization_serversexactly. A client rejects metadata whose issuer doesn't match.code_challenge_methods_supportedincludesS256. MCP clients refuse to start authorization without it, because they can't confirm PKCE support.authorization_endpointandtoken_endpointare present. That's where the client will send the user and exchange the authorization code.
You may notice that our MCP server also answers at http://localhost:3000/.well-known/oauth-authorization-server. The WSO2 SDK serves that short copy for older MCP clients. Current clients follow the issuer to WSO2 Identity Platform, as we just did, so always check the metadata there.
We've now connected the discovery process to a real authorization server.
Our MCP server advertises its protected resource information, while WSO2 Identity Platform publishes the authorization configuration.
We haven't implemented any OAuth endpoints ourselves.
How does the authorization server know our client?
Finding the authorization server is only part of the flow. The authorization server also needs to identify the application requesting access.
That's what OAuth client registration is for.
MCP supports three ways for a client to identify itself:
- Preregistration: the application receives a client ID before beginning authorization.
- Client ID Metadata Documents: the client identifies itself through an HTTPS URL hosting its metadata.
- Dynamic Client Registration: the client registers programmatically, when the authorization server supports it.
For our example, we'll preregister the client with WSO2 Identity Platform. We already know which authorization server we're using, so there's no need to introduce dynamic registration into the first working flow.
Register our MCP client
WSO2 Identity Platform has an application template made for MCP clients. In the Console:
- Go to Applications > New Application.
- Select MCP Client Application.
- Fill in the wizard:
- Name: any name you'll recognize, such as
Local MCP Client. - Authorized redirect URL:
http://127.0.0.1:3030/callback. - Public client: leave it enabled.
- Name: any name you'll recognize, such as
- Click Create.
- Open the application's Protocol tab and copy its Client ID.
- On the same tab, under Access Token, check that the token type is JWT. Our server validates tokens itself using WSO2 Identity Platform's signing keys, so it can't accept opaque tokens.
The redirect URL is where WSO2 Identity Platform sends the authorization code after the user signs in. Our TypeScript client will listen on exactly that URL, so the hostname, port, and path must match.
The client runs on your machine and can't keep a secret, so it's a public client. Instead of a client secret, it proves the token request came from the same client that started authorization, using PKCE.
The Setting up MCP Clients guide covers this template in more detail.
Configure access to the MCP resource
The client can now start authorization, but it can't request access to anything yet. WSO2 Identity Platform needs to know about our MCP server, which scope it accepts, and who may use it.
For this tutorial, we'll use a scope named mcp:tools. It's an example scope, not one defined by the MCP specification.
Register the MCP server
- Go to Resources > MCP Servers and click + New MCP Server.
- Enter:
- Identifier:
http://localhost:3000/mcp - Display Name: any name, such as
Local Add Server.
- Identifier:
- Click Next.
- In the Scopes step, add
mcp:toolswith a display name and description, then click Add Scope. The display name and description appear on the consent page. - Click Create.
The identifier must match MCP_RESOURCE in .env exactly. WSO2 Identity Platform puts it in the token's aud claim, and our server only accepts tokens whose aud matches.
Authorize the client to use it
- Go to Applications and open the client you created.
- Open the Authorization tab and click Authorize a resource.
- Select the MCP server as the Resource, and select
mcp:toolsunder Authorized Scopes. - Click Finish.
Give your user a role
Authorizing the application isn't enough on its own. The signed-in user also needs a role that grants the scope.
- Go to User Management > Roles and click New Role.
- Enter a role name, choose Application as the audience, and select your MCP client application.
- Click Next, select the MCP server, and grant the
mcp:toolspermission. - Click Finish.
- Open the new role's Users tab, click Assign User, select the user you'll sign in as, and click Update.
The Securing MCP Servers and Manage roles guides cover these screens in more detail.
Add the client configuration
-
Return to the project directory.
-
Open
.envand add:MCP_CLIENT_ID=<your-public-client-id>
MCP_SERVER_URL=http://localhost:3000/mcp
MCP_SCOPE=mcp:tools -
Keep the existing
BASE_URLandMCP_RESOURCEvalues.
We now have the values needed for our client to identify the MCP server and its OAuth registration.
Consent inside an agent run
We're ready to add OAuth to our client.
But there's an important difference between calling a tool and authorizing access to it.
Our application can make an MCP request automatically. It can't automatically grant the user's consent.
When authorization is required, it needs to send the user to the authorization server.
For this tutorial, we'll complete authorization before an agent begins calling tools.
The flow will look like this:
- Application connects to the MCP server
- 401 Unauthorized
- SDK discovers the authorization server
- Application presents the authorization URL
- UserSigns in and authorizes access
- Application receives the callback
- SDK exchanges the authorization code
- Client reconnects with credentials
We'll implement this interaction in a local TypeScript application.
Once the client can authorize successfully, an agent framework can use the same connection.
If authorization becomes necessary halfway through an agent run, the application needs to pause the affected operation and resume it after consent. We'll come back to that at the end.
Where do the tokens live?
Our application also needs somewhere to store OAuth credentials.
The MCP TypeScript SDK defines an OAuthClientProvider interface for supplying client registration information, temporary authorization state, and tokens.
The SDK handles the protocol operations. Our provider determines how application-specific information is retained and how authorization is presented to the user.
We'll start by keeping the credentials in memory.
That means closing the program discards them, and every run starts with a fresh sign-in. Persistent, per-user storage is a production concern, and we'll come back to it at the end.
Create the OAuth provider
The provider is a class the SDK calls back into during the OAuth flow. We never call these methods ourselves. Whenever the SDK needs to read or save something, such as the client ID, a token, or the PKCE verifier, it calls the matching method on our provider.
-
Install the
openpackage, which opens a URL in the default browser on macOS, Windows, and Linux:npm install --save-exact [email protected] -
In the project directory, create
oauth-provider.tsand add the code below.
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(() => {});
}
}
Here's what each part does, in the order the SDK uses them.
Who the client is
redirectUrl: where WSO2 Identity Platform sends the browser after sign-in. It must match the Authorized redirect URL we registered.clientMetadata: describes our client to the SDK.application_type: 'native'marks it as an application running on the user's machine, not a web server.scopeis the scope the SDK requests, read fromMCP_SCOPEin.env. The SDK only falls back to this value when the server doesn't advertise a scope, and ours doesn't. Without it, the client requests no scope, WSO2 Identity Platform issues a token that isn't intended for our MCP server, and the server rejects it.
clientInformation(): returns the client ID we copied from the Console. The SDK passes in the issuer of the authorization server it discovered. If that issuer isn't the one we expect, we return nothing, so our client ID is never sent to an unexpected server.
Discovery
saveDiscoveryState()anddiscoveryState(): keep what the SDK learned during discovery, such as the authorization server's metadata, so it doesn't repeat discovery after the browser callback.
Starting authorization
state(): creates a random value the SDK adds to the authorization URL. We keep a copy inlastStateand check that the callback carries the same value, which proves the callback answers our own request.saveCodeVerifier()andcodeVerifier(): hold the PKCE verifier. The SDK creates it before authorization and sends it with the token request, proving that the client exchanging the code is the one that started the flow.redirectToAuthorization(): called with the finished authorization URL. After checking that it uses HTTPS, so the user never signs in over an insecure connection, we print the URL and open it in the default browser withopen. If no browser can be opened, for example over SSH,openfails quietly and the printed URL still works.
After authorization
saveTokens()andtokens(): store and return the access token, and a refresh token if one is issued. The SDK adds the access token to every MCP request. TheTokenstype at the top of the file is the token response shape, taken from the SDK's own types.
Everything is held in memory, in the class's private fields, so a restart starts the flow again.
We don't implement OAuth token exchange ourselves. The SDK handles that once the browser returns the authorization response.
Putting the client together
We now have a protected MCP server, an OAuth client registration, and an OAuthClientProvider.
Let's connect them.
Update the client environment
Open .env and add the authorization server's issuer:
OAUTH_ISSUER=https://api.asgardeo.io/t/<organization>/oauth2/token
This is the issuer value from the authorization server metadata we inspected earlier. It isn't the same as BASE_URL: it ends in /oauth2/token.
Our provider only hands the client ID to an authorization server whose issuer matches this value exactly. If they differ, the SDK stops with an authorization server mismatch error instead of sending your client ID somewhere unexpected.
Our .env now contains the server-side and client-side configuration:
BASE_URL=https://api.asgardeo.io/t/<organization>
MCP_RESOURCE=http://localhost:3000/mcp
OAUTH_ISSUER=https://api.asgardeo.io/t/<organization>/oauth2/token
MCP_CLIENT_ID=<your-public-client-id>
MCP_SERVER_URL=http://localhost:3000/mcp
MCP_SCOPE=mcp:tools
What the client takes on
Right now, client.ts sends a fixed Authorization: Bearer demo-token header through requestInit. It never authenticates. It assumes someone already has a token and attaches it to every request.
WSO2 Identity Platform won't accept a made-up token, so the client now has to take part in getting a real one.
That sounds like a lot of new work. Most of it isn't ours:
| Responsibility | Handled by |
|---|---|
| Discover the authorization server | MCP SDK |
| Generate the PKCE values | MCP SDK, stored through our provider |
| Build the authorization URL | MCP SDK, shown by our provider |
| Exchange the code for tokens | MCP SDK, in finishAuth() |
| Attach the access token to requests | MCP SDK |
| Receive the browser's callback | Our callback server |
Check the callback's state | Our callback server |
| Reconnect after sign-in | Our client |
The MCP communication itself doesn't change. Connecting, listing tools, and calling them work exactly as before.
What we add is the part the SDK can't do from inside a library: getting the user through the browser and back. We'll split it into two files, so the OAuth plumbing stays out of the code that talks to the MCP server.
callback-server.tswaits for the browser to return.client.tsconnects, handles the first401, and calls tools.
Wait for the browser callback
After the user signs in, WSO2 Identity Platform redirects the browser to our redirect URL:
http://127.0.0.1:3030/callback?code=...&state=...
Something has to be listening there. We'll start a small HTTP server from Node's built-in node:http module, take that one request, and shut the server down.
Listening on a loopback address like this is the standard approach for applications that run on the user's machine (RFC 8252). A hosted application would use an HTTPS callback endpoint instead.
Create callback-server.ts and add:
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() takes the redirect URL and the state our provider created, and returns the callback's query parameters once they pass these checks:
- The path must match. Requests to any other path, like the browser asking for
/favicon.ico, get a404and are otherwise ignored. - The authorization server may report an error. If the user denies access, the callback carries
errorinstead ofcode. We show a failure page and reject with the server's description. - The
statemust match. A different value means this callback doesn't answer our request, so we reject it. This check must happen before the code goes anywhere nearfinishAuth(). - A code must be present. Without one, there's nothing to exchange.
Only after all of that does the browser see "Authorization complete".
The server never outlives the flow. It closes after the first callback, whether that callback succeeded or failed. It gives up after five minutes if the user never finishes signing in. If port 3030 is already taken, the listen error rejects the promise instead of leaving the client hanging.
Update client.ts
With the callback handled, the client's job is short:
- Try to connect. With no token stored, the server answers
401. The SDK runs discovery, builds the authorization URL, and passes it to our provider, which opens it in your browser.connect()then throws an authentication error. - Wait for the callback.
- Pass the callback parameters to
transport.finishAuth(). The SDK sends the authorization code and the PKCE verifier to WSO2 Identity Platform, and saves the tokens through our provider. - Reconnect with a new client and transport. This time the SDK attaches the access token, and
listTools()runs as before.
Open client.ts and replace its contents with:
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!
);
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'
)
);
}
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;
}
async function main() {
const client = await connect();
try {
const { tools } = await client.listTools();
console.log(
'Available tools:',
tools.map(tool => tool.name)
);
} finally {
await client.close();
}
}
main().catch(error => {
console.error('MCP client failed:', error);
process.exitCode = 1;
});
The one line that connects OAuth to the MCP client is in createTransport():
{ authProvider: provider }
It replaces the requestInit header we used before. From then on, the SDK attaches the access token itself.
connect() follows the four steps above, in order. If a token is already stored, step 1 succeeds and the function returns straight away.
isAuthenticationRequired() exists because the SDK can report "authentication required" in two ways: as an UnauthorizedError, or as an error with the code CLIENT_HTTP_AUTHENTICATION when the 401 arrives while the client is still negotiating the protocol version. We treat both the same way. Any other error is a real failure, so we rethrow it.
The final catch prints the whole error, not just its message. A network failure surfaces as fetch failed, and the actual reason, such as ECONNREFUSED when the MCP server isn't running, is in the error's cause.
Run the client
-
Make sure the Express MCP server is still running.
-
Open another terminal in the project directory and run:
node --env-file=.env --import tsx client.tsOn the first run, the provider has no stored tokens. The SDK tries to connect, gets the
401, runs discovery, and our provider opens the authorization URL in your browser. -
If the browser doesn't open, open the printed URL yourself.
-
Sign in as the user you assigned the
mcp:toolsrole to, and complete any required consent.The authorization server redirects the browser to:
http://127.0.0.1:3030/callback?code=...&state=...Our callback server checks the response and its
state, then the browser shows:Authorization complete. You can close this tab. -
Back in the terminal, watch the client finish. It passes the callback parameters to
finishAuth(), the SDK exchanges the code for tokens and saves them through our provider, and the client reconnects.
If the WSO2 middleware accepts the token, the client lists our add tool:
Available tools: [ 'add' ]
Invoke the protected tool
-
Open
client.tsand find:const { tools } = await client.listTools();
console.log(
'Available tools:',
tools.map(tool => tool.name)
); -
Immediately after this block, before the
finallyblock, add:const result = await client.callTool({
name: 'add',
arguments: {
a: 5,
b: 10
}
});
console.log(result.content); -
Save the file and run the client again.
Because we're using in-memory token storage, every run starts a new authorization flow. Once it completes, the client lists the add tool and returns the result.
We've now tested discovery, browser authorization, token exchange, and a protected MCP tool invocation.
What happens when the token expires?
If the authorization server issues a refresh token along with the access token, the SDK uses it to get a new access token when the old one expires, and saves the result through the provider's saveTokens() method.
Our provider keeps tokens in memory, so they don't survive a restart. To see a refresh happen, you'd need to keep the program running until the access token expires.
A production application would use a secure credential store, and keep credentials separate for each user, authorization server, resource, and client registration. Why Your MCP Token Expires Mid-Run looks at what happens when a token expires in the middle of a long agent run.
Verifying the resource indicator
We've authenticated successfully, but there's another thing we need to verify.
Was the access token issued for our MCP server?
Imagine we have two MCP servers using the same authorization server:
https://documents.example.com/mcp
https://finance.example.com/mcp
A token issued for the document server shouldn't automatically authorize access to the finance server.
MCP uses the OAuth resource parameter to identify the protected resource for which the client requests a token.
Our local MCP endpoint is:
http://localhost:3000/mcp
The client must request authorization for the intended MCP resource, and the MCP server must reject tokens that aren't intended for it.
Verify audience enforcement
We passed audience: resource to McpAuthServer, so the SDK should reject any token whose aud claim isn't our MCP resource. We still need to prove it with a real token.
In particular, we need to distinguish between a token that has a valid signature and issuer and a token that is actually intended for our server.
A valid signature alone isn't enough.
-
Check which audience your access token carries. Decode it with your identity platform's token diagnostics, or any JWT decoder you trust, and look at the
audclaim. -
Configure a second test API resource in WSO2 Identity Platform.
-
Obtain a token intended only for that resource.
-
Send it to our MCP server:
curl -i -X POST http://localhost:3000/mcp \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $OTHER_RESOURCE_TOKEN" \
-d '{}'Here,
OTHER_RESOURCE_TOKENholds the token obtained for the second test resource.
Our MCP server should reject that token with 401.
If it doesn't, the server's audience validation needs to be corrected before deployment.
The failure must be established through a real integration test. We shouldn't assume that a token is correctly audience-bound simply because the client sent a resource parameter.
What breaks in production
We've established the basic OAuth flow. There are still several cases worth testing before using this connection in a deployed agent application.
1. The access token expires during a tool call
A long-running application may make many MCP requests. Its access token could expire while it is operating.
The SDK can attempt to refresh credentials when a valid refresh token is available.
If refresh fails or the grant has been revoked, the application may need to request authorization again.
A production client should also avoid blindly retrying operations that may already have completed.
2. The application loses its authorization state
Our provider stores OAuth state, the PKCE verifier, and discovery information in memory.
That works for a local experiment, but a hosted application may need shared storage.
For example, a callback could reach a different application instance from the one that started authorization.
The application must be able to associate the callback with the correct user and pending authorization request.
3. The client uses the wrong transport
The OAuth flow we've implemented applies to HTTP-based MCP connections.
A local stdio MCP server doesn't use the same HTTP authorization flow.
We shouldn't assume that every transport supports the same authentication mechanism.
4. Credentials are shared between users
Our example uses one local OAuth provider with one token store.
A hosted application may serve multiple users and connect to several MCP resources.
It must resolve credentials for the correct user, client registration, authorization server, and resource.
Sharing a provider or token store between unrelated users could expose one user's permissions to another.
5. The server accepts a token for another resource
A token may be correctly signed and issued by a trusted authorization server but still be intended for a different API.
The MCP server must validate its intended audience.
That's why we need the resource-isolation test described earlier.
6. OAuth discovery fails
If an MCP server doesn't publish usable Protected Resource Metadata, or a proxy removes the authentication challenge, the client may not know where to initiate authorization.
Start debugging with the HTTP response.
Inspect the WWW-Authenticate header and resource metadata.
Then check the authorization server's metadata, client registration, redirect URI, and token exchange.
Capture actual failures from your integration tests rather than treating one SDK error message as universal behavior.
7. The agent needs additional consent during a run
Our example completes authorization before making tools available to an agent.
But an agent may discover halfway through a task that another operation requires additional permissions.
The application may need to pause that operation, present an authorization request, and resume execution after the user grants access.
The model can't complete the authorization interaction on the user's behalf. The LangGraph article looks at what that handoff involves.
Taking this into an agent application
We started with a small MCP client that connected to a local Express server and called an add tool.
Then we made the server require authentication and saw why supplying a static bearer token wasn't enough.
Next, we used WSO2 Identity Platform's MCP authorization SDK to protect the server and publish the information needed for OAuth discovery.
On the client side, we introduced OAuthClientProvider so the official MCP TypeScript SDK could handle authorization requests, PKCE, token exchange, and authorized connections.
We now have the connection an AI agent needs to access protected MCP tools.
The agent can use this connection through a tool adapter:
- UserAsks a question
- Agent selects a tool
- Application's tool adapter
- Authorized MCP client
- WSO2-protected MCP server
The model needs tool descriptions and input schemas to decide which operations to perform.
It doesn't need access to OAuth credentials.
The application remains responsible for associating credentials with the correct user and connection.
For production use, we'd extend the example with secure persistent token storage, refresh handling, and integration tests covering expired tokens, revoked authorization, and incorrect audiences.
In the companion article, Connecting a LangGraph Agent to an OAuth-Protected MCP Server, we hand this same authorized connection to a LangGraph agent, let a model choose the tool, and prove the access token never reaches the model.
On this page
- The problem the tutorials skip
- Why static headers are not enough
- The authProvider parameter that connects the pieces
- Delegating to the MCP SDK's OAuth provider
- How does the authorization server know our client?
- Consent inside an agent run
- Where do the tokens live?
- Putting the client together
- Verifying the resource indicator
- What breaks in production
- Taking this into an agent application