Need more detail? Connect your coding agent to the full docs.

Skip to Content
AMIRILDocs

Wrap an API as a tool server

Put a small MCP server in front of an API that has none, so you can grant its actions to your agents as tools. About sixty lines of TypeScript.

When a service has an API and no tool server, and no connector platform covers it, wrap the API yourself. The tool server you write is a small web service. It lists tools and turns each tool call into a request to the API.

The example wraps a payments API with two tools, get_payment and issue_payment, using the official MCP SDK for TypeScript. You need Node 24 or later, which runs TypeScript files directly.

Write the server

Install the SDK and zod:

npm install @modelcontextprotocol/sdk zod

Save this as server.ts:

server.ts
// A tool server in front of a payments API: one read tool and one tool
// that moves money. Shown on /tool-servers/wrap-an-api and /tool-servers/move-a-tool.
import { createHash, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";

// API_URL and API_KEY reach the payments API. SERVER_KEY is the key Amiril sends to this server.
const { API_URL, API_KEY, SERVER_KEY } = process.env;
if (!API_URL || !API_KEY || !SERVER_KEY) throw new Error("Set API_URL, API_KEY and SERVER_KEY.");

/** One request to the API, returned to the agent as the tool's result. */
const call = async (method: string, path: string, body?: object) => {
  const response = await fetch(`${API_URL}${path}`, {
    method,
    headers: { authorization: `Bearer ${API_KEY}`, "content-type": "application/json" },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  return { content: [{ type: "text" as const, text: await response.text() }], isError: !response.ok };
};

const buildServer = () => {
  const server = new McpServer({ name: "payments", title: "Payments", version: "1.0.0" });
  server.registerTool(
    "get_payment",
    {
      title: "Get a payment",
      description: "Returns one payment by its id.",
      inputSchema: { payment_id: z.string() },
      annotations: { readOnlyHint: true },
    },
    ({ payment_id }) => call("GET", `/payments/${encodeURIComponent(payment_id)}`),
  );
  server.registerTool(
    "issue_payment",
    {
      title: "Issue a payment",
      description: "Pays an amount to a payee. A payment cannot be taken back.",
      inputSchema: { payee: z.string(), amount: z.number().positive() },
      annotations: { destructiveHint: true },
    },
    ({ payee, amount }) => call("POST", "/payments", { payee, amount }),
  );
  return server;
};

// Hashing both sides lets the comparison take the same time whatever was sent.
const digest = (value: string) => createHash("sha256").update(value).digest();
const expected = digest(`Bearer ${SERVER_KEY}`);

createServer(async (req, res) => {
  if (!timingSafeEqual(digest(req.headers.authorization ?? ""), expected)) return void res.writeHead(401).end();
  if (req.url !== "/mcp" || req.method !== "POST") return void res.writeHead(405).end();
  const chunks: Buffer[] = [];
  for await (const chunk of req) chunks.push(chunk as Buffer);
  // A new server and transport for each request, so nothing is kept between calls.
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
  res.on("close", () => void transport.close());
  await buildServer().connect(transport);
  await transport.handleRequest(req, res, JSON.parse(Buffer.concat(chunks).toString()));
}).listen(Number(process.env.PORT ?? 3000));

The server reads three variables. API_URL and API_KEY reach the payments API, and Amiril never sees that key. SERVER_KEY is a key of the server's own. Amiril sends it in the Authorization header as Bearer followed by the key. The server answers 401 to any request that lacks it.

How the example shapes its tools

The example gives each action its own tool. Amiril grants an agent single tools, so a tool that could both read and pay would have to be granted whole.

Each tool also says what it does to data. get_payment sets readOnlyHint: true and issue_payment sets destructiveHint: true. Amiril sets each tool's access level from these hints, as check the name, slug and access explains.

The model reads each description to decide when to call the tool. That is why the description of issue_payment says a payment cannot be taken back.

Run it on your machine

Create the server's key:

openssl rand -base64 32

Use a new value, never the API's key or a gateway token. Start the server with it:

API_URL=https://payments.example.com API_KEY=sk_live_your_api_key SERVER_KEY=the-value-you-created node server.ts

The server listens on port 3000 and answers MCP requests at /mcp. A request without the key is refused:

curl -i -X POST http://localhost:3000/mcp
HTTP/1.1 401 Unauthorized

With the key, the server lists its two tools. Put your SERVER_KEY value after Bearer:

curl -s -X POST http://localhost:3000/mcp \
  -H "Authorization: Bearer the-value-you-created" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | grep -o '"name":"[a-z_]*"'
"name":"get_payment"
"name":"issue_payment"

Host it and register it

Deploy the server with the same three variables, anywhere that gives it an HTTPS address. Keep both keys in your host's secret store, and use a different SERVER_KEY in each environment.

Register the server in Amiril as connect an MCP server with an API key shows. Use https://your-host/mcp as the Server URL. In Key or token, enter Bearer, a space and the value of SERVER_KEY.

When you select Test connection, Amiril names the server Payments and gives it the slug payments. get_payment arrives as Read and issue_payment as Destructive. Select Add 2 tools.

Grant the tools to an agent on its Access tab.

When you add a tool to the server later, Amiril picks it up on its next sync. That happens every 15 minutes, or at once when you select Sync now on the server's page.

Next steps

Last updated on