Skip to main content

An MCP server with no LumoAuth package

Write the three parts by hand, in any language: the metadata document, the 401 challenge and the token check.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGoPlain HTTPNode.jsFastAPIGo net/http

What it shows​

  1. At start, the server reads the metadata that LumoAuth publishes for its registration. It serves the same document at /.well-known/oauth-protected-resource/mcp, where MCP clients look for it.
  2. It reads the metadata of the issuer, checks that the issuer matches, and takes the address of the key set from it.
  3. A request without a token gets 401, with a WWW-Authenticate header that names the metadata and the basic scopes.
  4. The server verifies each token: the signature with the key set, the type at+jwt, the issuer, the audience and the expiry.
  5. Each tool needs a scope. A valid token without it gets 403 with error="insufficient_scope" and the missing scope.

Each server uses only an HTTP framework and a JWT library. It answers the MCP messages initialize, tools/list and tools/call by hand, with no MCP package.

Before you start​

  • An MCP server registered in LumoAuth, and an agent for the test client. The setup script registers Invoices at http://localhost:3000/mcp, with invoices:read as its basic scope. It creates the agent invoice-reader, which holds invoices:read and not invoices:refund.
  • Node.js 20 or later, Python 3.10 or later, or Go 1.22 or later. The test client needs curl and jq.
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 servers do not.
LUMOAUTH_MCP_SERVER_IDThe ID of the registered MCP server (mcp_…). The setup script prints it. The servers read it.
MCP_AGENT_IDThe ID of the test agent (agt_…). The setup script prints it. The test client reads it.

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

node mcp-servers/without-a-package/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/without-a-package/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 });

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. Each server ran with the curl test client. Each one was also called by the client of the MCP TypeScript SDK and by lumo mcp test, and refused a token that was issued for another MCP server.

mcp-servers/without-a-package/js/server.mjs
// An MCP server with no LumoAuth package: Node's HTTP server and the JWT
// library jose. It serves the metadata, answers with the 401 challenge,
// verifies each token and checks the scope of each tool.
//
// node mcp-servers/without-a-package/js/server.mjs
//
// It listens on http://localhost:3000/mcp, the resource URI of the registration.
import http from 'node:http';
import { createRemoteJWKSet, jwtVerify } from 'jose';

const lumoauthUrl = (process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev').replace(/\/+$/, '');
const issuer = `${lumoauthUrl}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;

const getJson = async (url) => {
const response = await fetch(url);
if (!response.ok) throw new Error(`${url} answered ${response.status}`);
return response.json();
};

// 1. LumoAuth publishes the metadata of the registration. This server serves
// the same document at its own address, where MCP clients look for it.
const metadata = await getJson(`${issuer}/.well-known/oauth-protected-resource/mcp/${process.env.LUMOAUTH_MCP_SERVER_ID}`);
const resource = new URL(metadata.resource);
const metadataPath = `/.well-known/oauth-protected-resource${resource.pathname}`;
const metadataUrl = `${resource.origin}${metadataPath}`;

// The issuer's own metadata names the key set. Never build that path yourself.
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}.`);
const keys = createRemoteJWKSet(new URL(server.jwks_uri));

const invoices = [
{ id: 'INV-1001', customer: 'Northwind Labs', amount: 1200 },
{ id: 'INV-1002', customer: 'Acme', amount: 300 },
];
const tools = {
list_invoices: { scope: 'invoices:read', run: () => invoices.map((i) => `${i.id} ${i.customer} ${i.amount}`).join(', ') },
refund: { scope: 'invoices:refund', run: (args) => `Refunded ${args.invoice_id}` },
};

// Scopes compare exactly. LumoAuth adds one rule: a granted scope that ends
// in ":*" covers the scopes under it.
const covered = (needed, granted) =>
granted.some((g) => g === needed || (g.endsWith(':*') && g !== ':*' && needed.startsWith(g.slice(0, -1))));

function send(res, status, body, headers = {}) {
res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
res.end(body === undefined ? undefined : JSON.stringify(body));
}

// 2. A request without a valid token gets 401, with the address of the metadata.
function challenge(res, status, error, description, scope) {
const parts = [];
if (error) parts.push(`error="${error}"`);
if (description) parts.push(`error_description="${description}"`);
parts.push(`resource_metadata="${metadataUrl}"`);
parts.push(`scope="${scope ?? metadata.scopes_supported.join(' ')}"`);
send(res, status, { error: error ?? 'invalid_request' }, { 'WWW-Authenticate': `Bearer ${parts.join(', ')}` });
}

// 3. The token check: signature from the key set, type, issuer, audience, expiry.
async function verify(token) {
const { payload } = await jwtVerify(token, keys, { issuer, audience: metadata.resource, typ: 'at+jwt' });
return payload;
}

http
.createServer(async (req, res) => {
if (req.method === 'GET' && req.url === metadataPath) return send(res, 200, metadata);
if (req.url !== resource.pathname) return send(res, 404, { error: 'not_found' });
if (req.method !== 'POST') return send(res, 405, { error: 'method_not_allowed' });
// A browser page of another site must not reach a server on your machine.
if (req.headers.origin && req.headers.origin !== resource.origin) return send(res, 403, { error: 'origin_not_allowed' });

const bearer = /^Bearer (.+)$/i.exec(req.headers.authorization ?? '')?.[1];
if (!bearer) return challenge(res, 401);
let claims;
try {
claims = await verify(bearer);
} catch {
return challenge(res, 401, 'invalid_token', 'the token is not valid for this server');
}

let body = '';
for await (const chunk of req) body += chunk;
const message = JSON.parse(body);
if (message.id === undefined) return send(res, 202);
const reply = (result) => send(res, 200, { jsonrpc: '2.0', id: message.id, result });

if (message.method === 'initialize') {
return reply({
protocolVersion: message.params.protocolVersion,
capabilities: { tools: {} },
serverInfo: { name: 'invoices', version: '1.0.0' },
});
}
if (message.method === 'tools/list') {
return reply({
tools: Object.keys(tools).map((name) => ({
name,
inputSchema: name === 'refund'
? { type: 'object', properties: { invoice_id: { type: 'string' } }, required: ['invoice_id'] }
: { type: 'object', properties: {} },
})),
});
}
if (message.method === 'tools/call') {
const tool = tools[message.params.name];
if (!tool) return send(res, 200, { jsonrpc: '2.0', id: message.id, error: { code: -32602, message: 'Unknown tool' } });
// 4. The scope of the tool. A valid token without it gets 403, which
// names the scope, so that the client can ask the person for it.
const granted = (claims.scope ?? '').split(' ');
if (!covered(tool.scope, granted)) return challenge(res, 403, 'insufficient_scope', undefined, tool.scope);
return reply({ content: [{ type: 'text', text: tool.run(message.params.arguments ?? {}) }] });
}
send(res, 200, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } });
})
.listen(Number(process.env.PORT ?? 3000));
node mcp-servers/without-a-package/js/server.mjs
# In a second terminal:
sh mcp-servers/without-a-package/http/check.sh

The three servers behave the same, so one test client works for all of them. Start one server, then run the test client in a second terminal.

Check the result​

Output
no token: 401 Bearer resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp", scope="invoices:read"
tools: list_invoices, refund
list_invoices: INV-1001 Northwind Labs 1200, INV-1002 Acme 300
refund: 403 Bearer error="insufficient_scope", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp", scope="invoices:refund"
  • The first line is the challenge. An MCP client reads resource_metadata, and from that document it finds LumoAuth. The server needs no other setting for that.
  • Open http://localhost:3000/.well-known/oauth-protected-resource/mcp in a browser. It shows the resource, the issuer of your organization and the basic scopes.
  • The last line names invoices:refund. An MCP client that signs a person in can ask for that scope and try again: see Ask for more scope when a tool needs it.
  • The servers also work with the client of the MCP TypeScript SDK, and with lumo mcp test <server-id> <agent-id>.

Limits​

  • The servers accept only bearer tokens. For a registration with Require DPoP sender-constrained tokens on, the server must also check a proof on each request, as described in the server guide. The DPoP recipe uses the packages for that.
  • A signature check cannot show that a token was revoked before it expires. Before an action that matters, ask LumoAuth with token introspection.
  • The servers read the metadata once, at start. Restart a server after you change the registration.
  • The MCP handling is the smallest part that a client needs: one JSON answer for each request, no stream, no notifications to the client. For more, use an MCP SDK with the TypeScript package or FastMCP.