Skip to main content

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.

RecipeDraftView source
This page is a draft. The code exists, and not all of it has been run for this page yet. The page says what was checked.
Works with
PythonJavaScript / TypeScriptFastMCPMCP TypeScript SDK
Standards
RFC 9396

What it shows​

  1. The tool refund names the approval that it needs: the type payment_initiation, the action refund, and the invoice of the call.
  2. 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.
  3. The agent opens a task and asks for exactly that detail. A person approves it in the portal.
  4. The agent calls the tool again and sends the approval in the header X-LumoAuth-Jit-Token.
  5. 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 Invoices at http://localhost:3000/mcp, with the scopes invoices:read and invoices:refund.
  • An agent whose capabilities do not cover a refund. The setup script creates refund-desk-agent with the single capability invoices: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.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYFor 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_IDThe ID of the registered MCP server (mcp_…). The setup script prints it. The server reads it.
AGENT_CLIENT_IDThe client ID of the agent, which is its agent ID (agt_…). The setup script prints it.
AGENT_CLIENT_SECRETThe 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.

mcp-servers/tools-that-need-approval/python/server.py
"""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")))
mcp-servers/tools-that-need-approval/python/agent.py
"""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.

The agent stops at "waiting for a person" until somebody decides:

  1. Open the portal and go to AI Agents, then Approvals.
  2. The tab Waiting shows the request of refund-desk-agent, with the reason, the type payment_initiation and the action refund.
  3. Open the menu … at the end of the row, and click Approve.

Check the result​

Output
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 for INV-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 lists actions, privileges, locations and datatypes. 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.