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.
What it shows
- A call without a token gets
401and the challenge, which names the metadata of the server. - 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.
- The token names the server as its audience, so it works at that server only.
- The agent calls the tool
whoamiwith the token. - The tool
refundneeds the scopeinvoices: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:readand notinvoices:refund. The setup script createsinvoice-assistant, and the registration of the server if it is missing.
| 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 and admin:agents:write. The agent itself needs no API key. |
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. |
MCP_URL | Optional. 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.
- Node.js
- Python
- Go
- Java
- C#
// 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
"""An agent gets a token for one MCP server and calls its tools.
python mcp-clients/an-agent-calls-a-tool/python/agent.py
Start an MCP server first, in another terminal.
"""
import asyncio
import base64
import json
import os
import requests
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport
from lumoauth import LumoAuthAgent
MCP_URL = os.environ.get("MCP_URL", "http://localhost:3000/mcp")
# 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"},
headers={"Accept": "application/json, text/event-stream"}, timeout=10)
print(f"no token: {answer.status_code} {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.
agent = LumoAuthAgent()
token = agent.get_mcp_credential(MCP_URL).access_token
payload = token.split(".")[1]
claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
print(f"token: audience {claims['aud']}")
async def main() -> None:
# 3. The agent calls a tool with the token.
async with Client(StreamableHttpTransport(MCP_URL, auth=token)) as client:
who = await client.call_tool("whoami", {})
print(f"whoami: {who.content[0].text}")
# 4. A refund needs a scope that the agent's capabilities do not cover.
refund = await client.call_tool("refund", {"invoiceId": "INV-1001"}, raise_on_error=False)
print(f"refund: {'refused: ' if refund.is_error else ''}{refund.content[0].text}")
asyncio.run(main())
python mcp-clients/an-agent-calls-a-tool/python/agent.py
// An agent gets a token for one MCP server and calls its tools.
//
// go run ./mcp-clients/an-agent-calls-a-tool/go
//
// Start an MCP server first, in another terminal.
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
var mcpURL = "http://localhost:3000/mcp"
// call sends one JSON-RPC request. The Go SDK has no MCP client, so the
// agent speaks the stateless form of MCP over HTTP: one POST for each call.
func call(token, method string, params any) (*http.Response, map[string]any) {
body, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
request, _ := http.NewRequest(http.MethodPost, mcpURL, bytes.NewReader(body))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json, text/event-stream")
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
raw, _ := io.ReadAll(response.Body)
// A server may answer with JSON or with a stream of events. In a stream,
// the answer is the data of the event.
text := string(raw)
if i := strings.LastIndex(text, "data: "); i >= 0 {
text = strings.TrimSpace(text[i+len("data: "):])
}
var message map[string]any
json.Unmarshal([]byte(text), &message)
return response, message
}
func toolText(message map[string]any) (string, bool) {
result, _ := message["result"].(map[string]any)
content, _ := result["content"].([]any)
isError, _ := result["isError"].(bool)
if len(content) == 0 {
return fmt.Sprint(message["error"]), true
}
return content[0].(map[string]any)["text"].(string), isError
}
func main() {
ctx := context.Background()
if value := os.Getenv("MCP_URL"); value != "" {
mcpURL = value
}
// 1. Without a token, the server answers 401 and says where its metadata is.
response, _ := call("", "tools/list", map[string]any{})
fmt.Printf("no token: %d %s\n", response.StatusCode, response.Header.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.
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
token, err := agent.MCPToken(ctx, mcpURL)
if err != nil {
log.Fatal(err)
}
payload, _ := base64.RawURLEncoding.DecodeString(strings.Split(token, ".")[1])
var claims struct {
Aud any `json:"aud"`
}
json.Unmarshal(payload, &claims)
fmt.Printf("token: audience %v\n", claims.Aud)
// 3. The agent calls a tool with the token.
_, who := call(token, "tools/call", map[string]any{"name": "whoami", "arguments": map[string]any{}})
text, _ := toolText(who)
fmt.Printf("whoami: %s\n", text)
// 4. A refund needs a scope that the agent's capabilities do not cover.
_, refund := call(token, "tools/call", map[string]any{"name": "refund", "arguments": map[string]any{"invoiceId": "INV-1001"}})
text, refused := toolText(refund)
if refused {
text = "refused: " + text
}
fmt.Printf("refund: %s\n", text)
}
go run ./mcp-clients/an-agent-calls-a-tool/go
// An agent gets a token for one MCP server and calls its tools.
//
// java -cp "java/lib/*" mcp-clients/an-agent-calls-a-tool/java/Agent.java
//
// Start an MCP server first, in another terminal.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.lumoauth.LumoAgent;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.Map;
public class Agent {
static final String MCP_URL = System.getenv().getOrDefault("MCP_URL", "http://localhost:3000/mcp");
static final ObjectMapper JSON = new ObjectMapper();
static final HttpClient HTTP = HttpClient.newHttpClient();
// One JSON-RPC request. The Java SDK has no MCP client, so the agent speaks
// the stateless form of MCP over HTTP: one POST for each call.
static HttpResponse<String> call(String token, String method, Object params) throws Exception {
String body = JSON.writeValueAsString(Map.of("jsonrpc", "2.0", "id", 1, "method", method, "params", params));
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(MCP_URL))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.POST(HttpRequest.BodyPublishers.ofString(body));
if (token != null) request.header("Authorization", "Bearer " + token);
return HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString());
}
// A server may answer with JSON or with a stream of events. In a stream,
// the answer is the data of the event.
static String toolText(HttpResponse<String> response) throws Exception {
String text = response.body();
int data = text.lastIndexOf("data: ");
if (data >= 0) text = text.substring(data + "data: ".length()).trim();
JsonNode result = JSON.readTree(text).path("result");
String value = result.path("content").path(0).path("text").asText();
return result.path("isError").asBoolean() ? "refused: " + value : value;
}
public static void main(String[] args) throws Exception {
// 1. Without a token, the server answers 401 and says where its metadata is.
HttpResponse<String> answer = call(null, "tools/list", Map.of());
System.out.printf("no token: %d %s%n", answer.statusCode(),
answer.headers().firstValue("WWW-Authenticate").orElse(""));
// 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.
LumoAgent agent = LumoAgent.fromEnvironment();
String token = agent.mcpToken(MCP_URL);
JsonNode claims = JSON.readTree(Base64.getUrlDecoder().decode(token.split("\\.")[1]));
System.out.printf("token: audience %s%n", claims.path("aud").asText());
// 3. The agent calls a tool with the token.
System.out.printf("whoami: %s%n", toolText(call(token, "tools/call", Map.of("name", "whoami", "arguments", Map.of()))));
// 4. A refund needs a scope that the agent's capabilities do not cover.
System.out.printf("refund: %s%n", toolText(call(token, "tools/call",
Map.of("name", "refund", "arguments", Map.of("invoiceId", "INV-1001")))));
}
}
java -cp "java/lib/*" mcp-clients/an-agent-calls-a-tool/java/Agent.java
#:package LumoAuth@1.7.0
#:property PublishAot=false
// An agent gets a token for one MCP server and calls its tools.
//
// dotnet run mcp-clients/an-agent-calls-a-tool/csharp/Agent.cs
//
// Start an MCP server first, in another terminal.
using System.Buffers.Text;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using LumoAuth;
var mcpUrl = Environment.GetEnvironmentVariable("MCP_URL") ?? "http://localhost:3000/mcp";
using var http = new HttpClient();
// One JSON-RPC request. The .NET SDK has no MCP client, so the agent speaks
// the stateless form of MCP over HTTP: one POST for each call.
async Task<HttpResponseMessage> Call(string? token, string method, object parameters)
{
var body = JsonSerializer.Serialize(new { jsonrpc = "2.0", id = 1, method, @params = parameters });
var request = new HttpRequestMessage(HttpMethod.Post, mcpUrl) { Content = new StringContent(body, Encoding.UTF8, "application/json") };
request.Headers.Accept.ParseAdd("application/json, text/event-stream");
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
return await http.SendAsync(request);
}
// A server may answer with JSON or with a stream of events. In a stream, the
// answer is the data of the event.
async Task<string> ToolText(HttpResponseMessage response)
{
var text = await response.Content.ReadAsStringAsync();
var data = text.LastIndexOf("data: ", StringComparison.Ordinal);
if (data >= 0) text = text[(data + "data: ".Length)..].Trim();
var result = JsonDocument.Parse(text).RootElement.GetProperty("result");
var value = result.GetProperty("content")[0].GetProperty("text").GetString();
var refused = result.TryGetProperty("isError", out var isError) && isError.GetBoolean();
return refused ? $"refused: {value}" : value!;
}
// 1. Without a token, the server answers 401 and says where its metadata is.
var answer = await Call(null, "tools/list", new { });
Console.WriteLine($"no token: {(int)answer.StatusCode} {string.Join(", ", answer.Headers.WwwAuthenticate)}");
// 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.
using var agent = LumoAgent.FromEnvironment();
var token = await agent.McpTokenAsync(mcpUrl);
var claims = JsonDocument.Parse(Base64Url.DecodeFromChars(token.Split('.')[1])).RootElement;
Console.WriteLine($"token: audience {claims.GetProperty("aud")}");
// 3. The agent calls a tool with the token.
Console.WriteLine($"whoami: {await ToolText(await Call(token, "tools/call", new { name = "whoami", arguments = new { } }))}");
// 4. A refund needs a scope that the agent's capabilities do not cover.
Console.WriteLine($"refund: {await ToolText(await Call(token, "tools/call", new { name = "refund", arguments = new { invoiceId = "INV-1001" } }))}");
dotnet run mcp-clients/an-agent-calls-a-tool/csharp/Agent.cs
Check the result
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 theaudclaim of the token. It is the resource URI of the server, exactly as the agent sent it. whoamishows 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:refundin 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.