Skip to main content

Write an MCP client that signs in

Build the client side of MCP authorization: from the first 401 to a token for that server.

RecipeReadyView source
Works with
JavaScript / TypeScriptMCP TypeScript SDK

What it shows​

  1. The client calls the server without a token, and reads resource_metadata and scope from the 401 challenge.
  2. It reads the metadata of the server, which names the resource and the authorization server. Then it reads the metadata of the authorization server, and checks that the issuer matches.
  3. It runs the authorization code flow with PKCE and the resource parameter. A person signs in and approves, and LumoAuth issues a token for this server only.
  4. It calls the tool with the MCP TypeScript SDK client. On 403 insufficient_scope, it asks the person again for the scopes that it holds and the missing ones, and calls again.

Each step is written by hand, with fetch and node:crypto, so that you can see what an MCP client does. The MCP SDK client only sends the MCP messages.

Before you start​

  • An MCP server that answers a missing scope with 403 insufficient_scope. Start the server of An MCP server with no LumoAuth package or of Ask for more scope when a tool needs it in another terminal.
  • A public application for the client, with the redirect URI http://localhost:8765/callback and every scope that the client may ask for. The setup script creates "Local MCP client", and the registration of the server if it is missing.
  • A user who can sign in to your organization.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYFor the setup script only: an API key with the scopes admin:agents:read, admin:agents:write, admin:clients:read and admin:clients:write. The client needs no API key.
MCP_CLIENT_IDThe client ID of the public application "Local MCP client". The setup script prints it.
MCP_URLOptional. The address of the MCP server. The default is http://localhost:3000/mcp.
MCP_TOOLOptional. The tool to call. The default is refund.
MCP_TOOL_ARGSOptional. The arguments of the tool, as JSON. The default is {"invoice_id": "INV-1001"}.

The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.

node mcp-clients/write-an-mcp-client/setup.mjs
setup.mjs
// Creates what the recipe needs: the registration of the MCP server, and a
// public application for the MCP client. Run it again at any time.
//
// node mcp-clients/write-an-mcp-client/setup.mjs
//
// The API key needs the scopes admin:agents:read, admin:agents:write,
// admin:clients:read and admin:clients:write.
import { ensure, printEnv } from '../../_lib/admin.mjs';

// The resource URI is the exact address that clients connect to.
const resource = process.env.MCP_RESOURCE_URI ?? 'http://localhost:3000/mcp';

const server = await ensure('/admin/mcp/servers', (s) => s.resource_uri === resource, {
name: 'Invoices',
description: 'Reads and refunds invoices.',
resource_uri: resource,
endpoint_url: resource,
scopes_supported: ['invoices:read', 'invoices:refund'],
// The challenge names only the basic scopes. The client asks for
// invoices:refund when a tool needs it.
basic_scopes: ['invoices:read'],
// The client of this recipe sends plain bearer tokens.
require_dpop: false,
});

// The client is a public application: it has no secret and uses PKCE. Its
// list of scopes must hold every scope that it may ever ask for.
const redirectUri = process.env.MCP_CLIENT_REDIRECT_URI ?? 'http://localhost:8765/callback';
const client = await ensure('/admin/clients', (c) => c.name === 'Local MCP client', {
name: 'Local MCP client',
isConfidential: false,
redirectUris: [redirectUri],
scopes: ['openid', 'profile', 'email', 'offline_access', 'invoices:read', 'invoices:refund'],
});

console.log(`MCP server ${server.name} (${server.resource_uri}) and the application "${client.name}" are ready.`);
printEnv({ MCP_CLIENT_ID: client.clientId });

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. The client ran against three servers with no change to its code: the Node.js server of the recipe with no package, the server of the scope step-up recipe, and a second registration with another tool and another application. A headless browser signed a test user in.

mcp-clients/write-an-mcp-client/js/client.mjs
// An MCP client that signs a person in, written step by step: from the first
// 401 to a token for the server, and a second sign-in when a tool needs more.
//
// node mcp-clients/write-an-mcp-client/js/client.mjs
//
// Start an MCP server first, in another terminal. The client prints an
// address. Open it in a browser, sign in and approve.
import crypto from 'node:crypto';
import http from 'node:http';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';

const mcpUrl = process.env.MCP_URL ?? 'http://localhost:3000/mcp';
const clientId = process.env.MCP_CLIENT_ID;
const redirectUri = process.env.MCP_CLIENT_REDIRECT_URI ?? 'http://localhost:8765/callback';
const tool = process.env.MCP_TOOL ?? 'refund';
const toolArguments = JSON.parse(process.env.MCP_TOOL_ARGS ?? '{"invoice_id": "INV-1001"}');

const getJson = async (url) => {
const response = await fetch(url);
if (!response.ok) throw new Error(`${url} answered ${response.status}`);
return response.json();
};
// One value of a WWW-Authenticate header, such as resource_metadata or scope.
const param = (header, name) => new RegExp(`${name}="([^"]*)"`).exec(header ?? '')?.[1];

// 1. Call the server without a token. The 401 challenge names the metadata
// of the server, and the scopes to ask for first.
const first = await fetch(mcpUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
});
const challenge = first.headers.get('www-authenticate');
const metadataUrl = param(challenge, 'resource_metadata');
console.log(`no token: ${first.status}, metadata ${metadataUrl}`);

// 2. The metadata names the resource (the audience of the token) and the
// authorization server. The metadata of that server is at the well-known
// address between its host and its path, and it must name the same issuer.
const metadata = await getJson(metadataUrl);
const issuer = metadata.authorization_servers[0];
const { origin, pathname } = new URL(issuer);
const server = await getJson(`${origin}/.well-known/oauth-authorization-server${pathname}`);
if (server.issuer !== issuer) throw new Error(`The metadata names the issuer ${server.issuer}, not ${issuer}.`);
console.log(`resource: ${metadata.resource}, issuer ${issuer}`);

// The browser comes back to the redirect URI with the code.
let deliver;
const callback = http.createServer((req, res) => {
const url = new URL(req.url, redirectUri);
if (url.pathname !== new URL(redirectUri).pathname) return res.writeHead(404).end();
res.end('You can close this window.');
deliver(url.searchParams);
});
callback.listen(Number(new URL(redirectUri).port));

// 3. The authorization code flow with PKCE. The resource parameter asks for a
// token for this server only.
async function signIn(scope) {
const verifier = crypto.randomBytes(32).toString('base64url');
const state = crypto.randomBytes(16).toString('base64url');
const authorize = new URL(server.authorization_endpoint);
authorize.search = new URLSearchParams({
response_type: 'code',
client_id: clientId,
redirect_uri: redirectUri,
scope,
state,
resource: metadata.resource,
code_challenge: crypto.createHash('sha256').update(verifier).digest('base64url'),
code_challenge_method: 'S256',
});
console.log(`authorize: scope "${scope}"\n open ${authorize}`);

const answer = await new Promise((resolve) => (deliver = resolve));
if (answer.get('state') !== state) throw new Error('The state does not match.');
// The answer names the issuer, so that it cannot come from another server.
if (answer.has('iss') && answer.get('iss') !== issuer) throw new Error('The answer comes from another issuer.');
if (!answer.get('code')) throw new Error(`Sign-in failed: ${answer.get('error')}`);

const response = await fetch(server.token_endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code: answer.get('code'),
redirect_uri: redirectUri,
client_id: clientId,
code_verifier: verifier,
resource: metadata.resource,
}),
});
const tokens = await response.json();
if (!response.ok) throw new Error(`The token request failed: ${tokens.error_description ?? tokens.error}`);
console.log(`token: scope "${tokens.scope}"`);
return tokens;
}

// 4. Call the tools with the token. The fetch function keeps the last
// WWW-Authenticate header, which names a missing scope.
let lastChallenge;
const recordingFetch = async (url, init) => {
const response = await fetch(url, init);
lastChallenge = response.headers.get('www-authenticate') ?? lastChallenge;
return response;
};
async function connect(accessToken) {
const client = new Client({ name: 'my-mcp-client', version: '1.0.0' });
await client.connect(
new StreamableHTTPClientTransport(new URL(mcpUrl), {
fetch: recordingFetch,
requestInit: { headers: { Authorization: `Bearer ${accessToken}` } },
}),
);
return client;
}

let tokens = await signIn(param(challenge, 'scope') ?? metadata.scopes_supported.join(' '));
let client = await connect(tokens.access_token);
console.log(`tools: ${(await client.listTools()).tools.map((t) => t.name).join(', ')}`);

let result;
try {
result = await client.callTool({ name: tool, arguments: toolArguments });
} catch (error) {
// A valid token without the scope of the tool gets 403 insufficient_scope.
// Ask the person again, for the scopes held so far and the missing ones.
const missing = param(lastChallenge, 'scope');
if (error.code !== 403 || !missing) throw error;
console.log(`${tool}: 403, needs "${missing}"`);
await client.close();
tokens = await signIn([...new Set([...tokens.scope.split(' '), ...missing.split(' ')])].join(' '));
client = await connect(tokens.access_token);
result = await client.callTool({ name: tool, arguments: toolArguments });
}
console.log(`${tool}: ${result.content[0].text}`);

await client.close();
callback.close();
node mcp-clients/write-an-mcp-client/js/client.mjs

The client prints an address two times. Open each one in a browser, sign in and approve. The second consent screen asks only for invoices:refund, and shows the scope that you already gave.

Check the result​

Output
no token: 401, metadata http://localhost:3000/.well-known/oauth-protected-resource/mcp
resource: http://localhost:3000/mcp, issuer https://app.lumoauth.dev/orgs/acme-corp/api/v1
authorize: scope "invoices:read"
open https://app.lumoauth.dev/orgs/acme-corp/api/v1/oauth/authorize?response_type=code&client_id=client_8b1c7d9936f0682eca5bc579757abc27&…
token: scope "invoices:read"
tools: list_invoices, refund
refund: 403, needs "invoices:refund"
authorize: scope "invoices:read invoices:refund"
open https://app.lumoauth.dev/orgs/acme-corp/api/v1/oauth/authorize?response_type=code&client_id=client_8b1c7d9936f0682eca5bc579757abc27&…
token: scope "invoices:read invoices:refund"
refund: Refunded INV-1001
  • The client knows only the address of the MCP server and its own client ID. It found LumoAuth, the endpoints and the first scope in the metadata.
  • Point the client at another MCP server with no change to the code: set MCP_URL, MCP_TOOL, MCP_TOOL_ARGS, and the MCP_CLIENT_ID of an application that may ask for the scopes of that server.
  • The person sees the client under Authorized apps in their account, at https://app.lumoauth.dev/account/consents.

Limits​

  • The client keeps the tokens in memory and asks for no refresh token. A client that runs for a long time stores a refresh token, and signs the person in again when it needs a new scope, because a refresh cannot add a scope.
  • The server of Protect a server built on the MCP TypeScript SDK refuses a missing scope with an error result, not with 403. Against that server, the client prints the refusal and does not ask again.
  • MCP_CLIENT_ID can also be the https address of a client metadata document. LumoAuth then reads the client from that document, with no registration. This recipe was run with a registered application only.