Protect a FastMCP server
Add LumoAuth to a FastMCP server in three lines: discovery, the 401 challenge and token checks.
What it shows
- The provider reads the registration of the server from LumoAuth at start.
- It serves the protected resource metadata, and answers a request without a token with a challenge.
- It verifies each token: signature, issuer, audience, expiry and type.
- A tool reads who is calling: a person, an agent, or an agent for a person.
- A tool names the scope that it needs. A caller without that scope does not see the tool.
Before you start
- An MCP server registered in LumoAuth, with
http://localhost:3000/mcpas 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 capabilityinvoices:read. - 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. The setup script and the test client read it. The server 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 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/fastmcp/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/fastmcp/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.
- Python
"""An MCP server on FastMCP that accepts only tokens from LumoAuth.
python mcp-servers/fastmcp/python/server.py
It listens on http://localhost:3000/mcp, the resource URI of the registration.
"""
import os
from fastmcp import FastMCP
from lumoauth_fastmcp import LumoAuthProvider, current_caller, require_scopes
# The provider reads LUMOAUTH_ORG_ID and LUMOAUTH_MCP_SERVER_ID. At start it
# reads the registration from LumoAuth: the resource URI, the basic scopes and
# the DPoP switch. It then serves the metadata document, answers a request
# without a token with a challenge, and verifies each token.
mcp = FastMCP("Invoices", auth=LumoAuthProvider())
INVOICES = [
{"id": "INV-1001", "customer": "Northwind Labs", "amount": 1200},
{"id": "INV-1002", "customer": "Acme", "amount": 300},
]
@mcp.tool
def whoami() -> str:
"""Say who is calling."""
caller = current_caller()
if caller.is_delegated:
return f"agent {caller.actor} for user {caller.sub}"
if caller.is_agent:
return f"agent {caller.agent_id}"
return f"user {caller.sub}"
@mcp.tool(auth=require_scopes("invoices:read"))
def list_invoices() -> list[dict]:
"""List the invoices."""
return INVOICES
# A caller whose token lacks the scope does not see this tool and cannot call it.
@mcp.tool(auth=require_scopes("invoices:refund"))
def refund(invoice_id: str) -> str:
"""Refund one invoice."""
return f"Refunded {invoice_id}"
if __name__ == "__main__":
mcp.run(transport="http", port=int(os.environ.get("PORT", "3000")))
"""Calls the server three ways: without a token, with the token of an agent,
and for a tool that the token does not cover.
python mcp-servers/fastmcp/python/check.py
Start the server first, in another terminal.
"""
import asyncio
import os
import re
import requests
from fastmcp import Client
from fastmcp.exceptions import ToolError
MCP_URL = os.environ.get("MCP_URL", "http://localhost:3000/mcp")
LUMOAUTH_URL = os.environ.get("LUMOAUTH_URL", "https://app.lumoauth.dev").rstrip("/")
API = f"{LUMOAUTH_URL}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1"
# 1. Without a token, the server answers 401 and says where its metadata is.
answer = requests.post(MCP_URL, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, timeout=10)
challenge = answer.headers["WWW-Authenticate"]
print(f"no token: {answer.status_code} {challenge}")
# The metadata names the resource. A token must be issued for exactly that resource.
metadata_url = re.search(r'resource_metadata="([^"]+)"', challenge).group(1)
resource = requests.get(metadata_url, timeout=10).json()["resource"]
# 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.
token = requests.post(
f"{API}/admin/agents/{os.environ['MCP_AGENT_ID']}/token",
headers={"X-API-Key": os.environ["LUMOAUTH_API_KEY"]},
json={"resource": resource, "expiresIn": 300},
timeout=10,
).json()["data"]["accessToken"]
async def main() -> None:
async with Client(MCP_URL, auth=token) as client:
tools = await client.list_tools()
print("tools:", ", ".join(sorted(tool.name for tool in tools)))
result = await client.call_tool("whoami")
print("whoami:", result.data)
# 3. The agent holds invoices:read only, so the server refuses the refund.
try:
await client.call_tool("refund", {"invoice_id": "INV-1001"})
print("refund: allowed")
except ToolError as error:
print("refund: refused:", error)
asyncio.run(main())
python mcp-servers/fastmcp/python/server.py
# In a second terminal:
python mcp-servers/fastmcp/python/check.py
The test client connects to http://localhost:3000/mcp. Use that spelling everywhere: a token for localhost does not work at 127.0.0.1, which the start banner of FastMCP prints.
Check the result
no token: 401 Bearer scope="invoices:read", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp"
tools: list_invoices, whoami
whoami: agent agt_d14f76250aa280b6
refund: refused: Unknown tool: 'refund'
- The first line is the challenge. An MCP client reads
resource_metadatafrom it and finds your organization in that document. - The agent holds
invoices:read, so its token carries that scope. The list of tools has norefund, and a call to it is refused. - A token that the server cannot verify is refused with
401, anderror_descriptionin the challenge gives the reason. - With the lumo CLI,
lumo mcp test <server-id> <agent-id>gets a token for the agent and sendstools/listto the server.
To sign in as a person from a real client, see Connect Claude Code, Cursor or VS Code.
Limits
- The provider reads the registration once, at start. Restart the server after you change the registration.
- The checks apply to the HTTP transport. A server on stdio has no OAuth step, and
current_caller()returnsNonethere. - A tool with
auth=require_scopes(...)is hidden from a caller that lacks the scope. For aninsufficient_scopeanswer that a client can act on, see Ask for more scope when a tool needs it.