Tools that need a person's approval
Mark a tool as high-risk. An agent sees it in the list, and a call returns the approval that it must ask for.
What it shows
- The tool
refundnames the approval that it needs: the typepayment_initiation, the actionrefund, and the invoice of the call. - The agent calls the tool with its normal token. The call fails with
insufficient_authorization_details, and the error holds the detail to ask for. - The agent opens a task and asks for exactly that detail. A person approves it in the portal.
- The agent calls the tool again and sends the approval in the header
X-LumoAuth-Jit-Token. - The approval names one invoice, so a refund of another invoice is refused.
The check is in the body of the tool. The tool therefore stays in the list of tools, and an agent can find out what to ask for.
Before you start
- An MCP server registered in LumoAuth. The setup script registers
Invoicesathttp://localhost:3000/mcp, with the scopesinvoices:readandinvoices:refund. - An agent whose capabilities do not cover a refund. The setup script creates
refund-desk-agentwith the single capabilityinvoices:read. - A person who decides, with the permission
jit.approve. The owner of an agent cannot decide its requests, so the setup script makes Maya Chen the owner. You can then approve as the administrator. - Check that your plan includes just-in-time permissions in the plans matrix.
| 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 | For the setup script only: an API key with the scopes admin:agents:read, admin:agents:write and admin:users:write. The server and the agent do not read 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, which is its agent ID (agt_…). The setup script prints 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/tools-that-need-approval/setup.mjs
setup.mjs
// Creates what the recipe needs: the registration of the MCP server, an agent
// that may read invoices, and a user who owns the agent. Run it again at any time.
//
// node mcp-servers/tools-that-need-approval/setup.mjs
//
// The API key needs the scopes admin:agents:read, admin:agents:write and
// admin:users:write.
import { randomBytes } from 'node:crypto';
import { call, 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'],
basic_scopes: ['invoices:read'],
// The agent of this recipe sends plain bearer tokens.
require_dpop: false,
});
const agent = await ensure('/admin/agents', (a) => a.name === 'refund-desk-agent', {
name: 'refund-desk-agent',
description: 'Reads invoices, and asks a person before it refunds one.',
identityType: 'client_secret',
// The agent may read invoices. A refund is outside its capabilities, so a
// person decides each request.
capabilities: ['invoices: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;
// The owner of an agent cannot decide its requests, and the agent belongs to
// the person who created it: you. Give it to another person, so that you can
// approve in the portal.
const owner = await ensure('/admin/users', (u) => u.email === 'maya.chen@example.com', {
email: 'maya.chen@example.com',
name: 'Maya Chen',
// The recipe never signs in as this user, so nobody needs the password.
password: `${randomBytes(18).toString('base64url')}#Aa1`,
emailVerified: true,
});
await call('PATCH', `/admin/agents/${agent.agentId}`, { ownerId: owner.id });
console.log(`MCP server ${server.name} (${server.resource_uri}) and agent ${agent.name} are ready. The owner of the agent is ${owner.email}.`);
printEnv({ LUMOAUTH_MCP_SERVER_ID: server.server_id, AGENT_CLIENT_ID: agent.agentId, AGENT_CLIENT_SECRET: secret });
LumoAuth shows a secret once. A second run of the setup script therefore asks for a new secret, and the old one stops at once.
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Each server and each agent ran against an organization, and a person approved in the portal. The line refund INV-1001: Refunded INV-1001 was not seen: both packages ignored the approval in the X-LumoAuth-Jit-Token header, so the call was refused again.
- Python
- Node.js
"""An MCP server on FastMCP with one tool that needs the approval of a person.
python mcp-servers/tools-that-need-approval/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, ensure_jit
mcp = FastMCP("Invoices", auth=LumoAuthProvider())
@mcp.tool
def list_invoices() -> list[dict]:
"""List the invoices."""
return [
{"id": "INV-1001", "customer": "Northwind Labs", "amount": 1200},
{"id": "INV-1002", "customer": "Acme", "amount": 300},
]
@mcp.tool
def refund(invoice_id: str) -> str:
"""Refund one invoice. Needs an approval for this invoice."""
# The caller needs a just-in-time permission for this type, this action
# and this invoice. Without it, the call fails with
# insufficient_authorization_details, and the error names the detail to
# ask for. The check is in the body, so the tool stays in the list.
ensure_jit("payment_initiation", actions=["refund"], identifier=invoice_id)
return f"Refunded {invoice_id}"
if __name__ == "__main__":
mcp.run(transport="http", port=int(os.environ.get("PORT", "3000")))
"""An agent calls a tool that needs approval, asks a person, and calls again.
python mcp-servers/tools-that-need-approval/python/agent.py
Start the server first, in another terminal. The program waits until a
person approves the request in the portal.
"""
import asyncio
import json
import os
import re
import requests
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport
from fastmcp.exceptions import ToolError
from lumoauth import JITContext, LumoAuthAgent
MCP_URL = os.environ.get("MCP_URL", "http://localhost:3000/mcp")
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
agent = LumoAuthAgent()
if not agent.authenticate():
raise SystemExit("The agent could not authenticate. Check its ID and its secret.")
# The normal token of the agent for this MCP server.
mcp_token = agent.get_mcp_token(MCP_URL)
async def refund(invoice_id: str, jit_token: str | None = None):
"""Calls the tool. Returns the result, or the detail that the server asks for."""
# The approval travels in its own header, next to the normal token.
headers = {"X-LumoAuth-Jit-Token": jit_token} if jit_token else {}
async with Client(StreamableHttpTransport(MCP_URL, auth=mcp_token, headers=headers)) as client:
try:
result = await client.call_tool("refund", {"invoice_id": invoice_id})
return result.content[0].text, None
except ToolError as error:
# The error text ends with the detail that the server asks for.
# The hint is one object, or a list with one object in older package versions.
hint = re.search(r"authorization_details_hint=(\[.*\]|\{.*\})", str(error))
parsed = json.loads(hint.group(1)) if hint else None
return None, parsed[0] if isinstance(parsed, list) else parsed
async def main() -> None:
# 0. 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"},
headers={"Accept": "application/json, text/event-stream"}, timeout=10)
print(f"no token: {answer.status_code} {answer.headers.get('WWW-Authenticate')}")
# 1. With the normal token, the server names the approval that it needs.
_, needed = await refund("INV-1001")
print(f"refund INV-1001: needs approval for {json.dumps(needed)}")
# 2. The agent asks for exactly that detail, for one task. A refund is
# outside its capabilities, so the call waits for a person.
jit = JITContext(agent)
task_id = jit.create_task(name="Refund invoice INV-1001", task_type="finance")
print(f"task: {task_id}")
print("request: waiting for a person")
request = jit.request_permission(needed, justification="Northwind Labs was charged twice for INV-1001.")
print(f"request: {request['status']}")
if request["status"] == "approved":
jit_token = jit.get_token(request["request_id"])
# 3. The same call, now with the approval.
result, needed = await refund("INV-1001", jit_token)
print(f"refund INV-1001: {result or 'refused, needs ' + json.dumps(needed)}")
# 4. The approval names one invoice. It does not cover another.
result, needed = await refund("INV-1002", jit_token)
print(f"refund INV-1002: {result or 'refused, needs ' + json.dumps(needed)}")
# The end of the task ends the permission: LumoAuth revokes the token.
jit.complete_task()
print("task: completed")
asyncio.run(main())
python mcp-servers/tools-that-need-approval/python/server.py
# In a second terminal:
python mcp-servers/tools-that-need-approval/python/agent.py
Compiles. Not run against an organization. The steps up to the approval ran against an organization. The call with the approval was refused: the server ignores the JIT token, which is a JWT for the organization and not an at+jwt token for the server.
// An MCP server on the MCP TypeScript SDK with one tool that needs the
// approval of a person.
//
// node mcp-servers/tools-that-need-approval/js/server.mjs
//
// It listens on http://localhost:3000/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 { InsufficientAuthorizationDetailsError, getCaller, lumoAuth, missingAuthorizationDetails } from '@lumoauth/mcp';
import { z } from 'zod';
// lumoAuth() reads LUMOAUTH_ORG_ID and LUMOAUTH_MCP_SERVER_ID.
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' });
server.registerTool('list_invoices', { description: 'List the invoices.' }, async () =>
text(JSON.stringify([
{ id: 'INV-1001', customer: 'Northwind Labs', amount: 1200 },
{ id: 'INV-1002', customer: 'Acme', amount: 300 },
])),
);
server.registerTool(
'refund',
{ description: 'Refund one invoice. Needs an approval for this invoice.', inputSchema: { invoice_id: z.string() } },
async ({ invoice_id: invoiceId }, extra) => {
// The caller needs a just-in-time permission for this type, this action
// and this invoice. Without it, the call fails with
// insufficient_authorization_details, and the error names the detail to
// ask for. The check is in the handler, so the tool stays in the list.
const needed = [{ type: 'payment_initiation', actions: ['refund'], identifier: invoiceId }];
const missing = missingAuthorizationDetails(needed, getCaller(extra).authorizationDetails);
if (missing.length > 0) throw new InsufficientAuthorizationDetailsError('refund', missing);
return text(`Refunded ${invoiceId}`);
},
);
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 ?? 3000));
// An agent calls a tool that needs approval, asks a person, and calls again.
//
// node mcp-servers/tools-that-need-approval/js/agent.mjs
//
// Start the server first, in another terminal. The program waits until a
// person approves the request in the portal.
import { LumoAgent } from '@lumoauth/agent';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
const mcpUrl = process.env.MCP_URL ?? 'http://localhost:3000/mcp';
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const agent = new LumoAgent();
// The normal token of the agent for this MCP server.
const mcpToken = await agent.mcp.getToken(mcpUrl);
/** Calls the tool. Returns the result, or the detail that the server asks for. */
async function refund(invoiceId, jitToken) {
const headers = { Authorization: `Bearer ${mcpToken}` };
// The approval travels in its own header, next to the normal token.
if (jitToken) headers['X-LumoAuth-Jit-Token'] = jitToken;
const client = new Client({ name: 'refund-desk-agent', version: '1.0.0' });
await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl), { requestInit: { headers } }));
try {
const result = await client.callTool({ name: 'refund', arguments: { invoice_id: invoiceId } });
const message = result.content[0].text;
if (!result.isError) return { result: message };
// The error text ends with the detail that the server asks for.
// The hint is one object, or a list with one object in older package versions.
const hint = /authorization_details_hint=(\[.*\]|\{.*\})/.exec(message);
const parsed = hint ? JSON.parse(hint[1]) : undefined;
return { needed: Array.isArray(parsed) ? parsed[0] : parsed };
} finally {
await client.close();
}
}
// 0. Without a token, the server answers 401 and says where its metadata is.
const answer = await fetch(mcpUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
});
console.log(`no token: ${answer.status} ${answer.headers.get('www-authenticate')}`);
// 1. With the normal token, the server names the approval that it needs.
const { needed } = await refund('INV-1001');
console.log(`refund INV-1001: needs approval for ${JSON.stringify(needed)}`);
// 2. The agent asks for exactly that detail, for one task. A refund is
// outside its capabilities, so the call waits for a person.
const task = await agent.jit.createTask({ name: 'Refund invoice INV-1001', type: 'finance' });
console.log(`task: ${task.taskId}`);
console.log('request: waiting for a person');
const request = await agent.jit.requestPermission(needed, {
justification: 'Northwind Labs was charged twice for INV-1001.',
});
console.log(`request: ${request.status}`);
if (request.status === 'approved') {
const jitToken = await agent.jit.getToken(request.request_id);
// 3. The same call, now with the approval.
const first = await refund('INV-1001', jitToken);
console.log(`refund INV-1001: ${first.result ?? `refused, needs ${JSON.stringify(first.needed)}`}`);
// 4. The approval names one invoice. It does not cover another.
const second = await refund('INV-1002', jitToken);
console.log(`refund INV-1002: ${second.result ?? `refused, needs ${JSON.stringify(second.needed)}`}`);
}
// The end of the task ends the permission: LumoAuth revokes the token.
await agent.jit.completeTask();
console.log('task: completed');
node mcp-servers/tools-that-need-approval/js/server.mjs
# In a second terminal:
node mcp-servers/tools-that-need-approval/js/agent.mjs
Compiles. Not run against an organization. The steps up to the approval ran against an organization. The call with the approval was refused: the server ignores the JIT token, which is a JWT for the organization and not an at+jwt token for the server.
The agent stops at "waiting for a person" until somebody decides:
- Open the portal and go to AI Agents, then Approvals.
- The tab Waiting shows the request of
refund-desk-agent, with the reason, the typepayment_initiationand the actionrefund. - Open the menu … at the end of the row, and click Approve.
Check the result
no token: 401 Bearer scope="invoices:read", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp"
refund INV-1001: needs approval for {"type":"payment_initiation","actions":["refund"],"identifier":"INV-1001"}
task: task_161d1e47d140a4284663bd00b24830d8
request: waiting for a person
request: approved
refund INV-1001: Refunded INV-1001
refund INV-1002: refused, needs {"type":"payment_initiation","actions":["refund"],"identifier":"INV-1002"}
task: completed
- The second line is the answer of the server to the normal token. It names the type, the action and the invoice.
- The last refund line shows the limit of the approval: it covers
INV-1001, and the server asks again forINV-1002. - In the portal, the tab Approved of the Approvals page shows the request and the name of the person who approved it.
Limits
- The approval is valid for 300 seconds here, and never longer than its task. When the agent completes the task, LumoAuth revokes the JIT token.
- The packages check the signature and the detail of the JIT token. They do not ask LumoAuth whether it was revoked. For a refund, also call token introspection on each call.
- A detail has a fixed form:
type,identifier, and the listsactions,privileges,locationsanddatatypes. An amount cannot be part of it. - To ask for approval without an MCP server, see Ask a person for a permission, for one task.