Check tokens at the gateway
Run the token check next to an MCP server in Kubernetes, as a sidecar or as an external authorization service for Envoy.
What it shows
- The MCP server checks no token. It listens on
127.0.0.1, so a caller must pass the gateway in front of it. - With Envoy, the gateway asks
npx lumoauth ext-authzabout each request. The check service verifies the token and answers with the401challenge, a403, or a yes with the caller inX-LumoAuth-*headers. - As a Kubernetes sidecar,
npx lumoauth secureruns in the pod, in front of the server, and does the same checks itself. - The server reads who is calling from the headers. Headers with those names that the client sent never reach it.
Both ways need no change to the code of the MCP server.
Before you start
- An MCP server registered with the address of the gateway as its resource URI. The setup script registers
Invoices (gateway)athttp://localhost:8080/mcp. In a cluster, use the publichttpsaddress that routes to the Service. - Two agents for the test client:
invoice-readerholdsinvoices:read, andrefund-agentdoes not. The setup script creates them. - For Envoy: Docker. The
docker runcommand uses the host network, which Docker on Linux offers. Docker Desktop needs host networking switched on in its settings. - For the sidecar: a Kubernetes cluster. Put your organization and the server ID in the
envof thelumoauthcontainer, and your image in themcp-servercontainer.
| 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 gateway does not. |
LUMOAUTH_MCP_SERVER_ID | The ID of the registered MCP server (mcp_…). The setup script prints it. The check service reads 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/envoy-and-kubernetes/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/envoy-and-kubernetes/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 gateway, not of the server behind it.
const resource = process.env.MCP_RESOURCE_URI ?? 'http://localhost:8080/mcp';
const server = await ensure('/admin/mcp/servers', (s) => s.resource_uri === resource, {
name: 'Invoices (gateway)',
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 gateway 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 });
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Envoy ran in Docker, with the check service and the MCP server on the same machine. The Kubernetes manifest was not applied to a cluster: its sidecar container ran in Docker and gave the same output.
- Envoy
- Kubernetes sidecar
# Envoy in front of an MCP server. Envoy asks `npx lumoauth ext-authz` about
# each request, and passes the request on only when the check service says
# yes. The check service also serves the metadata for MCP clients.
#
# Envoy listens on 0.0.0.0:8080 the resource URI of the registration
# the check service on 127.0.0.1:9001 npx lumoauth ext-authz --port 9001
# the MCP server on 127.0.0.1:8000 it checks no token itself
static_resources:
listeners:
- name: mcp
address:
socket_address: { address: 0.0.0.0, port_value: 8080 }
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: mcp
route_config:
virtual_hosts:
- name: mcp
domains: ["*"]
routes:
# The metadata comes from the check service, with no token.
- match: { prefix: "/.well-known/" }
route: { cluster: lumoauth_check }
typed_per_filter_config:
envoy.filters.http.ext_authz:
"@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute
disabled: true
# Everything else goes to the MCP server, without the token
# and without the client's approval token: the check service
# has read it, and the MCP server trusts only its headers.
- match: { prefix: "/" }
route: { cluster: mcp_server }
request_headers_to_remove: ["authorization", "dpop", "x-lumoauth-jit-token"]
http_filters:
# Only the check service may set the identity headers. Remove
# the ones that the client sent.
- name: envoy.filters.http.header_mutation
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutation
mutations:
request_mutations:
- remove: x-lumoauth-subject
- remove: x-lumoauth-subject-type
- remove: x-lumoauth-agent-id
- remove: x-lumoauth-actor
- remove: x-lumoauth-client-id
- remove: x-lumoauth-scopes
- remove: x-lumoauth-trace-id
- remove: x-lumoauth-is-jit
# With --vault github=conn_…, also remove x-lumoauth-vault-github-token.
- name: envoy.filters.http.ext_authz
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz
# The check service reads the JSON-RPC body for the per-tool
# policy and for --jit.
with_request_body: { max_request_bytes: 65536, allow_partial_message: true }
http_service:
server_uri: { uri: "http://127.0.0.1:9001", cluster: lumoauth_check, timeout: 5s }
authorization_request:
allowed_headers:
patterns:
- exact: authorization
- exact: dpop
- exact: traceparent
- exact: x-lumoauth-jit-token
- exact: content-type
authorization_response:
allowed_upstream_headers:
patterns:
- prefix: x-lumoauth-
- exact: traceparent
allowed_client_headers:
patterns:
- exact: www-authenticate
- exact: insufficient-authorization-details
- exact: x-lumoauth-denied-tool
- exact: content-type
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
clusters:
- name: lumoauth_check
type: STATIC
load_assignment:
cluster_name: lumoauth_check
endpoints:
- lb_endpoints:
- endpoint: { address: { socket_address: { address: 127.0.0.1, port_value: 9001 } } }
- name: mcp_server
type: STATIC
load_assignment:
cluster_name: mcp_server
endpoints:
- lb_endpoints:
- endpoint: { address: { socket_address: { address: 127.0.0.1, port_value: 8000 } } }
// An MCP server that checks no token: it trusts the gateway in front of it.
// It reads who is calling from the headers that the gateway adds. It listens
// on 127.0.0.1 only, so that callers must pass the gateway.
//
// node mcp-servers/envoy-and-kubernetes/js/upstream.mjs
import express from 'express';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
const text = (value) => ({ content: [{ type: 'text', text: value }] });
const app = express();
app.use(express.json());
app.get('/healthz', (req, res) => res.send('ok'));
app.post('/mcp', async (req, res) => {
const server = new McpServer({ name: 'invoices', version: '1.0.0' });
server.registerTool('whoami', { description: 'Say who is calling.' }, async (extra) => {
// The gateway sets these headers after it checked the token.
const headers = extra.requestInfo.headers;
return text(
`${headers['x-lumoauth-subject']} (${headers['x-lumoauth-scopes']}), ` +
`actor ${headers['x-lumoauth-actor'] ?? 'none'}, approval ${headers['x-lumoauth-is-jit'] ?? 'none'}`,
);
});
server.registerTool('list_invoices', { description: 'List the invoices.' }, async () =>
text('INV-1001 Northwind Labs 1200, INV-1002 Acme 300'),
);
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 ?? 8000), '127.0.0.1');
// Calls the server through the gateway: without a token, with the token of an
// agent that holds invoices:read (and with headers that try to pass for the
// gateway), and with the token of an agent that does not hold it.
//
// node mcp-servers/envoy-and-kubernetes/js/check.mjs
//
// Start the server, the check service and the gateway first.
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
const mcpUrl = process.env.MCP_URL ?? 'http://localhost:8080/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 gateway answers 401 and says where the metadata is.
const answer = await post();
const challenge = answer.headers.get('www-authenticate');
console.log(`no token: ${answer.status} ${challenge}`);
// The gateway serves the metadata too. It names the resource of the tokens.
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 gateway. It also sends two headers that only the
// gateway may set. The gateway removes them, so the server sees the truth.
const headers = {
Authorization: `Bearer ${await tokenFor(process.env.MCP_AGENT_ID)}`,
'X-LumoAuth-Actor': 'agent_agt_forged',
'X-LumoAuth-Is-Jit': 'true',
};
const client = new Client({ name: 'recipe-check', version: '1.0.0' });
await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl), { requestInit: { headers } }));
console.log('invoice-reader: tools:', (await client.listTools()).tools.map((tool) => tool.name).join(', '));
console.log('invoice-reader: whoami:', (await client.callTool({ name: 'whoami' })).content[0].text);
await client.close();
// 3. The other agent holds invoices:refund only. The gateway 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')}`);
node mcp-servers/envoy-and-kubernetes/js/upstream.mjs &
npx lumoauth ext-authz --port 9001 --host 127.0.0.1 --scope invoices:read &
docker run --rm --network host -v "$PWD/mcp-servers/envoy-and-kubernetes/js/envoy.yaml:/etc/envoy/envoy.yaml:ro" envoyproxy/envoy:v1.34.14
# In a second terminal:
node mcp-servers/envoy-and-kubernetes/js/check.mjs
Run against a LumoAuth organization.
# A pod with two containers: your MCP server, and `npx lumoauth secure` in
# front of it. The MCP server listens on 127.0.0.1:8000, which only the
# containers of the pod can reach. The sidecar listens on 8080, checks each
# token, and passes the request on with the caller in X-LumoAuth-* headers.
#
# kubectl apply -f mcp-servers/envoy-and-kubernetes/js/sidecar.yaml
#
# Register the server with its public address as the resource URI, for
# example https://mcp.example.com/mcp, and route that address to the Service.
apiVersion: apps/v1
kind: Deployment
metadata:
name: invoices-mcp
spec:
replicas: 2
selector:
matchLabels:
app: invoices-mcp
template:
metadata:
labels:
app: invoices-mcp
spec:
containers:
- name: lumoauth
image: node:22-alpine
command:
- npx
- --yes
- lumoauth@1.4.0
- secure
- --upstream=http://127.0.0.1:8000/mcp
- --port=8080
- --scope=invoices:read
# The health check needs no token. It reaches /healthz of the server.
- --public=/healthz
env:
- name: LUMOAUTH_URL
value: https://app.lumoauth.dev
- name: LUMOAUTH_ORG_ID
value: acme-corp
- name: LUMOAUTH_MCP_SERVER_ID
value: mcp_0123456789abcdef01234567
# npx keeps the package here.
- name: HOME
value: /tmp
ports:
- name: mcp
containerPort: 8080
readinessProbe:
httpGet: { path: /healthz, port: mcp }
initialDelaySeconds: 10
securityContext:
runAsNonRoot: true
runAsUser: 1000
allowPrivilegeEscalation: false
capabilities: { drop: ["ALL"] }
- name: mcp-server
# Your MCP server. It checks no token, and it must listen on 127.0.0.1:8000.
image: registry.example.com/invoices-mcp:1.0.0
env:
- name: UPSTREAM_PORT
value: "8000"
---
apiVersion: v1
kind: Service
metadata:
name: invoices-mcp
spec:
selector:
app: invoices-mcp
ports:
- name: mcp
port: 80
targetPort: mcp
// An MCP server that checks no token: it trusts the gateway in front of it.
// It reads who is calling from the headers that the gateway adds. It listens
// on 127.0.0.1 only, so that callers must pass the gateway.
//
// node mcp-servers/envoy-and-kubernetes/js/upstream.mjs
import express from 'express';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
const text = (value) => ({ content: [{ type: 'text', text: value }] });
const app = express();
app.use(express.json());
app.get('/healthz', (req, res) => res.send('ok'));
app.post('/mcp', async (req, res) => {
const server = new McpServer({ name: 'invoices', version: '1.0.0' });
server.registerTool('whoami', { description: 'Say who is calling.' }, async (extra) => {
// The gateway sets these headers after it checked the token.
const headers = extra.requestInfo.headers;
return text(
`${headers['x-lumoauth-subject']} (${headers['x-lumoauth-scopes']}), ` +
`actor ${headers['x-lumoauth-actor'] ?? 'none'}, approval ${headers['x-lumoauth-is-jit'] ?? 'none'}`,
);
});
server.registerTool('list_invoices', { description: 'List the invoices.' }, async () =>
text('INV-1001 Northwind Labs 1200, INV-1002 Acme 300'),
);
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 ?? 8000), '127.0.0.1');
// Calls the server through the gateway: without a token, with the token of an
// agent that holds invoices:read (and with headers that try to pass for the
// gateway), and with the token of an agent that does not hold it.
//
// node mcp-servers/envoy-and-kubernetes/js/check.mjs
//
// Start the server, the check service and the gateway first.
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
const mcpUrl = process.env.MCP_URL ?? 'http://localhost:8080/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 gateway answers 401 and says where the metadata is.
const answer = await post();
const challenge = answer.headers.get('www-authenticate');
console.log(`no token: ${answer.status} ${challenge}`);
// The gateway serves the metadata too. It names the resource of the tokens.
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 gateway. It also sends two headers that only the
// gateway may set. The gateway removes them, so the server sees the truth.
const headers = {
Authorization: `Bearer ${await tokenFor(process.env.MCP_AGENT_ID)}`,
'X-LumoAuth-Actor': 'agent_agt_forged',
'X-LumoAuth-Is-Jit': 'true',
};
const client = new Client({ name: 'recipe-check', version: '1.0.0' });
await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl), { requestInit: { headers } }));
console.log('invoice-reader: tools:', (await client.listTools()).tools.map((tool) => tool.name).join(', '));
console.log('invoice-reader: whoami:', (await client.callTool({ name: 'whoami' })).content[0].text);
await client.close();
// 3. The other agent holds invoices:refund only. The gateway 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')}`);
kubectl apply -f mcp-servers/envoy-and-kubernetes/js/sidecar.yaml
Compiles. Not run against an organization. No Kubernetes cluster was available. The sidecar container ran in Docker with the same image and command, and the test client gave the output; the manifest itself was not applied.
In envoy.yaml, the filter header_mutation removes the identity headers that the client sent, before the check service adds its own. The route removes the token before Envoy passes the request on, so the MCP server never sees it.
Check the result
no token: 401 Bearer scope="invoices:read", resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource/mcp"
invoice-reader: tools: whoami, list_invoices
invoice-reader: whoami: agent_agt_d14f76250aa280b6 (invoices:read), actor none, approval none
refund-agent: 403 Bearer error="insufficient_scope", error_description="Missing scope: invoices:read", scope="invoices:read", resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource/mcp"
- The challenge and the metadata come from the check service, through Envoy. An MCP client finds LumoAuth from them alone.
- The
whoamiline is what the server read from the headers. The test client sentX-LumoAuth-ActorandX-LumoAuth-Is-Jititself, and the server showsnonefor both. refund-agentholds noinvoices:read. The check service answers403, and the request never reaches the server.- In a cluster, the server listens on
127.0.0.1inside the pod. A request from another pod reaches only the sidecar.
Limits
- Without the
header_mutationfilter, Envoy passes a client'sX-LumoAuth-ActororX-LumoAuth-Is-Jitheader to the server when the check service sets no value for it. Keep the filter, and add a line for each--vaultheader. - The check service reads the request body only for the per-tool policy (
--tool-policy) and for--jit. Envoy sends at most 64 KiB of the body in this file. npxdownloads the package when the sidecar starts. For a cluster, build an image withlumoauthinstalled, so that a start needs no download.- The check service and the sidecar read the registration once, at start. Restart them after you change it.