Skip to main content

Function: apiCall()

apiCall(method, url, options?): Promise<unknown>

Defined in: index.ts:355

Generic HTTP helper for use inside MCP tool handlers.

Accepts any full URL (third-party APIs, public APIs, etc.) or a path relative to the apiBaseUrl configured in createMcpRouter.

Headers configured via getApiHeaders in createMcpRouter are injected automatically into every request, allowing transparent forwarding of auth tokens, API keys, or any other header — without coupling this helper to a specific authentication scheme. Per-call options.headers take precedence over context-injected headers.

Parameters​

ParameterTypeDescription
methodstringHTTP method (e.g. 'GET', 'POST', 'PUT', 'DELETE')
urlstringFull URL or a path starting with / (appended to apiBaseUrl)
options?ApiCallOptionsOptional body and per-call header overrides

Returns​

Promise<unknown>

Parsed JSON response body

Examples​

Bearer token forwarding (configured once in `createMcpRouter`)

import { apiCall, createMcpRouter, McpServer } from '@ttoss/http-server-mcp';

// Tool handler – no manual auth wiring needed
mcpServer.registerTool('list-portfolios', { description: '...', inputSchema: {} }, async () => {
const data = await apiCall('GET', '/portfolios');
return { content: [{ type: 'text', text: JSON.stringify(data) }] };
});

const mcpRouter = createMcpRouter(mcpServer, {
apiBaseUrl: `http://localhost:${process.env.PORT}/api/v1`,
// Forward the caller's Bearer token to every apiCall
getApiHeaders: (ctx) => ({ Authorization: ctx.headers.authorization ?? '' }),
});

x-api-key forwarding

const mcpRouter = createMcpRouter(mcpServer, {
apiBaseUrl: 'https://internal-service/api',
getApiHeaders: (ctx) => ({
'x-api-key': ctx.headers['x-api-key'] as string,
}),
});

Third-party or public API (full URL, no context required)

const weather = await apiCall('GET', 'https://api.weather.com/current?city=Berlin');
const created = await apiCall('POST', 'https://api.example.com/items', {
body: { name: 'widget' },
headers: { Authorization: 'Bearer fixed-service-token' },
});