Call an outside API from a tool
Inside an MCP tool, get a token for the caller's GitHub or Google account from LumoAuth, and call that API.
What it shows
- The tool
my_github_issuesruns only when a person stands behind the call: the person, or an agent that acts for the person. - The tool asks the Token Vault of LumoAuth for a GitHub token. The packages send the person from the verified token of the call.
- The vault returns a short-lived token for that person's GitHub account, and the tool calls the GitHub API with it.
- When the person has not linked a GitHub account, the tool says where to link it.
The MCP server stores no GitHub credential, and it never sends the person's LumoAuth token to GitHub. The vault answers only to an agent, so the server signs in as its own agent, engineering-mcp.
Before you start
- Check that your plan includes agent connections in the plans matrix.
- An OAuth app at GitHub, with its client ID and client secret.
- The registration of the server, the agents and the application of the test client. The setup script creates them.
engineering-mcpmay act for users, which the vault requires for the token of a person.
| 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. |
AGENT_CLIENT_ID | The agent ID of engineering-mcp, the agent that the server signs in as. The setup script prints it. |
AGENT_CLIENT_SECRET | The client secret of engineering-mcp. The setup script prints it. |
CONNECTION_ID | The ID of the GitHub connection (conn_…), from its page in the portal. |
MCP_AGENT_ID | The agent ID of triage-bot, for the test client. The setup script prints it. |
MCP_CLIENT_ID | The client ID of the application "Engineering MCP client", for the test client. 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/outside-apis-from-a-tool/setup.mjs
setup.mjs
// Creates what the recipe needs: the registration of the MCP server, the
// agent that the server uses to reach the Token Vault, a test agent, and a
// public application for the MCP client. Run it again at any time.
//
// node mcp-servers/outside-apis-from-a-tool/setup.mjs
//
// The API key needs the scopes admin:agents:read, admin:agents:write,
// admin:clients:read and admin:clients: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:3004/mcp';
const server = await ensure('/admin/mcp/servers', (s) => s.resource_uri === resource, {
name: 'Engineering',
description: 'Reads the GitHub issues of the person who calls.',
resource_uri: resource,
endpoint_url: resource,
scopes_supported: ['issues:read'],
basic_scopes: ['issues:read'],
// The clients of this recipe send plain bearer tokens.
require_dpop: false,
});
// The Token Vault answers only to an agent. The MCP server signs in as this
// agent. It may act for users, so it may ask for the token of a person.
const serverAgent = await ensure('/admin/agents', (a) => a.name === 'engineering-mcp', {
name: 'engineering-mcp',
description: 'The Engineering MCP server. Fetches GitHub tokens for the people who call its tools.',
identityType: 'client_secret',
capabilities: ['issues:read'],
canActOnBehalfOfUsers: true,
});
// 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 =
serverAgent.clientSecret ??
(await call('POST', `/admin/agents/${serverAgent.agentId}/rotate-credentials`)).data.clientSecret;
// An agent that calls the tool by itself, with nobody to act for.
const triageBot = await ensure('/admin/agents', (a) => a.name === 'triage-bot', {
name: 'triage-bot',
description: 'Sorts new issues. Acts for nobody.',
identityType: 'client_secret',
capabilities: ['issues:read'],
});
// The MCP client is a public application: it has no secret and uses PKCE.
const redirectUri = process.env.MCP_CLIENT_REDIRECT_URI ?? 'http://localhost:8765/callback';
const client = await ensure('/admin/clients', (c) => c.name === 'Engineering MCP client', {
name: 'Engineering MCP client',
isConfidential: false,
redirectUris: [redirectUri],
scopes: ['openid', 'profile', 'email', 'offline_access', 'issues:read'],
});
console.log(`MCP server ${server.name} (${server.resource_uri}), the agents ${serverAgent.name} and ${triageBot.name}, and the application "${client.name}" are ready.`);
printEnv({
LUMOAUTH_MCP_SERVER_ID: server.server_id,
AGENT_CLIENT_ID: serverAgent.agentId,
AGENT_CLIENT_SECRET: secret,
MCP_AGENT_ID: triageBot.agentId,
MCP_CLIENT_ID: client.clientId,
});
Then create the connection in the portal. The Admin API has no call for it.
- Go to AI Agents, then Agents, and open the tab Connections. Click Add connection.
- Enter a Connection name, for example
GitHub, and chooseGitHubas the Provider template. - Under Whose account is used, choose User-delegated.
- Paste the Client ID and the Client secret of your GitHub app. Leave Scopes empty to use the defaults of the template.
- Under Agent access, keep Only selected agents, and choose
engineering-mcpunder Permitted agents. Click Add Connection. - The page of the connection shows the Connection ID (
conn_…) and the Callback URL. Put the ID inCONNECTION_ID, and register the callback URL in the settings of your GitHub app.
Each person links their own account:
- Open Accounts agents can use in your account, at
https://app.lumoauth.dev/account/connections. - Under Agents that may use this account once linked, tick
engineering-mcp, and click Link account. Approve on the GitHub page.
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Each server ran with each test client, and a person signed in. LumoAuth answered that the person has not linked a GitHub account, and the tool said where to link it. The call to GitHub with a linked account was not run.
- Node.js
- Python
// An MCP server on the MCP TypeScript SDK with a tool that calls GitHub for
// the person who calls it.
//
// node mcp-servers/outside-apis-from-a-tool/js/server.mjs
//
// It listens on http://localhost:3004/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 { LumoAgent, LumoAuthApiError } from '@lumoauth/agent';
import { lumoAuth } from '@lumoauth/mcp';
// lumoAuth() reads LUMOAUTH_ORG_ID and LUMOAUTH_MCP_SERVER_ID.
const auth = lumoAuth();
await auth.ready();
// The Token Vault answers only to an agent. The server signs in as its own
// agent, with AGENT_CLIENT_ID and AGENT_CLIENT_SECRET. LumoAgent renews the
// token before it expires.
const agent = new LumoAgent();
const connectionId = process.env.CONNECTION_ID;
const linkPage = `${(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev').replace(/\/+$/, '')}/account/connections`;
const text = (value) => ({ content: [{ type: 'text', text: value }] });
async function myGithubIssues(extra) {
let github;
try {
// The vault reads the person from the verified token of this call, and
// returns a short-lived GitHub token of that person.
const vault = lumoAuth({ agentToken: await agent.getAccessToken() });
github = await vault.vaultToken(connectionId, extra);
} catch (error) {
const code = error instanceof LumoAuthApiError ? error.body?.error : undefined;
if (['grant_not_found', 'grant_revoked', 'grant_expired', 'refresh_failed'].includes(code)) {
return text(`Link your GitHub account first, under Accounts agents can use: ${linkPage}`);
}
throw error;
}
const response = await fetch('https://api.github.com/issues', {
headers: { ...github.headers(), Accept: 'application/vnd.github+json' },
});
if (!response.ok) throw new Error(`GitHub answered ${response.status}`);
const issues = (await response.json()).map((i) => `${i.repository.full_name}#${i.number} ${i.title}`);
return text(issues.join('\n') || 'No open issues.');
}
function buildServer() {
const server = new McpServer({ name: 'engineering', version: '1.0.0' });
// A person must stand behind the call: the person, or an agent that acts
// for the person. An agent that acts for nobody is refused.
server.registerTool(
'my_github_issues',
{ description: 'List the open GitHub issues that are assigned to you.' },
auth.guard('my_github_issues', myGithubIssues, { users: 'delegated' }),
);
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 ?? 3004));
// Calls the server three ways: without a token, as an agent that acts for
// nobody, and as a person who signs in.
//
// node mcp-servers/outside-apis-from-a-tool/js/check.mjs
//
// Start the server first, in another terminal. The program prints an
// address. Open it in a browser, sign in and approve.
import http from 'node:http';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
const mcpUrl = process.env.MCP_URL ?? 'http://localhost:3004/mcp';
const redirectUri = process.env.MCP_CLIENT_REDIRECT_URI ?? 'http://localhost:8765/callback';
const lumoauthUrl = (process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev').replace(/\/+$/, '');
const api = `${lumoauthUrl}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
// 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. A test token of the agent triage-bot, from the Admin API. The agent acts
// for nobody, so the tool is not for it.
const issued = await fetch(`${api}/admin/agents/${process.env.MCP_AGENT_ID}/token`, {
method: 'POST',
headers: { 'X-API-Key': process.env.LUMOAUTH_API_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ resource: mcpUrl, expiresIn: 300 }),
});
const agentToken = (await issued.json()).data.accessToken;
const bot = new Client({ name: 'triage-bot', version: '1.0.0' });
await bot.connect(
new StreamableHTTPClientTransport(new URL(mcpUrl), { requestInit: { headers: { Authorization: `Bearer ${agentToken}` } } }),
);
const forBot = await bot.callTool({ name: 'my_github_issues' }).catch((error) => ({ isError: true, content: [{ text: error.message }] }));
console.log(`agent: ${forBot.isError ? 'refused' : 'allowed'}: ${forBot.content[0].text}`);
await bot.close();
// 3. A person signs in. The browser comes back to this address with the code.
let deliverCode;
const callback = http.createServer((req, res) => {
const url = new URL(req.url, redirectUri);
if (url.pathname !== new URL(redirectUri).pathname) return res.writeHead(404).end();
res.end('You can close this window.');
deliverCode(url.searchParams.get('code'));
});
callback.listen(Number(new URL(redirectUri).port));
const code = new Promise((resolve) => (deliverCode = resolve));
// What the MCP SDK needs for the authorization code flow with PKCE. This
// client keeps everything in memory.
let tokens;
let codeVerifier;
const provider = {
redirectUrl: redirectUri,
clientMetadata: { client_name: 'Engineering MCP client', redirect_uris: [redirectUri] },
clientInformation: () => ({ client_id: process.env.MCP_CLIENT_ID }),
tokens: () => tokens,
saveTokens: (saved) => (tokens = saved),
saveCodeVerifier: (verifier) => (codeVerifier = verifier),
codeVerifier: () => codeVerifier,
redirectToAuthorization: (url) => console.log(`person: open ${url}`),
};
const person = new Client({ name: 'engineering-mcp-client', version: '1.0.0' });
let transport = new StreamableHTTPClientTransport(new URL(mcpUrl), { authProvider: provider });
try {
await person.connect(transport);
} catch (error) {
if (!(error instanceof UnauthorizedError)) throw error;
await transport.finishAuth(await code);
// A transport starts only once, so the client connects with a new one.
transport = new StreamableHTTPClientTransport(new URL(mcpUrl), { authProvider: provider });
await person.connect(transport);
}
const forPerson = await person.callTool({ name: 'my_github_issues' });
console.log(`person: ${forPerson.content[0].text}`);
await person.close();
callback.close();
node mcp-servers/outside-apis-from-a-tool/js/server.mjs
# In a second terminal:
node mcp-servers/outside-apis-from-a-tool/js/check.mjs
Compiles. Not run against an organization. The LumoAuth side ran against an organization, up to the answer that the person has not linked GitHub. No GitHub OAuth app was available, so no account was linked and GitHub was not called.
"""An MCP server on FastMCP with a tool that calls GitHub for the person who calls it.
python mcp-servers/outside-apis-from-a-tool/python/server.py
It listens on http://localhost:3004/mcp, the resource URI of the registration.
"""
import os
import requests
from fastmcp import FastMCP
from lumoauth import LumoAuthAgent
from lumoauth.errors import LumoAuthApiError
from lumoauth_fastmcp import LumoAuthProvider, require_user
# Reads LUMOAUTH_ORG_ID and LUMOAUTH_MCP_SERVER_ID.
auth = LumoAuthProvider()
mcp = FastMCP("Engineering", auth=auth)
# The Token Vault answers only to an agent. The server signs in as its own
# agent, with AGENT_CLIENT_ID and AGENT_CLIENT_SECRET, and renews the token
# when it expires.
agent = LumoAuthAgent()
def agent_token() -> str:
agent.ensure_authenticated()
return agent.access_token
vault = auth.vault(token_provider=agent_token)
CONNECTION_ID = os.environ["CONNECTION_ID"]
LINK_PAGE = os.environ.get("LUMOAUTH_URL", "https://app.lumoauth.dev").rstrip("/") + "/account/connections"
# A person must stand behind the call: the person, or an agent that acts for
# the person. An agent that acts for nobody does not see the tool.
@mcp.tool(auth=require_user(allow_delegation=True))
def my_github_issues() -> str:
"""List the open GitHub issues that are assigned to you."""
try:
# The vault reads the person from the verified token of this call, and
# returns a short-lived GitHub token of that person.
github = vault.get_token(CONNECTION_ID)
except LumoAuthApiError as error:
if error.code in ("grant_not_found", "grant_revoked", "grant_expired", "refresh_failed"):
return f"Link your GitHub account first, under Accounts agents can use: {LINK_PAGE}"
raise
response = requests.get(
"https://api.github.com/issues",
headers={**github.headers(), "Accept": "application/vnd.github+json"},
timeout=10,
)
response.raise_for_status()
issues = [f"{i['repository']['full_name']}#{i['number']} {i['title']}" for i in response.json()]
return "\n".join(issues) or "No open issues."
if __name__ == "__main__":
mcp.run(transport="http", port=int(os.environ.get("PORT", "3004")))
"""Calls the server three ways: without a token, as an agent that acts for
nobody, and as a person who signs in.
python mcp-servers/outside-apis-from-a-tool/python/check.py
Start the server first, in another terminal. Your browser opens on the
sign-in page of LumoAuth. Sign in and approve.
"""
import asyncio
import os
from urllib.parse import urlparse
import requests
from fastmcp import Client
from fastmcp.client.auth import OAuth
from fastmcp.client.transports import StreamableHttpTransport
from fastmcp.exceptions import ToolError
MCP_URL = os.environ.get("MCP_URL", "http://localhost:3004/mcp")
REDIRECT_URI = os.environ.get("MCP_CLIENT_REDIRECT_URI", "http://localhost:8765/callback")
LUMOAUTH_URL = os.environ.get("LUMOAUTH_URL", "https://app.lumoauth.dev").rstrip("/")
API = f"{LUMOAUTH_URL}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1"
async def call(auth) -> str:
async with Client(StreamableHttpTransport(MCP_URL, auth=auth)) as client:
try:
result = await client.call_tool("my_github_issues")
return result.content[0].text
except ToolError as error:
return f"refused: {error}"
async def main() -> None:
# 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. A test token of the agent triage-bot, from the Admin API. The agent
# acts for nobody, so the tool is not for it.
issued = requests.post(
f"{API}/admin/agents/{os.environ['MCP_AGENT_ID']}/token",
headers={"X-API-Key": os.environ["LUMOAUTH_API_KEY"]},
json={"resource": MCP_URL, "expiresIn": 300},
timeout=10,
)
issued.raise_for_status()
print(f"agent: {await call(issued.json()['data']['accessToken'])}")
# 3. A person signs in. FastMCP runs the authorization code flow with
# PKCE, opens the browser, and receives the code on the callback port.
oauth = OAuth(client_id=os.environ["MCP_CLIENT_ID"], callback_port=urlparse(REDIRECT_URI).port)
print(f"person: {await call(oauth)}")
asyncio.run(main())
python mcp-servers/outside-apis-from-a-tool/python/server.py
# In a second terminal:
python mcp-servers/outside-apis-from-a-tool/python/check.py
Compiles. Not run against an organization. The LumoAuth side ran against an organization, up to the answer that the person has not linked GitHub. No GitHub OAuth app was available, so no account was linked and GitHub was not called.
The test client prints an address after person: open. Open it in a browser, sign in and approve. The Python client opens the browser itself.
Check the result
no token: 401 Bearer scope="issues:read", resource_metadata="http://localhost:3004/.well-known/oauth-protected-resource/mcp"
agent: refused: Tool 'my_github_issues' can only be run by a person.
person: open https://app.lumoauth.dev/orgs/acme-corp/api/v1/oauth/authorize?response_type=code&client_id=client_1848a861bfdc33d5554f68436b0debed&…
person: Link your GitHub account first, under Accounts agents can use: https://app.lumoauth.dev/account/connections
agent:is the call oftriage-bot, which acts for nobody. The JavaScript server refuses it with the text above. The Python server hides the tool, so the answer isUnknown tool.- The last line is the answer before the person links GitHub. Link the account as described above, and run the client again: the line lists the open issues that are assigned to the person.
- On the page of the connection in the portal, the table Grants shows the linked account and the agents that may use it.
- In Audit logs, each token that the vault returns adds an event
vault.token_issued, with the agent, the connection and the person. It never holds the token.
Limits
- The vault answers only to an agent, with a token that carries all of the agent's capabilities. The token of an application is refused.
- The person decides which agents may use the linked account. If the person did not tick
engineering-mcp, the vault answers403 delegation_not_allowed. - Unlink on the account page stops the access at once. The vault then answers
404or409, and the tool asks the person to link again. - The packages keep a vault token in memory until 30 seconds before it expires. The vault returns at most 60 tokens a minute to one agent.