# 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](/tool-servers/connectors) 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 [#write-the-server]

Install the SDK and zod:

```package-install
@modelcontextprotocol/sdk zod
```

Save this as `server.ts`:

```ts title="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 [#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](/tool-servers#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 [#run-it-on-your-machine]

Create the server's key:

```bash
openssl rand -base64 32
```

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

```bash
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:

```bash
curl -i -X POST http://localhost:3000/mcp
```

```text
HTTP/1.1 401 Unauthorized
```

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

```bash
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_]*"'
```

```text
"name":"get_payment"
"name":"issue_payment"
```

## Host it and register it [#host-it-and-register-it]

<Steps>
<Step>
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.
</Step>

<Step>
Register the server in Amiril as [connect an MCP server with an API key](/tool-servers/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`.
</Step>

<Step>
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**.
</Step>

<Step>
[Grant the tools to an agent](/agents/access) on its **Access** tab.
</Step>
</Steps>

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

- [Add a tool server](https://docs.amiril.ai/tool-servers.md): Register the MCP server where your agents' tools live and choose how Amiril signs in to it. Then grant its tools to agents on their Access tab.
- [Connect an MCP server with an API key](https://docs.amiril.ai/tool-servers/key.md): Register a tool server that takes a fixed API key or token in a header. You enter the key once in Amiril, and the gateway adds it to every call.
- [Move an in-process tool to a tool server](https://docs.amiril.ai/tool-servers/move-a-tool.md): Take a tool function and its API key out of your agent and put them on a tool server behind the Amiril gateway. The agent keeps one gateway token.
- [Connect a service through Composio](https://docs.amiril.ai/tool-servers/connectors.md): Reach a service with no MCP server of its own through Composio. Register the MCP address Composio gives you in Amiril, then grant its tools.
- [Grant tools to an agent](https://docs.amiril.ai/agents/access.md): Turn on the tools an agent may call, give it a gateway token and point its MCP client at the Amiril gateway. Then revoke the tools it stops using.

## More detail

- [Tool servers, the gateway and agent access](https://docs.amiril.ai/assistant/tool-servers.md): Everything about registering MCP tool servers, the four sign-in methods, the Amiril gateway, tool grants, gateway tokens, sync, the access log, access suggestions and their errors.
- [HTTP API: access](https://docs.amiril.ai/assistant/api/access.md): The access routes of Amiril's HTTP API: 16 operations, each with its parameters, request body, responses and token access.
