An MCP server that accepts only bound tokens
Require DPoP on an MCP server, so that a token taken from a log or a proxy cannot be used.
What it shows
- The registration of the server has "Require DPoP" on. The server reads that setting: its code has no DPoP option.
- The challenge and the metadata name the DPoP scheme and the signing algorithms that the server accepts.
- An agent makes a key, and sends a proof with its token request. LumoAuth binds the token to the key.
- The agent sends a new proof with each request, and the server checks it.
- The same token without a proof is refused.
Before you start
- An MCP server registered with Require DPoP sender-constrained tokens on. The setup script registers
Paymentsathttp://localhost:3003/mcpwithrequire_dpop: true. - An agent with a client ID and secret, and a capability that covers a scope of the server. The setup script creates
payments-agentwithpayments:read. - Node.js 20 or later, or Python 3.10 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. Only the setup script reads it. |
LUMOAUTH_MCP_SERVER_ID | The ID of the registered MCP server (mcp_…). The setup script prints it. The server reads it. |
AGENT_CLIENT_ID | The client ID of the agent. The setup script prints it. The client reads it. |
AGENT_CLIENT_SECRET | The client secret of the agent. 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/dpop/setup.mjs
setup.mjs
// Creates what the recipe needs: an MCP server that requires DPoP, and an
// agent with a client ID and secret. Run it again at any time.
//
// node mcp-servers/dpop/setup.mjs
//
// The API key needs the scopes admin:agents:read and admin:agents:write.
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
// A server with its own address: the DPoP switch belongs to the registration.
const resource = process.env.MCP_RESOURCE_URI ?? 'http://localhost:3003/mcp';
const server = await ensure('/admin/mcp/servers', (s) => s.resource_uri === resource, {
name: 'Payments',
description: 'Reads payments. Accepts only tokens that are bound to a key.',
resource_uri: resource,
endpoint_url: resource,
scopes_supported: ['payments:read'],
basic_scopes: ['payments:read'],
// LumoAuth then issues only bound tokens for this server.
require_dpop: true,
});
const agent = await ensure('/admin/agents', (a) => a.name === 'payments-agent', {
name: 'payments-agent',
description: 'Reads payments through the Payments MCP server.',
identityType: 'client_secret',
capabilities: ['payments:read'],
});
// LumoAuth shows a secret once, in the answer that creates it. On a second
// run the script therefore asks for a new secret, and the old one stops.
const secret =
agent.clientSecret ??
(await call('POST', `/admin/agents/${agent.agentId}/rotate-credentials`)).data.clientSecret;
console.log(`MCP server ${server.name} (${server.resource_uri}, DPoP required) and agent ${agent.name} are ready.`);
printEnv({ LUMOAUTH_MCP_SERVER_ID: server.server_id, AGENT_CLIENT_ID: agent.agentId, AGENT_CLIENT_SECRET: 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.
- Node.js
- Python
mcp-servers/dpop/js/server.mjs
// An MCP server that accepts only DPoP-bound tokens. The code has no DPoP
// setting: lumoAuth() reads the switch from the registration.
//
// node mcp-servers/dpop/js/server.mjs
//
// It listens on http://localhost:3003/mcp, the resource URI of the registration.
import express from 'express';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { getCaller, lumoAuth } from '@lumoauth/mcp';
const auth = lumoAuth();
const { requireDpop } = await auth.ready();
console.log(`DPoP required: ${requireDpop}`);
const app = express();
app.use(express.json());
app.use(auth.router());
// protect() checks the proof of each request: the method, the address, the
// hash of the token, and that the key of the proof is the key of the token.
app.post('/mcp', auth.protect(), async (req, res) => {
const server = new McpServer({ name: 'payments', version: '1.0.0' });
server.registerTool('whoami', { description: 'Say who is calling.' }, async (extra) => {
const caller = getCaller(extra);
// dpopJkt is the thumbprint of the key that the token is bound to.
return { content: [{ type: 'text', text: `${caller.sub}, key ${caller.dpopJkt}` }] };
});
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 ?? 3003));
mcp-servers/dpop/js/client.mjs
// An agent that holds a DPoP key. It gets a token that is bound to the key,
// and sends a new proof with each request to the MCP server.
//
// node mcp-servers/dpop/js/client.mjs
//
// Start the server first, in another terminal.
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { DpopProofSigner, LumoAgent, fetchWithDpop } from '@lumoauth/agent';
const mcpUrl = process.env.MCP_URL ?? 'http://localhost:3003/mcp';
const listTools = {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
};
// 1. Without a token, the challenge names the DPoP scheme and the algorithms.
const answer = await fetch(mcpUrl, listTools);
console.log(`no token: ${answer.status} ${answer.headers.get('www-authenticate')}`);
// 2. The agent makes a key. A real agent keeps the key in its secret store
// (signer.privateKeyPem). LumoAgent reads AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const signer = DpopProofSigner.generate();
const agent = new LumoAgent({ dpop: signer });
// The token request carries a proof, so LumoAuth binds the token to the key.
const { accessToken, tokenType } = await agent.mcp.getTokenDetailed(mcpUrl);
const claims = JSON.parse(Buffer.from(accessToken.split('.')[1], 'base64url'));
console.log(`token: type ${tokenType}, bound to the key of the agent: ${claims.cnf.jkt === signer.thumbprint ? 'yes' : 'no'}`);
// 3. fetchWithDpop adds "Authorization: DPoP <token>" and a new proof to each request.
const transport = new StreamableHTTPClientTransport(new URL(mcpUrl), {
fetch: (url, init) => fetchWithDpop(fetch, String(url), init, signer, { accessToken }),
});
const client = new Client({ name: 'payments-agent', version: '1.0.0' });
await client.connect(transport);
const who = await client.callTool({ name: 'whoami' });
console.log('whoami:', who.content[0].text);
await client.close();
// 4. The same token without a proof, as somebody who copied it would send it.
const copied = await fetch(mcpUrl, { ...listTools, headers: { ...listTools.headers, Authorization: `Bearer ${accessToken}` } });
console.log(`copied token: ${copied.status} ${copied.headers.get('www-authenticate')}`);
node mcp-servers/dpop/js/server.mjs
# In a second terminal:
node mcp-servers/dpop/js/client.mjs
mcp-servers/dpop/python/server.py
"""An MCP server on FastMCP that accepts only DPoP-bound tokens. The code has
no DPoP setting: the provider reads the switch from the registration.
python mcp-servers/dpop/python/server.py
It listens on http://localhost:3003/mcp, the resource URI of the registration.
"""
import os
from fastmcp import FastMCP
from lumoauth_fastmcp import LumoAuthProvider, current_caller
# The provider checks the proof of each request: the method, the address, the
# hash of the token, and that the key of the proof is the key of the token.
mcp = FastMCP("Payments", auth=LumoAuthProvider())
@mcp.tool
def whoami() -> str:
"""Say who is calling."""
caller = current_caller()
# dpop_thumbprint is the thumbprint of the key that the token is bound to.
return f"{caller.sub}, key {caller.dpop_thumbprint}"
if __name__ == "__main__":
mcp.run(transport="http", port=int(os.environ.get("PORT", "3003")))
mcp-servers/dpop/python/client.py
"""An agent that holds a DPoP key. It gets a token that is bound to the key,
and sends a new proof with each request to the MCP server.
python mcp-servers/dpop/python/client.py
Start the server first, in another terminal.
"""
import asyncio
import base64
import json
import os
import httpx2
import requests
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport
from lumoauth import LumoAuthAgent
MCP_URL = os.environ.get("MCP_URL", "http://localhost:3003/mcp")
LIST_TOOLS = {"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
ACCEPT = {"Accept": "application/json, text/event-stream"}
# 1. Without a token, the challenge names the DPoP scheme and the algorithms.
answer = requests.post(MCP_URL, json=LIST_TOOLS, headers=ACCEPT, timeout=10)
print(f"no token: {answer.status_code} {answer.headers['WWW-Authenticate']}")
# 2. dpop=True makes a key for this run. A real agent loads its key from a
# secret store (DpopKey.from_pem). The agent reads AGENT_CLIENT_ID and
# AGENT_CLIENT_SECRET.
agent = LumoAuthAgent(dpop=True)
# The token request carries a proof, so LumoAuth binds the token to the key.
credential = agent.get_mcp_credential(MCP_URL)
payload = credential.access_token.split(".")[1]
claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
bound = "yes" if claims["cnf"]["jkt"] == agent.dpop.thumbprint else "no"
print(f"token: type {credential.token_type}, bound to the key of the agent: {bound}")
class DpopAuth(httpx2.Auth):
"""Adds "Authorization: DPoP <token>" and a new proof to each request."""
def auth_flow(self, request):
request.headers.update(credential.headers(request.method, str(request.url)))
yield request
async def main() -> None:
# 3. The MCP client sends every request through DpopAuth.
async with Client(StreamableHttpTransport(MCP_URL, auth=DpopAuth())) as client:
result = await client.call_tool("whoami")
print("whoami:", result.content[0].text)
asyncio.run(main())
# 4. The same token without a proof, as somebody who copied it would send it.
copied = requests.post(
MCP_URL,
json=LIST_TOOLS,
headers={**ACCEPT, "Authorization": f"Bearer {credential.access_token}"},
timeout=10,
)
print(f"copied token: {copied.status_code} {copied.headers['WWW-Authenticate']}")
python mcp-servers/dpop/python/server.py
# In a second terminal:
python mcp-servers/dpop/python/client.py
Check the result
Output
no token: 401 DPoP scope="payments:read", resource_metadata="http://localhost:3003/.well-known/oauth-protected-resource/mcp", algs="ES256 ES384 ES512 RS256 RS384 RS512 PS256 PS384 PS512 EdDSA"
token: type DPoP, bound to the key of the agent: yes
whoami: agent_agt_c5babbc4cbbb532f, key a23TOX86BiR2W7CutMdo7XW9WozMqq8y6DhvVYFgECE
copied token: 401 DPoP error="invalid_token", error_description="DPoP-bound access token must be presented with the DPoP scheme", scope="payments:read", resource_metadata="http://localhost:3003/.well-known/oauth-protected-resource/mcp", algs="ES256 ES384 ES512 RS256 RS384 RS512 PS256 PS384 PS512 EdDSA"
- The challenge uses the scheme
DPoPin place ofBearer, and lists the algorithms inalgs. - The token has the type
DPoP, and itscnf.jktclaim is the thumbprint of the key of the agent. - The last line is the point of the recipe. Somebody who copies the token from a log holds no key, and the server refuses the token.
- The metadata document at
http://localhost:3003/.well-known/oauth-protected-resource/mcphasdpop_bound_access_tokens_required: true.
The text in error_description differs between the two packages. The status and the scheme are the same.
Limits
- Some MCP clients do not send DPoP proofs. Leave the switch off for a server that they must reach.
- A test token from the Admin API (
POST /admin/agents/{id}/token, orlumo mcp test) cannot be bound to a key. LumoAuth refuses such a request for a server that requires DPoP. - The server stores the IDs of the proofs that it saw, to refuse a proof that is sent twice. The store is in the memory of one process. With several processes, give the packages a shared store:
replayCachein JavaScript,replay_cachein Python. - The key of this recipe exists for one run. An agent that runs for a long time keeps its key in a secret store.