Decide for each tool
Hide the tools that a caller may not run, and refuse calls to them. LumoAuth decides for each tool and each caller.
What it shows
- The server has its own application, and asks LumoAuth with the client credentials of that application. It never sends the token of the caller.
- An administrator grants tools to an agent: single tools, or every tool of the server.
tools/listreturns only the tools that the caller may run.- A call to another tool is refused, with a result that the model can read.
- Every tool is denied until a grant allows it: nobody sees
delete_invoice.
Before you start
- Check that your plan includes fine-grained authorization in the plans matrix. Without it, every tool is denied.
- The setup script creates the rest: the application of the server with the scope
mcp:authorize, the registration that names this application, two agents, and their grants. - This recipe registers its own server, at
http://localhost:3002/mcp. The Admin API takes the application of the server at registration only. For a server that exists, open AI Agents, MCP servers, the server, Edit, and select the application under Per-tool authorization.
| 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, admin:agents:write, admin:clients:read and admin:clients: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. |
LUMOAUTH_MCP_CLIENT_ID | The client ID of the application of the MCP server itself. The setup script prints it. |
LUMOAUTH_MCP_CLIENT_SECRET | The client secret of that application. The setup script prints it. |
MCP_AGENT_ID | The ID of the agent invoice-reader. The setup script prints it. |
MCP_OTHER_AGENT_ID | The ID of the agent refund-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/per-tool-authorization/setup.mjs
setup.mjs
// Creates what the recipe needs: the application of the MCP server itself,
// the registration of the server, two agents, and their grants. Run it again
// at any time.
//
// node mcp-servers/per-tool-authorization/setup.mjs
//
// The API key needs the scopes admin:agents:read, admin:agents:write,
// admin:clients:read and admin:clients:write.
import { call, ensure, list, printEnv } from '../../_lib/admin.mjs';
// 1. The application of the MCP server itself. The server asks LumoAuth with
// a token of this application, never with the token of its caller.
const appName = 'Invoices MCP server';
let app = (await list('/admin/clients')).find((c) => c.name === appName);
let secret;
if (app) {
// LumoAuth shows a secret once. A second run therefore makes a new secret,
// and the old one stops working.
secret = (await call('POST', `/admin/clients/${app.clientId}/rotate-secret`)).data.secret;
} else {
app = (
await call('POST', '/admin/clients', {
name: appName,
grantTypes: ['client_credentials'],
scopes: ['mcp:authorize'],
isConfidential: true,
})
).data;
secret = app.secret;
}
// 2. The MCP server. Only the application above may ask about its tools. The
// Admin API takes this list at registration, so the recipe registers its
// own server, at its own address.
const resource = process.env.MCP_RESOURCE_URI ?? 'http://localhost:3002/mcp';
const server = await ensure('/admin/mcp/servers', (s) => s.resource_uri === resource, {
name: 'Invoices (rules for each tool)',
description: 'Reads and refunds invoices. LumoAuth decides for each tool.',
resource_uri: resource,
endpoint_url: resource,
scopes_supported: ['invoices:read', 'invoices:refund'],
basic_scopes: ['invoices:read'],
tool_authorizer_client_ids: [app.clientId],
// The test client of this recipe sends plain bearer tokens.
require_dpop: false,
});
// 3. Two agents. A capability lets an agent get a token for the server. It
// does not grant a tool.
const agent = (name, description, capabilities) =>
ensure('/admin/agents', (a) => a.name === name, { name, description, capabilities });
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']);
// 4. The grants. Every tool is denied until a grant allows it. LumoAuth stores
// a grant as a relationship: mcp_tool:<server>/<tool>#invoke@agent:<agent>.
await call('PUT', `/admin/mcp/servers/${server.server_id}/grants/${reader.agentId}`, { tools: ['list_invoices'] });
await call('PUT', `/admin/mcp/servers/${server.server_id}/grants/${refunder.agentId}`, { tools: ['list_invoices', 'refund'] });
console.log(`MCP server ${server.server_id}: invoice-reader may call list_invoices, refund-agent may call list_invoices and refund.`);
printEnv({
LUMOAUTH_MCP_SERVER_ID: server.server_id,
LUMOAUTH_MCP_CLIENT_ID: app.clientId,
LUMOAUTH_MCP_CLIENT_SECRET: secret,
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. Every version below was run against a LumoAuth organization.
- Node.js
- Python
mcp-servers/per-tool-authorization/js/server.mjs
// An MCP server that asks LumoAuth, for each tool, whether the caller may
// run it.
//
// node mcp-servers/per-tool-authorization/js/server.mjs
//
// It listens on http://localhost:3002/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 { lumoAuth } from '@lumoauth/mcp';
import { z } from 'zod';
// Besides the organization and the server ID, lumoAuth() reads
// LUMOAUTH_MCP_CLIENT_ID and LUMOAUTH_MCP_CLIENT_SECRET: the application of
// the server itself. With them, the policy for each tool is on.
const auth = lumoAuth();
await auth.ready();
const text = (value) => ({ content: [{ type: 'text', text: value }] });
function buildServer() {
const server = new McpServer({ name: 'invoices', version: '1.0.0' });
// secureTools() covers every tool of the server. It removes from the list
// the tools that the caller may not run, and it refuses calls to them.
// LumoAuth decides. The package keeps a decision for 30 seconds.
auth.secureTools(server);
server.registerTool('list_invoices', { description: 'List the invoices.' }, async () =>
text(JSON.stringify([{ id: 'INV-1001', customer: 'Northwind Labs', amount: 1200 }])),
);
server.registerTool(
'refund',
{ description: 'Refund one invoice.', inputSchema: { invoice_id: z.string() } },
async ({ invoice_id }) => text(`Refunded ${invoice_id}`),
);
server.registerTool(
'delete_invoice',
{ description: 'Delete one invoice.', inputSchema: { invoice_id: z.string() } },
async ({ invoice_id }) => text(`Deleted ${invoice_id}`),
);
return server;
}
const app = express();
app.use(express.json());
app.use(auth.router());
app.post('/mcp', auth.protect(), async (req, res) => {
const server = buildServer();
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 ?? 3002));
mcp-servers/per-tool-authorization/js/check.mjs
// Two agents ask the server for its tools and try a refund.
//
// node mcp-servers/per-tool-authorization/js/check.mjs
//
// Start the server 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:3002/mcp';
const lumoauthUrl = (process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev').replace(/\/+$/, '');
const api = `${lumoauthUrl}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
// 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: mcpUrl, expiresIn: 300 }),
});
return (await issued.json()).data.accessToken;
}
for (const [name, agentId] of [
['invoice-reader', process.env.MCP_AGENT_ID],
['refund-agent', process.env.MCP_OTHER_AGENT_ID],
]) {
const client = new Client({ name: 'recipe-check', version: '1.0.0' });
const headers = { Authorization: `Bearer ${await tokenFor(agentId)}` };
await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl), { requestInit: { headers } }));
// Each agent receives its own list.
const { tools } = await client.listTools();
console.log(`${name}: tools: ${tools.map((tool) => tool.name).sort().join(', ')}`);
// A call to a tool outside the list is refused too.
const refund = await client.callTool({ name: 'refund', arguments: { invoice_id: 'INV-1001' } });
console.log(`${name}: refund: ${refund.isError ? 'refused' : refund.content[0].text}`);
await client.close();
}
node mcp-servers/per-tool-authorization/js/server.mjs
# In a second terminal:
node mcp-servers/per-tool-authorization/js/check.mjs
mcp-servers/per-tool-authorization/python/server.py
"""An MCP server on FastMCP that asks LumoAuth, for each tool, whether the
caller may run it.
python mcp-servers/per-tool-authorization/python/server.py
It listens on http://localhost:3002/mcp, the resource URI of the registration.
"""
import os
from fastmcp import FastMCP
from lumoauth_fastmcp import LumoAuthProvider
# Besides the organization and the server ID, the provider reads
# LUMOAUTH_MCP_CLIENT_ID and LUMOAUTH_MCP_CLIENT_SECRET: the application of
# the server itself.
auth = LumoAuthProvider()
# tool_policy() covers every tool of the server. It removes from the list the
# tools that the caller may not run, and it refuses calls to them. LumoAuth
# decides. The package keeps a decision for 30 seconds.
mcp = FastMCP("Invoices", auth=auth, middleware=[auth.tool_policy()])
@mcp.tool
def list_invoices() -> list[dict]:
"""List the invoices."""
return [{"id": "INV-1001", "customer": "Northwind Labs", "amount": 1200}]
@mcp.tool
def refund(invoice_id: str) -> str:
"""Refund one invoice."""
return f"Refunded {invoice_id}"
@mcp.tool
def delete_invoice(invoice_id: str) -> str:
"""Delete one invoice."""
return f"Deleted {invoice_id}"
if __name__ == "__main__":
mcp.run(transport="http", port=int(os.environ.get("PORT", "3002")))
mcp-servers/per-tool-authorization/python/check.py
"""Two agents ask the server for its tools and try a refund.
python mcp-servers/per-tool-authorization/python/check.py
Start the server first, in another terminal.
"""
import asyncio
import os
import requests
from fastmcp import Client
from fastmcp.exceptions import ToolError
MCP_URL = os.environ.get("MCP_URL", "http://localhost:3002/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"
def token_for(agent_id: str) -> str:
"""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."""
issued = requests.post(
f"{API}/admin/agents/{agent_id}/token",
headers={"X-API-Key": os.environ["LUMOAUTH_API_KEY"]},
json={"resource": MCP_URL, "expiresIn": 300},
timeout=10,
)
return issued.json()["data"]["accessToken"]
async def main() -> None:
agents = [("invoice-reader", os.environ["MCP_AGENT_ID"]), ("refund-agent", os.environ["MCP_OTHER_AGENT_ID"])]
for name, agent_id in agents:
async with Client(MCP_URL, auth=token_for(agent_id)) as client:
# Each agent receives its own list.
tools = await client.list_tools()
print(f"{name}: tools: {', '.join(sorted(tool.name for tool in tools))}")
# A call to a tool outside the list is refused too.
try:
result = await client.call_tool("refund", {"invoice_id": "INV-1001"})
print(f"{name}: refund: {result.content[0].text}")
except ToolError:
print(f"{name}: refund: refused")
asyncio.run(main())
python mcp-servers/per-tool-authorization/python/server.py
# In a second terminal:
python mcp-servers/per-tool-authorization/python/check.py
Check the result
Output
invoice-reader: tools: list_invoices
invoice-reader: refund: refused
refund-agent: tools: list_invoices, refund
refund-agent: refund: Refunded INV-1001
- A valid token is not enough here. The token of
invoice-readerreaches the server, and the server still hidesrefundanddelete_invoicefrom it. - Change a grant, wait 30 seconds, and run the check again. The server needs no restart: it keeps a decision for 30 seconds.
- The lumo CLI asks the same question as the server. It exits with status 0 for "allowed" and 1 for "denied":
export LUMO_MCP_CLIENT_SECRET="$LUMOAUTH_MCP_CLIENT_SECRET"
lumo mcp check-tool "$LUMOAUTH_MCP_SERVER_ID" refund --subject "agent:$MCP_AGENT_ID" --client-id "$LUMOAUTH_MCP_CLIENT_ID"
- Each decision is in the audit log as the event
mcp.tool.authorization.
Limits
- When LumoAuth cannot be reached, the tool is refused.
- The setup script grants tools to agents. A grant for a person is a relationship that you add in the portal under Relationships: see Fine-grained authorization for agents.
- A grant names the tool as the server lists it in
tools/list. - An agent can ask about itself before it calls: see Say which agent may call which tool.