Skip to main content

An agent calls an MCP tool

An agent gets a token for one MCP server and calls a tool. The token works at that server only.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGoJavaC# / .NET

What it shows​

  1. A call without a token gets 401 and the challenge, which names the metadata of the server.
  2. The agent signs in with its client ID and secret, and asks LumoAuth for a token for the server. The address of the server is the resource of the request.
  3. The token names the server as its audience, so it works at that server only.
  4. The agent calls the tool whoami with the token.
  5. The tool refund needs the scope invoices:refund. The agent's capabilities do not cover it, so the server refuses the call.

No person signs in. The agent acts for itself, with the capabilities that it holds in the registry.

Before you start​

  • An MCP server that accepts tokens from LumoAuth. Start the server of Protect a server built on the MCP TypeScript SDK in another terminal. It listens on http://localhost:3000/mcp.
  • An agent with a client secret, whose capabilities cover invoices:read and not invoices:refund. The setup script creates invoice-assistant, and the registration of the server if it is missing.
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 and admin:agents:write. The agent itself needs no API key.
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.
MCP_URLOptional. The address of the MCP server, which is its resource URI. The default is http://localhost:3000/mcp.

The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.

node mcp-clients/an-agent-calls-a-tool/setup.mjs
setup.mjs
// Creates what the recipe needs: the registration of the MCP server, and an
// agent with a client secret that may read invoices. Run it again at any time.
//
// node mcp-clients/an-agent-calls-a-tool/setup.mjs
//
// The API key needs the scopes admin:agents:read and admin:agents:write.
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 agents of this recipe send plain bearer tokens.
require_dpop: false,
});

// The agent may read invoices. A refund is outside its capabilities.
const agent = await ensure('/admin/agents', (a) => a.name === 'invoice-assistant', {
name: 'invoice-assistant',
description: 'Answers questions about invoices through the Invoices MCP server.',
identityType: 'client_secret',
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;

console.log(`MCP server ${server.name} (${server.resource_uri}) and agent ${agent.name} are ready.`);
printEnv({ 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. Every version below was run against a LumoAuth organization. Each program ran against the server of the recipe for the MCP TypeScript SDK. The JavaScript and Python programs use an MCP client. The Go, Java and C# SDKs have no MCP client, so those programs send the JSON-RPC requests themselves.

mcp-clients/an-agent-calls-a-tool/js/agent.mjs
// An agent gets a token for one MCP server and calls its tools.
//
// node mcp-clients/an-agent-calls-a-tool/js/agent.mjs
//
// Start an MCP server first, in another terminal.
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';

// 1. 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')}`);

// 2. The agent asks LumoAuth for a token for this server. The address is the
// resource of the request, and it becomes the audience of the token.
// Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
const agent = new LumoAgent();
const token = await agent.mcp.getToken(mcpUrl);
const claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());
console.log(`token: audience ${claims.aud}`);

// 3. The agent calls a tool with the token.
const client = new Client({ name: 'invoice-assistant', version: '1.0.0' });
await client.connect(
new StreamableHTTPClientTransport(new URL(mcpUrl), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }),
);
const who = await client.callTool({ name: 'whoami', arguments: {} });
console.log(`whoami: ${who.content[0].text}`);

// 4. A refund needs a scope that the agent's capabilities do not cover.
const refund = await client.callTool({ name: 'refund', arguments: { invoiceId: 'INV-1001' } });
console.log(`refund: ${refund.isError ? 'refused: ' : ''}${refund.content[0].text}`);

await client.close();
node mcp-clients/an-agent-calls-a-tool/js/agent.mjs

Check the result​

Output
no token: 401 Bearer scope="invoices:read", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp"
token: audience http://localhost:3000/mcp
whoami: agent agt_f57ac14a650c1fb1
refund: refused: Tool 'refund' needs the scope invoices:refund.
  • The token: line shows the aud claim of the token. It is the resource URI of the server, exactly as the agent sent it.
  • whoami shows the agent ID. The server read it from the verified token.
  • The same token sent to another MCP server is refused there with 401, because the audience does not match.
  • The scopes of the token come from the agent's capabilities. Give the agent the capability invoices:refund in the portal, under AI Agents, Agents, and run the program again: the refund runs.

Limits​

  • The token is valid for one server. An agent that calls three servers asks for three tokens.
  • The Go, Java and .NET SDKs give the token, not an MCP client. Their programs send each call as one HTTP request, which a server without sessions accepts. For a full MCP client in those languages, use an MCP SDK and give it the token.
  • A token can be bound to a key of the agent: see An MCP server that accepts only bound tokens.
  • To call a tool for a person, the client signs the person in instead: see Write an MCP client that signs in.