Giving Claude Code typed tools for a REST API often means writing a small Model Context Protocol (MCP) server for that API: a program, known as a wrapper, that exposes each endpoint (a method on a URL path) as a tool and forwards each call. A tool here is a named action with typed inputs that a model can ask to run. Each API then needs its own wrapper, and each wrapper has to be kept in step with the API.

The Universal Tool Calling Protocol (UTCP) replaces the per-API code with data. A JSON file called a manual describes an API’s endpoints as tools, and a client library reads the manual and calls the API itself. A manual can be generated from an API’s OpenAPI spec, the machine-readable list of its endpoints. UTCP’s @utcp/mcp-bridge package then gives Claude Code access: it is one generic MCP server that can reach any API with a manual.

This article takes you from a REST API running in Docker to a Claude Code session that answers questions from it, with no API-specific server code. You will generate manuals/random.json from the OpenAPI spec of random-server, a public test API that can require an API key. You will connect the bridge to Claude Code with no key in the tool schemas or replies, and confirm an answer against the API directly. You will also learn what breaks a conversion, what the bridge exposes that you need to lock down, and when a hand-written server is still the better choice.

An MCP server still runs: the bridge is that server, and Claude Code starts it for you. What goes away is writing a server per API.

What you end up with

  • utcp-random/, a Node project pinned to @utcp/mcp-bridge 1.1.0, with random-server running in Docker on port 1220.
  • generate-manual.mjs, the generator, which converts a spec to a manual and reports the problems UTCP’s converter stays silent about.
  • .utcp_config.json, .mcp.json, .claude/settings.json, and CLAUDE.md, which connect the bridge to Claude Code and restrict what it can do.
  • A 12-test suite and a Makefile whose default target prints help.

Prerequisites

  • macOS with make from the Xcode Command Line Tools (xcode-select --install). Validated on macOS 27.2 on Apple silicon.
  • Docker Desktop (download), running. Validated on Docker 29.9.2. The image is public, so no registry login is needed.
  • Git, which comes with the Xcode Command Line Tools, configured with your name and email. The generated manual is committed so that you can review changes to it.
  • Node.js 22 or later (download). Validated on Node 26.13.0.
  • Claude Code (install guide), signed in. Validated on version 2.1.319. Step 7 runs real prompts, which count against your plan or API usage.
  • A working idea of MCP. You do not need to have built a server, but Build an MCP Server with FastMCP and Python is the place to start if the term is new.

Step 1: Create the project

The bridge is a Node package, and so is the converter that generates manuals, so this is a Node project. Two UTCP packages are pinned exactly so that your install matches what this article tested, since some of the examples on UTCP’s site are behind them, and the committed lockfile holds the versions of what those packages pull in. The .gitignore comes first, so the .env file holding your API key cannot be committed by accident.

mkdir utcp-random
cd utcp-random
git init -q
printf 'node_modules/\n.env\n.DS_Store\n*.log\n' > .gitignore
npm init -y
npm pkg set type=module
npm pkg set private=true --json
npm pkg delete scripts.test
npm install --save-exact @utcp/[email protected] @utcp/[email protected]
npm install --save-exact --save-dev @modelcontextprotocol/[email protected]
mkdir tests

@utcp/http supplies the converter, and @modelcontextprotocol/sdk, at the version the bridge itself uses, lets the later scripts talk to the bridge the way Claude Code does. npm reports advisories during the install, which Step 8 explains. Run every later command from inside utcp-random/, because the paths in the project are relative to it.

Step 2: Start the API and read its spec

A manual inherits its spec’s flaws, so look at both the API and the spec before converting anything. random-server serves generated test data, and its routes under /v1 need an x-api-key header once the container is started with an API_KEY environment variable. The first curl below has no key and is meant to fail. The random_ prefix in .env looks odd and is required, for a reason Step 5 gives.

printf 'random_API_KEY=demo-key\n' > .env
docker run -d --name random-server -p 1220:3100 -e API_KEY=demo-key \
  ghcr.io/mitchallen/random-server:2.3.5
sleep 2
curl -s http://localhost:1220/v1/people/count
echo
curl -s -H 'x-api-key: demo-key' http://localhost:1220/v1/people/count
echo
curl -s http://localhost:1220/openapi.json | node -e '
  const spec = JSON.parse(require("fs").readFileSync(0));
  const person = spec.paths["/v1/people/{objectId}"].get;
  console.log(spec.servers[0].url);
  console.log(person.operationId, JSON.stringify(person.security));
  console.log(spec.components.securitySchemes.apiKey);'
{"status":"401","error":"unauthorized","app":"random-server","version":"2.3.5"}
{"count":25}
http://localhost:1220
getPerson [{"apiKey":[]}]
{
  type: 'apiKey',
  in: 'header',
  name: 'x-api-key',
  description: 'Required only when the server is started with API_KEY set'
}

Port 1220 on your Mac maps to port 3100 in the container, and a first run also prints the image download. The server generates its records when the container starts, so the people you see later will differ from those shown here. The count of 25 does not change.

The last lines are why this spec’s tools work. It names the server with an absolute URL, each operation (OpenAPI’s word for an endpoint) has an operationId, a unique name, and the key is declared as a security scheme, the spec’s statement of how clients authenticate. random-server 2.3.5 added these for this purpose, and the spec in earlier versions converted to zero tools. Step 4 shows what each one prevents, which you will need for an API of your own.

Step 3: Generate the manual

The converter takes a parsed spec and returns a manual. The script around it fetches the spec, tells the converter how the API expects its key, and then checks the result, because the converter reports nothing in the cases Step 4 covers.

Create the file

touch generate-manual.mjs

Add the code: generate-manual.mjs

// Convert an OpenAPI spec, from a URL or a file, to a UTCP manual.
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
import { OpenApiConverter } from '@utcp/http';

const SOURCE = process.argv[2] ?? 'http://localhost:1220/openapi.json';
const OUTPUT = process.argv[3] ?? 'manuals/random.json';
const IS_URL = SOURCE.startsWith('http');

async function loadSpec() {
  if (!IS_URL) return JSON.parse(readFileSync(SOURCE, 'utf8'));
  const response = await fetch(SOURCE);
  if (!response.ok) throw new Error(`${SOURCE} returned ${response.status}`);
  return response.json();
}

const spec = await loadSpec();

// Use the API's own key scheme. Other kinds of scheme need their own handling.
const schemes = Object.values(spec.components?.securitySchemes ?? {});
const apiKey = schemes.find((scheme) => scheme.type === 'apiKey');

const manual = new OpenApiConverter(spec, {
  specUrl: IS_URL ? SOURCE : undefined,
  authTools: apiKey && {
    auth_type: 'api_key',
    api_key: '${API_KEY}',
    var_name: apiKey.name,
    location: apiKey.in,
  },
}).convert();

// The converter does not report any of these, and each one breaks a tool.
const problems = [];
const METHODS = ['get', 'put', 'post', 'delete', 'patch'];
const CALLABLE = /^(https:|http:\/\/(localhost|127\.0\.0\.1|\[::1\])[:/])/;
const SECRET = /key|token|auth|secret|password/i;

for (const [path, item] of Object.entries(spec.paths)) {
  for (const method of METHODS) {
    if (item[method] && !item[method].operationId) {
      problems.push(`${method.toUpperCase()} ${path}: no operationId, so no tool`);
    }
  }
}
for (const tool of manual.tools) {
  const { url, header_fields: headers = [] } = tool.tool_call_template;
  if (!CALLABLE.test(url)) {
    problems.push(`${tool.name}: the client will refuse the URL ${url}`);
  }
  for (const header of headers.filter((name) => SECRET.test(name))) {
    problems.push(`${tool.name}: the model would see the input ${header}`);
  }
}

mkdirSync(dirname(OUTPUT), { recursive: true });
writeFileSync(OUTPUT, JSON.stringify(manual, null, 2) + '\n');
console.log(`tools written to ${OUTPUT}: ${manual.tools.length}`);
for (const problem of problems) console.log(`problem: ${problem}`);
process.exitCode = problems.length > 0 ? 1 : 0;

Detailed breakdown

  • SOURCE and OUTPUT. Defaults for this project. Pass another spec’s URL or file path, and another output path, to convert a different API.
  • specUrl. Tells the converter where the spec came from, which it uses in its security checks.
  • authTools. The credentials for tools whose operations declare a security scheme, using the name and location the spec gives. The ${API_KEY} is written into the manual as a placeholder, a variable the client fills in at call time, so the manual holds no secret and can be committed. Only apiKey schemes are handled; a bearer token, for example, needs this block edited.
  • problems. Applies the checks described in Step 4, and sets a non-zero exit code so a build can fail on them. The secret check is a name match on header inputs, so treat it as a prompt to look.

Run it, print one of the generated tools, and commit the result so that later changes show up as a diff:

node generate-manual.mjs
node -e '
  const { tools } = JSON.parse(require("fs").readFileSync("manuals/random.json"));
  const { name, inputs, tool_call_template: template } = tools[6];
  console.log(JSON.stringify({ name, inputs, template }, null, 2));'
git add .
git commit -qm "Generate the random-server manual"
tools written to manuals/random.json: 16
{
  "name": "getPerson",
  "inputs": {
    "type": "object",
    "properties": {
      "objectId": {
        "description": "Position in the collection, starting at 1",
        "type": "integer",
        "minimum": 1
      }
    },
    "required": [
      "objectId"
    ]
  },
  "template": {
    "name": "random_server",
    "call_template_type": "http",
    "http_method": "GET",
    "url": "http://localhost:1220/v1/people/{objectId}",
    "auth": {
      "auth_type": "api_key",
      "api_key": "${API_KEY}",
      "var_name": "x-api-key",
      "location": "header"
    },
    "content_type": "application/json",
    "timeout": 30
  }
}

That one call produced a tool for all 16 endpoints, with no code for any of them. The tool_call_template block, shown as template, is a call template: the part of a tool that tells a client how to make the real request. {objectId} is a path parameter filled from the tool’s arguments. The key is not in inputs, so a model reading the tool’s schema never sees it.

Step 4: See what breaks a conversion

Your own API’s spec may not be as tidy, and a flawed spec fails quietly. The file below has the three flaws that random-server’s spec had before version 2.3.5. Running the generator on this file is meant to fail. Its output and the table after it, which adds a fourth flaw, are the checklist to apply to an API of yours.

Create the file

touch tests/flawed-openapi.json

Add the code: tests/flawed-openapi.json

{
  "openapi": "3.0.0",
  "info": { "title": "flawed", "version": "1.0.0" },
  "servers": [{ "url": "/" }],
  "paths": {
    "/v1/people": {
      "get": {
        "summary": "No operationId",
        "responses": { "200": { "description": "OK" } }
      }
    },
    "/v1/people/count": {
      "get": {
        "operationId": "countPeople",
        "summary": "The key is a parameter and the server URL is relative",
        "parameters": [
          {
            "in": "header",
            "name": "x-api-key",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": { "200": { "description": "OK" } }
      }
    }
  }
}

Detailed breakdown

  • servers with a relative URL. Common, because a relative URL suits a page like Swagger UI that is served by the API itself.
  • One operation with no operationId. The field is optional in OpenAPI.
  • x-api-key declared as a parameter. Also common, because it gives Swagger UI an input box for the key.
node generate-manual.mjs tests/flawed-openapi.json /tmp/flawed-manual.json
echo "exit code: $?"
tools written to /tmp/flawed-manual.json: 1
problem: GET /v1/people: no operationId, so no tool
problem: countPeople: the client will refuse the URL /v1/people/count
problem: countPeople: the model would see the input x-api-key
exit code: 1

Each problem would otherwise surface much later, or not at all:

ProblemWhat happens without the checkFix
No operationIdThe converter uses it as the tool’s name and skips the operation, with no warningGive every operation a unique operationId
Relative server URLEvery call to the tool fails with a security error, because the URL has no host to checkServe the spec with an absolute servers URL
Plain HTTP to another hostEvery call fails the same way: the client accepts only HTTPS, or HTTP to this machineServe the API over HTTPS and name that URL in servers
Key as a parameterThe key becomes a tool input that the model sees and has to supplyDeclare a security scheme and apply it with security

If you cannot change an API’s spec, edit a copy of the file and run the generator on that. A copy cannot fix plain HTTP, because the API itself has to serve HTTPS.

Step 5: Run the bridge and see what it exposes

The bridge needs a configuration file saying which manuals to load and where to find variables. Before involving Claude Code, drive the bridge from a small script, because that shows exactly what a host (an application that connects to MCP servers, such as Claude Code) will see, and any failure here has nothing to do with the model.

Create the file

touch .utcp_config.json

Add the code: .utcp_config.json

{
  "load_variables_from": [
    { "variable_loader_type": "dotenv", "env_file_path": ".env" }
  ],
  "manual_call_templates": [
    {
      "name": "random",
      "call_template_type": "file",
      "file_path": "manuals/random.json",
      "allowed_communication_protocols": ["http"]
    }
  ]
}

Detailed breakdown

  • load_variables_from. Reads variables from .env, relative to the directory the bridge starts in.
  • name: "random". Becomes a prefix for the manual’s tools, as in random.getPerson, and for its variables. The manual’s ${API_KEY} resolves to random_API_KEY, which is why .env uses that name. An underscore in a manual’s name is doubled, so my_api would need my__api_API_KEY.
  • call_template_type: "file". Each entry here is itself a call template, one that tells the client how to fetch a manual rather than how to call an API. This one reads the file you generated.
  • allowed_communication_protocols. Without it, the manual loads and every tool is refused, leaving zero tools and no error in the reply. The bridge’s stderr names the reason. A template allows only its own type by default, and these are http tools loaded by a file template. The rule stops a manual from switching a tool to a type you did not agree to.

Create the file

touch bridge-client.mjs

Add the code: bridge-client.mjs

// Start the bridge and talk to it the way an MCP host such as Claude Code does.
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';

export async function connect(configFile = '.utcp_config.json') {
  const transport = new StdioClientTransport({
    command: 'npx',
    args: ['--no-install', 'mcp-bridge'],
    env: { ...process.env, UTCP_CONFIG_FILE: configFile },
    stderr: 'pipe',
  });
  let stderr = '';
  transport.stderr?.on('data', (chunk) => {
    stderr += chunk;
  });

  const client = new Client({ name: 'bridge-client', version: '1.0.0' });
  await client.connect(transport);

  return {
    tools: async () => (await client.listTools()).tools.map((tool) => tool.name),
    call: async (name, args = {}) => {
      const reply = await client.callTool({ name, arguments: args });
      return JSON.parse(reply.content[0].text);
    },
    stderr: () => stderr,
    close: () => client.close(),
  };
}

Detailed breakdown

  • StdioClientTransport. Starts the bridge as a child process and speaks MCP to it over standard input and output, as Claude Code does.
  • stderr: 'pipe'. Captures the bridge’s error output for a test in Step 9.
  • call. The bridge answers each call with JSON in a text block, so this parses it.

Create the file

touch try-bridge.mjs

Add the code: try-bridge.mjs

// See what a host sees, then make one call through the bridge.
import { connect } from './bridge-client.mjs';

const bridge = await connect();

console.log('MCP tools:', (await bridge.tools()).join(', '));

const { tools } = await bridge.call('list_tools');
console.log(`UTCP tools: ${tools.length}, such as ${tools[6]}`);

const info = await bridge.call('tool_info', { tool_name: 'random.getPerson' });
console.log('inputs:', JSON.stringify(info.tool.inputs.properties));

const count = await bridge.call('call_tool', {
  tool_name: 'random.countPeople',
  arguments: {},
});
console.log('reply:', JSON.stringify(count));

await bridge.close();

Detailed breakdown

  • bridge.tools(). What MCP lists, the tools a host sees.
  • list_tools, tool_info, call_tool. Three of those MCP tools, used in the order a model has to use them.
node try-bridge.mjs
MCP tools: register_manual, deregister_manual, call_tool, search_tools, list_tools, get_required_keys_for_tool, tool_info
UTCP tools: 16, such as random.getPerson
inputs: {"objectId":{"description":"Position in the collection, starting at 1","type":"integer","minimum":1}}
reply: {"success":true,"tool_name":"random.countPeople","result":{"count":25}}

A host sees the seven generic tools on the first line, not the 16 tools from your manual. To use the API, a model lists the UTCP tools, reads the inputs of the one it wants, and passes its name and arguments to call_tool. That keeps the host’s tool list short however many APIs you add. The cost is extra model turns, where each tool result goes back to the model before it can make the next call, and the host can no longer see each tool’s input schema. Step 6 gives the model that order, and Step 8 weighs the cost.

Step 6: Connect the bridge to Claude Code

Three files connect the bridge and govern how a model uses it. The first, .mcp.json, is written by claude mcp add-json and tells Claude Code how to start the server. --scope project keeps it in this directory, where it can be committed.

claude mcp add-json --scope project utcp \
  '{"type":"stdio","command":"npx","args":["--no-install","mcp-bridge"],"env":{"UTCP_CONFIG_FILE":".utcp_config.json"}}'
cat .mcp.json
Added stdio MCP server utcp to project config
{
  "mcpServers": {
    "utcp": {
      "type": "stdio",
      "command": "npx",
      "args": [
        "--no-install",
        "mcp-bridge"
      ],
      "env": {
        "UTCP_CONFIG_FILE": ".utcp_config.json"
      }
    }
  }
}

Deny the tools that can run commands

The second file matters most. The bridge’s register_manual tool adds a manual at run time, and a manual is not limited to HTTP: the bridge also includes UTCP’s cli plugin, whose tools run local commands. While testing this article, registering a cli manual ran its discovery command on the machine at once, before any call_tool, even though register_manual reported failure. So a model allowed to use register_manual, perhaps steered by text in an API response, can reach your shell. Treat that tool as shell access, and do not allow mcp__utcp__* as a wildcard.

Create the file

mkdir -p .claude
touch .claude/settings.json

Add the code: .claude/settings.json

{
  "enabledMcpjsonServers": [
    "utcp"
  ],
  "permissions": {
    "allow": [
      "mcp__utcp__list_tools",
      "mcp__utcp__search_tools",
      "mcp__utcp__tool_info",
      "mcp__utcp__get_required_keys_for_tool",
      "mcp__utcp__call_tool"
    ],
    "deny": [
      "mcp__utcp__register_manual",
      "mcp__utcp__deregister_manual",
      "Read(./.env)"
    ]
  }
}

Detailed breakdown

  • deny. Removes the two manual-changing tools from the session, so manuals come only from .utcp_config.json. Treat that file and manuals/ as code: a cli entry added to that file would run at the next start, and a manual decides which URLs receive your key. Read(./.env) blocks Claude Code’s file tools from the key. It does not stop a subprocess, such as cat run through Bash, from reading the file, so keep Bash on prompts and use a low-privilege key.
  • allow. Rule names follow mcp__<server>__<tool>. These rules let the read and call tools run without a prompt. Allowing call_tool approves every tool in every manual, including any that write or delete, so remove it from this list if you add an API with write operations.
  • enabledMcpjsonServers. Approves this project’s server, once the folder is trusted.

Tell the model how to use the bridge

The third file exists because the tools are generic. Without it, a test run with Claude Haiku guessed {"id": 3} as the argument, and went looking through the local filesystem for the server’s source code before it succeeded. Claude Code reads a project’s CLAUDE.md at the start of a session.

Create the file

touch CLAUDE.md

Add the code: CLAUDE.md

# Calling the random-server API

The random-server API is available through the `utcp` MCP server. Do not look for
its source code or call it with curl.

1. Use `list_tools` to find a tool, such as `random.getPerson`.
2. Use `tool_info` to read that tool's inputs before the first call to it.
3. Use `call_tool` with `tool_name` and an `arguments` object, even an empty one.

Detailed breakdown

  • The opening line. Names the server and warns the model off the server’s source code and curl.
  • The numbered steps. Spell out the order from Step 5, including the arguments object that call_tool requires even for a tool with no inputs.

Trust the folder

Claude Code ignores a project’s approvals and allow rules until you trust its folder, and -p cannot ask. Without this, claude mcp list reports Pending approval, and under default permissions Step 7 fails because the bridge’s tools are not allowed. Run claude here once, accept the trust dialog, and leave with /exit:

claude

Then confirm that Claude Code can start the server:

claude mcp list | grep utcp
utcp: npx --no-install mcp-bridge - ✔ Connected

✔ Connected means that Claude Code started the bridge and completed the MCP handshake, the exchange that opens a session.

Step 7: Ask Claude Code about the API

Ask a question in plain language and get an answer from the API, with no server written for it. -p runs one prompt and exits, and --model haiku keeps the cost low; other models should work. The same setup applies if you run plain claude and ask interactively. The prompt asks the model to list its tool calls, so you can see the route it reports.

claude -p "How many people does the random-server API have, and what is the first and last name of person number 3? List the tool calls you made, one per line." --model haiku
curl -s -H 'x-api-key: demo-key' http://localhost:1220/v1/people/3
echo
The random-server API has **25 people**. Person number 3 is **Jerry Masi** (prefix Dr.).

Tool calls, in order:
- mcp__utcp__list_tools
- mcp__utcp__tool_info (random.countPeople)
- mcp__utcp__tool_info (random.getPerson)
- mcp__utcp__call_tool (random.countPeople)
- mcp__utcp__call_tool (random.getPerson, objectId 3)
{"type":"people","prefix":"Dr.","first":"Jerry","last":"Masi","age":46,"birthday":"9/9/1991","gender":"male","zip":"46482-3941","ssnFour":"3134","phone":"(329) 832-1600","email":"[email protected]"}

The name in Claude Code’s answer and the record from curl match. If ToolSearch appears in your list, it is Claude Code loading the definitions of the bridge’s tools. The answer came from the running API, through the manual generated in Step 3, with the key added by the bridge outside the model’s tool schemas and replies. Your wording and tool calls will vary between runs, because this is a model’s output, and your person will differ because the data does.

When the API changes, run node generate-manual.mjs again, review the change with git diff manuals/random.json, commit it, and start a new session.

Check the lock-down

A second prompt confirms that the deny rules for register_manual and .env take effect in a real session:

claude -p "Is a tool named mcp__utcp__register_manual available to you? Then try your Read tool on the file .env, using no other tool, and do not repeat its contents. Report both results." --model haiku
**1. Is `mcp__utcp__register_manual` available?** No. The `utcp` MCP tools I have are `mcp__utcp__list_tools`, `search_tools`, `tool_info`, `get_required_keys_for_tool`, and `call_tool`. There is no `register_manual`.

**2. Read of `.env`:** It failed. The Read tool returned "File is in a directory that is denied by your permission settings," so the file was not read and its contents are not in my context. I didn't try any other tool to get around the denial. If you need me to read it, you'd have to adjust the permission rule for that directory.

Step 8: Weigh the costs

The bridge removes a program you would otherwise write, but it brings costs of its own, and this step is about deciding whether to accept them. UTCP’s comparison page argues that UTCP avoids the extra hop of an MCP server. That holds for a program embedding a UTCP client directly. Through the bridge there is still a server in the path. In this article’s testing over loopback (this machine), the median of 200 calls was about 0.5 ms through the bridge against 0.3 ms with plain HTTP, and the bridge took about 300 ms to start. The extra model turns typically take far longer than any of these figures. These numbers do not say how either would behave against a remote API.

Two commands show the state of the package itself:

npm audit --omit=dev | grep vulnerabilities
npm view @utcp/mcp-bridge time.modified
10 high severity vulnerabilities
2026-05-03T19:30:09.799Z

Both results change over time, so yours may differ.

Four risks to weigh

  • Command execution. Covered in Step 6. Denying register_manual closes the path at run time.
  • The key in the bridge’s error output. When a call fails, the bridge dumps the whole failed request to stderr, including the x-api-key header. The reply to the model does not contain it. After a failed call in this article’s testing, a search of Claude Code’s cache and session files for the key found nothing, but anything else capturing the bridge’s stderr would have it. Use a low-privilege key, and do not ship that output to a logging service. The test suite records this behavior.
  • The dependency tree. The advisories behind that npm audit count come from two packages the bridge pulls in, zod and the MCP SDK version it pins. Some concern HTTP transports or OAuth, which this stdio setup may not use; this article did not assess each one. Do not run npm audit fix --force, because its proposed fix downgrades the bridge below the version used here. The date shows when the package’s npm entry last changed.
  • Log lines on standard output. The bridge prints its own log lines to stdout, which MCP reserves for protocol messages. Claude Code and the SDK client in this article tolerated them, but a stricter host might not.

Which to choose

These questions separate the bridge from a wrapper written for the API.

QuestionUTCP bridgeHand-written MCP server
What code do you write per API?None, if the spec is soundOne server
What does the host see?Generic tools from the bridgeOne typed tool per endpoint
How many model turns per call?More, since it looks tools up firstFewer
Can permissions differ per endpoint?Not with one call_tool ruleYes, one rule per tool
Can you shape tools for a model?Only through the specYes, freely
What happens when the API changes?Regenerate the manualEdit and redeploy
Who holds the key?The bridge, on the host’s machineThe server, which can run elsewhere

The bridge fits when you want many existing APIs reachable quickly, particularly read-only ones with good specs, served over HTTPS. A hand-written server fits when one API matters enough to shape its tools for a model, or when the credential must stay off the machine running the agent.

Step 9: Cover the behavior with tests

UTCP’s docs lag behind its packages, so this suite records the behavior this setup depends on, including what you would want to hear about if it changed. The tests talk to the bridge over MCP as Claude Code does, and compare results with a direct request rather than fixed values, because the data changes each time the container starts. They use no model, so they cost nothing to run.

Create the file

touch tests/bridge.test.mjs

Add the code: tests/bridge.test.mjs

// Run the bridge against the live random-server container.
import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { after, before, describe, test } from 'node:test';
import { promisify } from 'node:util';

import { connect } from '../bridge-client.mjs';

const BASE = 'http://localhost:1220';
const KEY = readFileSync('.env', 'utf8').match(/random_API_KEY=(.*)/)[1];
const MANUAL = 'manuals/random.json';

async function direct(path) {
  const response = await fetch(`${BASE}${path}`, { headers: { 'x-api-key': KEY } });
  assert.equal(response.status, 200);
  return response.json();
}

function tempConfig(template, variables = {}) {
  const dir = mkdtempSync(join(tmpdir(), 'utcp-'));
  const file = join(dir, 'config.json');
  writeFileSync(
    file,
    JSON.stringify({
      variables,
      manual_call_templates: [
        {
          name: 'random',
          call_template_type: 'file',
          file_path: resolve(MANUAL),
          ...template,
        },
      ],
    }),
  );
  return file;
}

describe('the bridge with the generated manual', () => {
  let bridge;
  before(async () => {
    bridge = await connect();
  });
  after(() => bridge.close());

  test('exposes generic tools, not one per endpoint', async () => {
    assert.deepEqual((await bridge.tools()).sort(), [
      'call_tool',
      'deregister_manual',
      'get_required_keys_for_tool',
      'list_tools',
      'register_manual',
      'search_tools',
      'tool_info',
    ]);
  });

  test('registers a tool for every operation in the spec', async () => {
    const spec = await direct('/openapi.json');
    const ids = Object.values(spec.paths).flatMap((item) =>
      Object.values(item).map((operation) => `random.${operation.operationId}`),
    );
    const { tools } = await bridge.call('list_tools');
    assert.deepEqual([...tools].sort(), ids.sort());
  });

  test('countPeople matches the server', async () => {
    const reply = await bridge.call('call_tool', {
      tool_name: 'random.countPeople',
      arguments: {},
    });
    assert.deepEqual(reply.result, await direct('/v1/people/count'));
  });

  test('getPerson matches the server', async () => {
    const reply = await bridge.call('call_tool', {
      tool_name: 'random.getPerson',
      arguments: { objectId: 1 },
    });
    assert.deepEqual(reply.result, await direct('/v1/people/1'));
  });

  test('no tool takes the API key as an input', () => {
    const { tools } = JSON.parse(readFileSync(MANUAL, 'utf8'));
    for (const tool of tools) {
      assert.ok(!('x-api-key' in (tool.inputs.properties ?? {})), tool.name);
    }
  });

  test('an out-of-range id reports the 404 without the key', async () => {
    const reply = await bridge.call('call_tool', {
      tool_name: 'random.getPerson',
      arguments: { objectId: 999 },
    });
    assert.equal(reply.success, false);
    assert.match(reply.error, /404.*out of range/);
    assert.ok(!JSON.stringify(reply).includes(KEY));
  });

  test('that failed call writes the key to stderr', () => {
    assert.ok(bridge.stderr().includes(KEY));
  });
});

test('a wrong key reports the 401', async () => {
  const bridge = await connect(
    tempConfig(
      { allowed_communication_protocols: ['http'] },
      { random_API_KEY: 'wrong' },
    ),
  );
  try {
    const reply = await bridge.call('call_tool', {
      tool_name: 'random.countPeople',
      arguments: {},
    });
    assert.equal(reply.success, false);
    assert.match(reply.error, /401/);
  } finally {
    await bridge.close();
  }
});

test('a file manual without allowed protocols registers nothing', async () => {
  const bridge = await connect(tempConfig({}));
  try {
    assert.deepEqual((await bridge.call('list_tools')).tools, []);
  } finally {
    await bridge.close();
  }
});

test('the generator reports the flaws in the bad spec', async () => {
  const output = join(mkdtempSync(join(tmpdir(), 'utcp-')), 'flawed.json');
  await assert.rejects(
    promisify(execFile)('node', [
      'generate-manual.mjs',
      'tests/flawed-openapi.json',
      output,
    ]),
    (error) => {
      assert.equal(error.code, 1);
      assert.match(error.stdout, /GET \/v1\/people: no operationId/);
      assert.match(error.stdout, /countPeople: the client will refuse the URL \/v1/);
      assert.match(error.stdout, /countPeople: the model would see the input x-api-key/);
      return true;
    },
  );
});

test('the generator reports plain HTTP to another host', async () => {
  const dir = mkdtempSync(join(tmpdir(), 'utcp-'));
  const spec = JSON.parse(readFileSync('tests/flawed-openapi.json', 'utf8'));
  spec.servers = [{ url: 'http://service.internal' }];
  writeFileSync(join(dir, 'spec.json'), JSON.stringify(spec));
  await assert.rejects(
    promisify(execFile)('node', [
      'generate-manual.mjs',
      join(dir, 'spec.json'),
      join(dir, 'manual.json'),
    ]),
    (error) => {
      assert.match(error.stdout, /refuse the URL http:\/\/service\.internal/);
      return true;
    },
  );
});

test('the project denies the manual-changing tools and reading .env', () => {
  const { permissions } = JSON.parse(readFileSync('.claude/settings.json', 'utf8'));
  assert.ok(permissions.deny.includes('Read(./.env)'));
  assert.ok(permissions.deny.includes('mcp__utcp__register_manual'));
  assert.ok(permissions.deny.includes('mcp__utcp__deregister_manual'));
  assert.ok(!permissions.allow.some((rule) => rule.endsWith('*')));
});

Detailed breakdown

  • direct. Asks the server itself, giving UTCP’s result something to match.
  • tempConfig. Writes a throwaway configuration, so the wrong-key and missing-protocol tests can vary one setting.
  • that failed call writes the key to stderr. Asserts a behavior you do not want. It depends on the failed call in the test before it, and if an upgrade fixes the leak, this test fails and tells you that Step 8’s warning can go.
  • The settings test. Checks only the file’s contents, that it denies the tools and .env and has no wildcard. Step 7’s second prompt is what shows Claude Code honoring it.

Step 10: Drive everything with make

A Makefile gathers the commands from the steps above, and recreating the container and the manual with it is the final check that the project holds together.

Create the file

touch Makefile

Add the code: Makefile

IMAGE := ghcr.io/mitchallen/random-server:2.3.5
NAME := random-server

include .env

.DEFAULT_GOAL := help
.PHONY: help up down generate test

help: ## Show this help
	@grep -hE '^[a-z]+:.*## ' $(MAKEFILE_LIST) | awk -F ':.*## ' '{printf "  %-10s %s\n", $$1, $$2}'

up: ## Start random-server on port 1220 with the key from .env
	@docker rm -f $(NAME) >/dev/null 2>&1 || true
	@docker run -d --name $(NAME) -p 1220:3100 -e API_KEY=$(random_API_KEY) $(IMAGE) >/dev/null
	@until curl -sf http://localhost:1220/ >/dev/null; do sleep 0.2; done
	@echo "$(NAME) is up on http://localhost:1220"

down: ## Stop and remove the container
	@docker rm -f $(NAME) >/dev/null 2>&1 || true

generate: ## Generate the manual from the server's OpenAPI spec
	@node generate-manual.mjs

test: generate ## Run the tests against the running container
	@node --test "tests/*.test.mjs"

Detailed breakdown

  • include .env. Reads random_API_KEY as a make variable, so the container and the bridge always use the same key. A missing .env stops make at once, where otherwise make up would pass an empty key and could start the server open.
  • "tests/*.test.mjs". Quoted so that Node, not the shell, expands the pattern.
  • grep -hE. Including .env adds a second file to MAKEFILE_LIST. Without -h, grep prefixes each line with its filename and the help screen breaks.
  • The until loop in up. Waits for the server to answer, so a following command cannot run before the container is ready.
  • test: generate. Regenerates the manual from the live spec before testing it.

Run make by itself to confirm the help screen, then rebuild and test:

make
make down
rm -f manuals/random.json
make up
make test
git add .
git commit -qm "Connect the bridge to Claude Code"
  help       Show this help
  up         Start random-server on port 1220 with the key from .env
  down       Stop and remove the container
  generate   Generate the manual from the server's OpenAPI spec
  test       Run the tests against the running container
random-server is up on http://localhost:1220
tools written to manuals/random.json: 16
▶ the bridge with the generated manual
  ✔ exposes generic tools, not one per endpoint (1.327ms)
  ✔ registers a tool for every operation in the spec (19.111209ms)
  ✔ countPeople matches the server (12.482041ms)
  ✔ getPerson matches the server (3.159458ms)
  ✔ no tool takes the API key as an input (0.218542ms)
  ✔ an out-of-range id reports the 404 without the key (2.917416ms)
  ✔ that failed call writes the key to stderr (0.07025ms)
✔ the bridge with the generated manual (335.64025ms)
✔ a wrong key reports the 401 (294.295459ms)
✔ a file manual without allowed protocols registers nothing (284.9455ms)
✔ the generator reports the flaws in the bad spec (102.62275ms)
✔ the generator reports plain HTTP to another host (101.81975ms)
✔ the project denies the manual-changing tools and reading .env (0.165541ms)
ℹ tests 12
ℹ suites 1
ℹ pass 12
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1206.029125

All 12 tests pass against a new container, and the project is committed without .env. When you are done, run make down to remove it.

Troubleshooting

claude mcp list shows the server as failed. Run node try-bridge.mjs from the project directory. If that fails too, the problem is in the bridge or its configuration, not Claude Code. UTCP_CONFIG_FILE and .env are both relative to the starting directory, so start Claude Code from utcp-random/.

Pending approval, or Ignoring 5 permissions.allow entries. The folder is not trusted. Run claude there once and accept the dialog (Step 6).

list_tools returns nothing. Check that manuals/random.json exists and that the template sets allowed_communication_protocols (Step 5). A manual that fails validation also leaves zero tools. The bridge’s stderr has the reason in each case.

Variable random_API_KEY ... not found, or a 401. The variable has to carry the manual’s name as a prefix, and the .env value has to match the container’s API_KEY.

Fewer tools than expected, or a security error naming a URL. The spec has a flaw from Step 4. Run generate-manual.mjs on it and read the problem: lines.

The model guesses arguments or looks elsewhere for the API. Check that CLAUDE.md is in the directory you started Claude Code from (Step 6).

Port 1220 is in use, or random-server already exists. make down removes the container. For another program on the port, change 1220 everywhere it appears: grep -rn 1220 . --exclude-dir=node_modules, then run make up and make generate.

Recap

You pointed a generator at an API’s OpenAPI spec, got a manual, and connected it to Claude Code through one generic MCP server. A plain-language question then got an answer from the running API, with no key in the tool schemas or replies and no code written for that API.

The approach works with conditions: the spec needs an operationId on each operation, an absolute HTTPS or loopback server URL, and a security scheme if the API takes a key; the model sees generic tools and needs a short CLAUDE.md; the folder must be trusted; and register_manual must be denied. An MCP server still runs, as one generic bridge rather than one per API.

Next improvements:

  • Add a second API. Generate another manual and add it to manual_call_templates under its own name, with its own prefixed key in .env, and mention it in CLAUDE.md. The host’s tool list does not grow.
  • Check specs in CI. generate-manual.mjs exits non-zero on a problem, so an API’s build can fail when its spec has one.

Avoid one shortcut. A manual template can use call_template_type: "http" with the spec’s URL and auth_tools, and the bridge will convert the spec at each start. In this article’s testing that stored the real key in the tool definition, and tool_info returned it to the caller. A generated manual keeps the ${API_KEY} placeholder, so stay with the file.