Put authorization in front of a server that you cannot change
Run one command in front of any MCP server: it adds discovery, the challenge and token checks, and passes allowed calls through.
What it shows
npx lumoauth checkprints what the registration says, before you start anything.- For an HTTP server,
npx lumoauth secure --upstreamruns as a proxy in front of it. - For a stdio server,
npx lumoauth secure --stdiostarts it and gives it an HTTP address, with one process for each session. - The proxy serves the metadata, sends the challenge and verifies each token.
--scopenames a scope that every request needs. - An HTTP server behind the proxy receives headers that say who is calling.
The server in the code stands for one that you cannot change. It can be written in any language.
Before you start
- An MCP server registered in LumoAuth. Its resource URI is the address of the proxy,
http://localhost:3000/mcp, not the address of the server behind it. The setup script registers it. - Two agents for the test client. The setup script creates
invoice-readerwith the capabilityinvoices:read, andrefund-agentwithinvoices:refundonly. - Node.js 20 or later.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | An API key with the scopes admin:agents:read and admin:agents:write. The setup script and the test client read it. The proxy does not. |
LUMOAUTH_MCP_SERVER_ID | The ID of the registered MCP server (mcp_…). The setup script prints it. |
MCP_AGENT_ID | The ID of the agent that holds invoices:read. The setup script prints it. |
MCP_OTHER_AGENT_ID | The ID of the agent that does not hold it. 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/secure-an-existing-server/setup.mjs
setup.mjs
// Creates what the recipe needs: the registration of the MCP server, and two
// agents for the test client. Run it again at any time.
//
// node mcp-servers/secure-an-existing-server/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 address of the proxy, not of the server behind it.
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,
});
const agent = (name, description, capabilities) =>
ensure('/admin/agents', (a) => a.name === name, { name, description, capabilities });
// The proxy asks for invoices:read on every request. One agent holds it, and one does not.
const reader = await agent('invoice-reader', 'Reads invoices through the Invoices MCP server.', ['invoices:read']);
const refunder = await agent('refund-agent', 'Refunds invoices, and reads none.', ['invoices:refund']);
console.log(`MCP server ${server.name} (${server.resource_uri}) and two agents are ready.`);
printEnv({ LUMOAUTH_MCP_SERVER_ID: server.server_id, MCP_AGENT_ID: reader.agentId, MCP_OTHER_AGENT_ID: refunder.agentId });
The proxy needs only LUMOAUTH_ORG_ID and LUMOAUTH_MCP_SERVER_ID, and LUMOAUTH_URL for the EU region.
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.
- HTTP server
- stdio server
// An MCP server over HTTP that checks nothing: the stand-in for a server that
// you cannot change. It listens on 127.0.0.1 only, so that callers must pass
// the proxy.
//
// node mcp-servers/secure-an-existing-server/js/upstream.mjs
import express from 'express';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
const invoices = [
{ id: 'INV-1001', customer: 'Northwind Labs', amount: 1200 },
{ id: 'INV-1002', customer: 'Acme', amount: 300 },
];
const app = express();
app.use(express.json());
app.post('/mcp', async (req, res) => {
// The proxy adds these headers after it verified the token. It removes
// headers with these names from the request of the client.
console.log(`upstream: ${req.body.method} from ${req.headers['x-lumoauth-subject']} (${req.headers['x-lumoauth-scopes']})`);
const server = new McpServer({ name: 'invoices', version: '1.0.0' });
server.registerTool('list_invoices', { description: 'List the invoices.' }, async () => ({
content: [{ type: 'text', text: JSON.stringify(invoices) }],
}));
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.UPSTREAM_PORT ?? 3001), '127.0.0.1');
// Calls the proxy three ways: without a token, with the token of an agent
// that holds invoices:read, and with the token of an agent that does not.
//
// node mcp-servers/secure-an-existing-server/js/check.mjs
//
// Start the proxy 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`;
const post = (headers = {}) =>
fetch(mcpUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', ...headers },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
});
// 1. Without a token, the proxy answers 401 and says where its metadata is.
const answer = await post();
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();
// A test token for an agent, from the Admin API. An agent that runs by itself
// asks the token endpoint with its own credential instead.
async function tokenFor(agentId) {
const issued = await fetch(`${api}/admin/agents/${agentId}/token`, {
method: 'POST',
headers: { 'X-API-Key': process.env.LUMOAUTH_API_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ resource, expiresIn: 300 }),
});
return (await issued.json()).data.accessToken;
}
// 2. The reader passes the proxy and reaches the server behind it.
const client = new Client({ name: 'recipe-check', version: '1.0.0' });
const authorization = { Authorization: `Bearer ${await tokenFor(process.env.MCP_AGENT_ID)}` };
await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl), { requestInit: { headers: authorization } }));
const { tools } = await client.listTools();
console.log('invoice-reader: tools:', tools.map((tool) => tool.name).join(', '));
const result = await client.callTool({ name: 'list_invoices' });
console.log('invoice-reader: list_invoices:', JSON.parse(result.content[0].text).length, 'invoices');
await client.close();
// 3. The other agent holds invoices:refund only. The proxy refuses its token.
const refused = await post({ Authorization: `Bearer ${await tokenFor(process.env.MCP_OTHER_AGENT_ID)}` });
console.log(`refund-agent: ${refused.status} ${refused.headers.get('www-authenticate')}`);
npx lumoauth check
npx lumoauth secure --upstream http://127.0.0.1:3001/mcp --port 3000 --scope invoices:read \
-- node mcp-servers/secure-an-existing-server/js/upstream.mjs
# In a second terminal:
node mcp-servers/secure-an-existing-server/js/check.mjs
// An MCP server over stdio: the stand-in for a server that an MCP client
// normally starts as a local process.
//
// node mcp-servers/secure-an-existing-server/js/stdio-server.mjs
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
const invoices = [
{ id: 'INV-1001', customer: 'Northwind Labs', amount: 1200 },
{ id: 'INV-1002', customer: 'Acme', amount: 300 },
];
const server = new McpServer({ name: 'invoices', version: '1.0.0' });
server.registerTool('list_invoices', { description: 'List the invoices.' }, async () => ({
content: [{ type: 'text', text: JSON.stringify(invoices) }],
}));
// stdout carries the protocol, so a log line goes to stderr.
console.error(`stdio server: process ${process.pid} started for one session`);
await server.connect(new StdioServerTransport());
// Calls the proxy three ways: without a token, with the token of an agent
// that holds invoices:read, and with the token of an agent that does not.
//
// node mcp-servers/secure-an-existing-server/js/check.mjs
//
// Start the proxy 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`;
const post = (headers = {}) =>
fetch(mcpUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', ...headers },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
});
// 1. Without a token, the proxy answers 401 and says where its metadata is.
const answer = await post();
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();
// A test token for an agent, from the Admin API. An agent that runs by itself
// asks the token endpoint with its own credential instead.
async function tokenFor(agentId) {
const issued = await fetch(`${api}/admin/agents/${agentId}/token`, {
method: 'POST',
headers: { 'X-API-Key': process.env.LUMOAUTH_API_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ resource, expiresIn: 300 }),
});
return (await issued.json()).data.accessToken;
}
// 2. The reader passes the proxy and reaches the server behind it.
const client = new Client({ name: 'recipe-check', version: '1.0.0' });
const authorization = { Authorization: `Bearer ${await tokenFor(process.env.MCP_AGENT_ID)}` };
await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl), { requestInit: { headers: authorization } }));
const { tools } = await client.listTools();
console.log('invoice-reader: tools:', tools.map((tool) => tool.name).join(', '));
const result = await client.callTool({ name: 'list_invoices' });
console.log('invoice-reader: list_invoices:', JSON.parse(result.content[0].text).length, 'invoices');
await client.close();
// 3. The other agent holds invoices:refund only. The proxy refuses its token.
const refused = await post({ Authorization: `Bearer ${await tokenFor(process.env.MCP_OTHER_AGENT_ID)}` });
console.log(`refund-agent: ${refused.status} ${refused.headers.get('www-authenticate')}`);
npx lumoauth check
npx lumoauth secure --stdio --port 3000 --scope invoices:read \
-- node mcp-servers/secure-an-existing-server/js/stdio-server.mjs
# In a second terminal:
node mcp-servers/secure-an-existing-server/js/check.mjs
In the HTTP version, the command after -- starts the server, and the proxy waits until the server listens. Leave that part out for a server that already runs.
Check the result
no token: 401 Bearer scope="invoices:read", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp"
invoice-reader: tools: list_invoices
invoice-reader: list_invoices: 2 invoices
refund-agent: 403 Bearer error="insufficient_scope", error_description="Missing scope: invoices:read", scope="invoices:read", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp"
- The request without a token and the request of
refund-agentnever reach the server behind the proxy. - In the HTTP version, the terminal of the proxy shows one line for each request that reached the server. Each line has the caller from the header
X-LumoAuth-Subject, for exampleupstream: tools/call from agent_agt_d14f76250aa280b6 (invoices:read). - In the stdio version, the terminal shows one line when the proxy starts a process for a session.
Limits
- The proxy does not pass the token on. An HTTP server behind it reads the caller from the
X-LumoAuth-*headers. A stdio server does not receive the caller. - Keep the server on
127.0.0.1, or on a network that only the proxy can reach. A request that goes around the proxy is not checked. - The proxy reads the registration at start. Restart it after you change the registration.
- For rules for each tool, see Decide for each tool.