Skip to main content

Protect a server built on the MCP TypeScript SDK

Add LumoAuth to an MCP server in Express or in a fetch handler: discovery, the 401 challenge and token checks.

RecipeReadyView source
Works with
JavaScript / TypeScriptMCP TypeScript SDKExpress

What it shows​

  1. lumoAuth() reads the registration of the server from LumoAuth.
  2. router() serves the protected resource metadata.
  3. protect() sends the challenge, verifies the token and sets req.auth.
  4. A tool reads the caller with getCaller(), and guard() refuses a call that lacks a scope.
  5. In a fetch handler, discovery() and gate() do the work of router() and protect().

Before you start​

  • An MCP server registered in LumoAuth, with http://localhost:3000/mcp as its resource URI. The setup script registers it. Register an MCP server explains each setting.
  • An agent for the test client. The setup script creates invoice-reader, which holds the capability invoices:read.
  • Node.js 20 or later.
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_KEYAn API key with the scopes admin:agents:read and admin:agents:write. The setup script and the test client read it. The server does not.
LUMOAUTH_MCP_SERVER_IDThe ID of the registered MCP server (mcp_…). The setup script prints it.
MCP_AGENT_IDThe ID of the test agent (agt_…). The setup script prints it.

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

node mcp-servers/typescript-sdk/setup.mjs
setup.mjs
// Creates what the recipe needs: the registration of the MCP server, and an
// agent that may read invoices. Run it again at any time.
//
// node mcp-servers/typescript-sdk/setup.mjs
//
// The API key needs the scopes admin:agents:read and admin:agents: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'],
// A client asks for the basic scopes first. The challenge names only these.
basic_scopes: ['invoices:read'],
// The test client of this recipe sends plain bearer tokens.
require_dpop: false,
});

// The agent holds invoices:read and not invoices:refund.
const agent = await ensure('/admin/agents', (a) => a.name === 'invoice-reader', {
name: 'invoice-reader',
description: 'Reads invoices through the Invoices MCP server.',
capabilities: ['invoices:read'],
});

console.log(`MCP server ${server.name} (${server.resource_uri}) and agent ${agent.name} are ready.`);
printEnv({ LUMOAUTH_MCP_SERVER_ID: server.server_id, MCP_AGENT_ID: agent.agentId });

The server needs only LUMOAUTH_ORG_ID and LUMOAUTH_MCP_SERVER_ID, and LUMOAUTH_URL for the EU region. It holds no secret.

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.

mcp-servers/typescript-sdk/js/server.mjs
// An MCP server on the MCP TypeScript SDK and Express that accepts only
// tokens from LumoAuth.
//
// node mcp-servers/typescript-sdk/js/server.mjs
//
// It listens on http://localhost:3000/mcp, the resource URI of the registration.
import express from 'express';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { lumoAuth } from '@lumoauth/mcp';
import { buildServer } from './tools.mjs';

// lumoAuth() reads LUMOAUTH_ORG_ID and LUMOAUTH_MCP_SERVER_ID. ready() reads
// the registration from LumoAuth now, so that a wrong server ID stops the start.
const auth = lumoAuth();
await auth.ready();

const app = express();
app.use(express.json());

// The metadata document that tells a client where LumoAuth is.
app.use(auth.router());

// protect() answers a request without a valid token with the challenge. It
// puts the verified caller on req.auth, and the transport passes it to the tools.
app.post('/mcp', auth.protect({ requiredScopes: ['invoices:read'] }), async (req, res) => {
const server = buildServer(auth);
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
res.on('close', () => {
transport.close();
server.close();
});
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});

app.listen(Number(process.env.PORT ?? 3000));
mcp-servers/typescript-sdk/js/tools.mjs
// The tools of the Invoices server. Both versions of the server use this file.
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { getCaller } from '@lumoauth/mcp';
import { z } from 'zod';

const invoices = [
{ id: 'INV-1001', customer: 'Northwind Labs', amount: 1200 },
{ id: 'INV-1002', customer: 'Acme', amount: 300 },
];

const text = (value) => ({ content: [{ type: 'text', text: value }] });

/** A new server for one request. `auth` is the result of `lumoAuth()`. */
export function buildServer(auth) {
const server = new McpServer({ name: 'invoices', version: '1.0.0' });

server.registerTool('whoami', { description: 'Say who is calling.' }, async (extra) => {
// The caller comes from the verified token, never from an argument.
const caller = getCaller(extra);
if (caller.isDelegated) return text(`agent ${caller.actor} for user ${caller.sub}`);
if (caller.isAgent) return text(`agent ${caller.agentId}`);
return text(`user ${caller.sub}`);
});

server.registerTool('list_invoices', { description: 'List the invoices.' }, async () => text(JSON.stringify(invoices)));

// guard() refuses the call when the token lacks the scope. The refusal is a
// tool result with isError, so that the model can read the reason.
server.registerTool(
'refund',
{ description: 'Refund one invoice.', inputSchema: { invoiceId: z.string() } },
auth.guard('refund', async ({ invoiceId }) => text(`Refunded ${invoiceId}`), { scopes: ['invoices:refund'] }),
);

return server;
}
mcp-servers/typescript-sdk/js/check.mjs
// Calls the server three ways: without a token, with the token of an agent,
// and for a tool that the token does not cover.
//
// node mcp-servers/typescript-sdk/js/check.mjs
//
// Start the server first, in another terminal.
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 lumoauthUrl = (process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev').replace(/\/+$/, '');
const api = `${lumoauthUrl}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;

// 1. Without a token, the server answers 401 and says where its metadata is.
const answer = 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 = answer.headers.get('www-authenticate');
console.log(`no token: ${answer.status} ${challenge}`);

// The metadata names the resource. A token must be issued for exactly that resource.
const metadataUrl = /resource_metadata="([^"]+)"/.exec(challenge)[1];
const { resource } = await (await fetch(metadataUrl)).json();

// 2. Get a test token for the agent from the Admin API. An agent that runs by
// itself asks the token endpoint with its own credential instead.
const issued = await fetch(`${api}/admin/agents/${process.env.MCP_AGENT_ID}/token`, {
method: 'POST',
headers: { 'X-API-Key': process.env.LUMOAUTH_API_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ resource, expiresIn: 300 }),
});
const token = (await issued.json()).data.accessToken;

const client = new Client({ name: 'recipe-check', version: '1.0.0' });
await client.connect(
new StreamableHTTPClientTransport(new URL(mcpUrl), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }),
);

const { tools } = await client.listTools();
console.log('tools:', tools.map((tool) => tool.name).sort().join(', '));
const who = await client.callTool({ name: 'whoami' });
console.log('whoami:', who.content[0].text);

// 3. The agent holds invoices:read only, so the server refuses the refund.
const refund = await client.callTool({ name: 'refund', arguments: { invoiceId: 'INV-1001' } });
console.log(refund.isError ? 'refund: refused:' : 'refund:', refund.content[0].text);

await client.close();
node mcp-servers/typescript-sdk/js/server.mjs
# In a second terminal:
node mcp-servers/typescript-sdk/js/check.mjs

Both versions use @modelcontextprotocol/sdk. The fetch version runs on Node.js through @hono/node-server.

Check the result​

Output
no token: 401 Bearer scope="invoices:read", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp"
tools: list_invoices, refund, whoami
whoami: agent agt_d14f76250aa280b6
refund: refused: Tool 'refund' needs the scope invoices:refund.
  • The first line is the challenge. An MCP client reads resource_metadata from it and finds your organization in that document.
  • The agent holds invoices:read, so its token passes protect(). The token lacks invoices:refund, so guard() refuses the refund with a result that the model can read.
  • A token that LumoAuth issued for another audience gets 401 with error_description="Invalid audience".

To sign in as a person from a real client, see Connect Claude Code, Cursor or VS Code.

Limits​

  • The package reads the registration once. Restart the server after you change the registration.
  • guard() leaves the tool in the list of tools. To hide tools from a caller, see Decide for each tool.
  • A refusal from guard() is a tool result, not an HTTP 403. A client cannot use it to ask the person for more scope: see Ask for more scope when a tool needs it.