Skip to main content

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.

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
JavaScript / TypeScriptPythonMCP TypeScript SDKFastMCP

What it shows​

  1. The tool my_github_issues runs only when a person stands behind the call: the person, or an agent that acts for the person.
  2. The tool asks the Token Vault of LumoAuth for a GitHub token. The packages send the person from the verified token of the call.
  3. The vault returns a short-lived token for that person's GitHub account, and the tool calls the GitHub API with it.
  4. 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-mcp may act for users, which the vault requires for the token of a person.
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_KEYAn 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_IDThe ID of the registered MCP server (mcp_…). The setup script prints it.
AGENT_CLIENT_IDThe agent ID of engineering-mcp, the agent that the server signs in as. The setup script prints it.
AGENT_CLIENT_SECRETThe client secret of engineering-mcp. The setup script prints it.
CONNECTION_IDThe ID of the GitHub connection (conn_…), from its page in the portal.
MCP_AGENT_IDThe agent ID of triage-bot, for the test client. The setup script prints it.
MCP_CLIENT_IDThe 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.

  1. Go to AI Agents, then Agents, and open the tab Connections. Click Add connection.
  2. Enter a Connection name, for example GitHub, and choose GitHub as the Provider template.
  3. Under Whose account is used, choose User-delegated.
  4. Paste the Client ID and the Client secret of your GitHub app. Leave Scopes empty to use the defaults of the template.
  5. Under Agent access, keep Only selected agents, and choose engineering-mcp under Permitted agents. Click Add Connection.
  6. The page of the connection shows the Connection ID (conn_…) and the Callback URL. Put the ID in CONNECTION_ID, and register the callback URL in the settings of your GitHub app.

Each person links their own account:

  1. Open Accounts agents can use in your account, at https://app.lumoauth.dev/account/connections.
  2. 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.

mcp-servers/outside-apis-from-a-tool/js/server.mjs
// 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));
mcp-servers/outside-apis-from-a-tool/js/check.mjs
// 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.

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​

Output
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 of triage-bot, which acts for nobody. The JavaScript server refuses it with the text above. The Python server hides the tool, so the answer is Unknown 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 answers 403 delegation_not_allowed.
  • Unlink on the account page stops the access at once. The vault then answers 404 or 409, 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.