kilo-logo
kilo-logo
kilo-logo

How to Connect an OpenAPI API to Claude Code: A Practical Integration Guide

Tom Dallimore

By

Tom Dallimore

Published

An OpenAPI spec is turned into MCP tools that Claude Code calls from the terminal, with the refund tool marked as needing approval.

You ask Claude Code to fix a bug in the billing client. It reads the code, nods politely, and writes a fix that sends customer_ref to your invoices endpoint.

Your API has never had a field called customer_ref. It is called customer_id, and it is right there in the OpenAPI spec that Claude never opened.

Lovely.

Claude Code is very good at reading a codebase. It is not psychic about the API sitting behind it. If the only thing it knows about your service is the client code (which is probably out of date) and whatever it remembers from training, it will guess. Confidently.

The short version: a proper Claude Code integration with an OpenAPI API means wrapping the API in an MCP server, registering it with the Claude Code CLI, and giving Claude a short list of tools it is allowed to call. Start read-only. Add GitHub Actions once the local setup is boring. You can hand-write the MCP server, or point the open-source Fetch Hive MCP gateway at the spec you already have. I will show both.

If you are new to MCP, start with my guide on how to build an MCP server. If you already know the basics, carry on.

What a Claude Code Integration Actually Is

Claude Code is Anthropic's agentic coding tool. You run it from the terminal, the desktop app or your IDE (VS Code, which is Microsoft's, and the JetBrains family). It reads files, writes code, can run tests, creates branches and opens pull requests. It is not autocomplete with ambitions.

It talks to the outside world through three channels:

  • Files. It can read and modify anything in the repo you started it in, including your OpenAPI spec if it lives there.

  • The shell. Git, linters, build tools, test runners, curl. Whatever your terminal can run, Claude can ask to run.

  • MCP servers. Remote APIs and data sources, exposed as typed tools with input schemas. This is the bit that matters for an OpenAPI API.

The Model Context Protocol (MCP) is a standard way for an AI client to discover and call tools. Each MCP server publishes a list of tools with names, descriptions and JSON schemas. Once a server is registered, those tools appear in Claude's context and it can call them in the middle of a coding task, the same way it would call git.

One correction to a myth that turns up in a lot of tutorials: you do not need the IDE plugin to use MCP. The plugin connects Claude Code to your editor features (diffs, selections, diagnostics). MCP servers are registered with the Claude Code CLI and work fine in a plain terminal on macOS, Linux (Ubuntu and friends) or Windows.

Claude Code reaches files in the repo, commands in the shell, and an OpenAPI API through an MCP server.

Do You Even Need MCP for This?

Not always. Here is the honest version.

If the spec lives in the same repo and all you want is for Claude to write correct client code, you do not need MCP. Point Claude at the file. Put "the API contract is openapi/v2/public.yaml, read it before touching src/billing" in your CLAUDE.md. Done. That alone fixes the customer_ref problem.

You need MCP when Claude has to call the API, not just read about it:

  • Pulling real data to debug something ("why did invoice INV-2047 fail?").

  • Checking a fix against the live staging service before it opens a PR.

  • Sharing the same set of tools across a team, so everybody's Claude has the same access.

  • Controlling exactly which endpoints are callable, with authentication handled outside the prompt.

Could Claude just curl the API from the shell? Yes. It will also happily paste your bearer token into a command line, and you get no schema, no per-endpoint permission and no clean audit trail. Well, you wouldn't let a new contractor work like that, would you?

My call: read the spec as a file for code generation, use MCP for anything that calls the API.

Prerequisites

Before you start, get these sorted:

  • Install the Claude Code CLI. Use the native installer from the setup page in Anthropic's docs, or npm (npm install -g @anthropic-ai/claude-code), then run claude update to make sure you are current. Supported platforms are macOS, Linux (Ubuntu, Debian and the rest) and Windows (natively or through WSL).

  • Have access to Claude models. A paid Claude plan or an Anthropic Console account works, as does Amazon Bedrock or Google Vertex AI if your company routes through a cloud platform.

  • Have a running API with an accurate OpenAPI spec. OpenAPI 3.0 or 3.1, served at a URL (FastAPI gives you /openapi.json for free) or stored in the repo. If the spec is wrong, every tool built from it is wrong. Garbage in, garbage called.

  • Have the right GitHub access if you want the PR automation later: permission to create branches, push commits and install a GitHub App on the repository.

  • Node 20 or later if you hand-write the MCP server in Node.

The IDE plugin is optional. If you use it, run claude from your IDE's integrated terminal and the plugin connects automatically, or use the /ide command from an external terminal started in the same project directory.

Two Ways to Wire an OpenAPI API into Claude Code

There are two sensible routes. Pick based on how many operations you have and how much custom logic each one needs.

Dimension

Option 1: hand-written MCP server

Option 2: Fetch Hive MCP gateway

What you write

A Node or Python file with one function per tool

Nothing. You point it at the OpenAPI spec

Best for

A handful of tools, custom logic, combining calls

APIs that already publish a decent spec

Transport to Claude Code

stdio (Claude starts the process)

Streamable HTTP on 127.0.0.1:8787

Keeping tools in sync

You edit code when the API changes

Re-run add-spec when the spec changes

Reaching it from GitHub Actions

Hard. It runs on your laptop

Tunnel or the hosted gateway

Cost

Free

Free and open source (Apache 2.0)

Verdict: if you want three carefully designed tools, write them. If you want Claude to see the API you already documented, do not hand-write 40 wrappers.

There is decent research on how well the generated route works. A 2026 study, From REST to MCP, generated MCP servers from 80 real-world OpenAPI contracts: 76% of sampled tools worked out of the box, and automated repair of the specs raised that to 94.2%. The same paper found official, hand-built MCP servers expose a median of only 19% of the operations their API offers. Generation gets you working tools. Curation is still your job.

Two Buttons meme: a sweating developer cannot choose between hand-writing 40 MCP tool wrappers and using the OpenAPI spec they already wrote.

Option 1: Write a Small MCP Server and Register It

We will use one boring example throughout: a billing API on http://127.0.0.1:5001 with a spec at /openapi.json and three operations, listInvoices, getCustomer and createRefund. Boring is good. It looks like most internal APIs.

Step 1: Decide Where the Spec Lives

Keep the spec in the repo (for example openapi/v2/public.yaml) and version it with the code. Then the Claude session, the MCP server and your reviewers all look at the same contract, and a spec change shows up in a pull request like any other change. A spec that only exists on a running staging box is a spec nobody reviews.

Step 2: Map Operations to Tools

Each OpenAPI operation you want to expose becomes one MCP tool. The rules I stick to:

  • Name tools after the operationId, with underscores. list_invoices, get_customer, create_refund. Some model providers reject dots in tool names, so billing.list is a bad idea.

  • Write descriptions like prompts, because they are. Claude picks tools by reading them. "Create a refund. Only use this when the user explicitly asks for a refund" prevents a lot of creative refunding.

  • Read authentication from environment variables. Bearer tokens, API keys or OAuth client credentials come from env, never from a tool argument and never from the prompt.

  • Fix the base URL in config. If a tool argument can choose which host gets called, you have built an SSRF machine with a chat interface.

  • Return errors as tool results. "API returned 404: invoice INV-2047 not found" lets Claude explain the problem. A hung request just wastes a turn.

A minimal tool in the official TypeScript SDK looks like this:

JAVASCRIPT
server.registerTool(
  'list_invoices',
  {
    description: 'List invoices for a customer. Read-only.',
    inputSchema: { customer_id: z.string(), status: z.enum(['paid', 'failed', 'open']).optional() },
    annotations: { readOnlyHint: true },
  },
  async ({ customer_id, status }) =>
    callApi(`/invoices?customer_id=${encodeURIComponent(customer_id)}${status ? `&status=${status}` : ''}`)
);

I covered the full server, including the callApi helper, timeouts and stdio logging, in my guide to connecting a localhost API to Cursor. The server code is identical for Claude Code. Only the registration step changes.

Step 3: Register It with the Claude Code CLI

Registration is one command. For a local stdio server:

SHELL
claude mcp add --env BILLING_API_KEY=sk_test_123 --transport stdio billing \
  -- node /Users/you/projects/billing-mcp/index.js

Everything before the -- is for Claude Code (transport, env, scope). Everything after it is the command that starts your server. Use an absolute path. Claude does not always start your server from the folder you expect.

By default this writes to your local scope, which only you see in this project. For a team, add --scope project. That writes a .mcp.json file at the repo root that you commit, so all developers who clone the repo get the same server:

JSON
{
  "mcpServers": {
    "billing": {
      "type": "stdio",
      "command": "node",
      "args": ["tools/billing-mcp/index.js"],
      "env": { "BILLING_API_KEY": "${BILLING_API_KEY}" }
    }
  }
}

The ${BILLING_API_KEY} syntax expands from each developer's environment, and ${VAR:-default} works for fallbacks. Do not commit a real key into .mcp.json. Somebody always does. It always ends up in a Slack thread titled "quick question".

The third scope, --scope user, makes a server available in every project on your machine. Use it for personal tools, not for a project's API.

Option 2: Skip the Wrapper with the Fetch Hive MCP Gateway

WARNING: Shameless self-promotion incoming. It is relevant, I promise.

If your API already publishes an OpenAPI spec, you have already written the tool definitions. You just wrote them in a different format. The Fetch Hive MCP gateway compiles the spec into MCP tools and serves them over Streamable HTTP. The CLI is a single open-source binary (Apache 2.0, on GitHub) that runs on your machine.

Install it with Homebrew (brew install Fetch-Hive/tap/mcp-gateway) or npx (npx --yes @fetch-hive/mcp-gateway), then:

SHELL
# One-time setup. Prints a bearer token once, so save it.

mcp-gateway init --allow-private-networks

# Compile the spec your local API serves

mcp-gateway add-spec --name billing \
  --url http://127.0.0.1:5001/openapi.json \
  --insecure-http --allow-private-networks

# Call a tool before Claude is involved at all

mcp-gateway test billing list_invoices --args '{"customer_id": "cus_42"}'

# Serve it on http://127.0.0.1:8787/mcp

export MCP_GATEWAY_TOKEN=...

mcp-gateway serve billing

# Print the exact config for Claude Code

mcp-gateway inspect billing --client claude-code

The flags look fussy for a reason. The gateway refuses localhost, private networks and plain HTTP unless you opt in, which is the right default for something that makes requests on behalf of an AI agent.

Then register the HTTP endpoint with Claude Code:

SHELL
claude mcp add --transport http billing http://127.0.0.1:8787/mcp \
  --header "Authorization: Bearer $MCP_GATEWAY_TOKEN"

Two things you get without building them. The gateway audits the spec before serving and flags the parts that make bad tools (missing parameter descriptions, open-ended objects, too many required fields). And when something outside your laptop needs the API, such as a teammate or a GitHub Actions runner, mcp-gateway serve billing --tunnel gives you a public https URL ending in .mcp.fetchhive.com/mcp, still behind the bearer token. For an API that is already deployed, the hosted gateway does the same job with access tokens, request logs and tool policies.

My OpenAPI to MCP guide walks through the compile step properly. And to be clear: you do not need Fetch Hive for any of this. Option 1 works. The gateway just saves you writing and maintaining the wrapper.

Test the Connection Before You Trust It

Do this in order. It saves an afternoon.

  1. Check the server is registered. Run claude mcp list in your terminal, or claude mcp get billing for the detail.

  2. Check the server is connected. Inside a Claude Code session, run /mcp. Your server should show as connected with its tools listed. Servers from a project .mcp.json show as pending until you approve them, which is a feature, not a bug.

  3. Call one read-only tool. Prompt: "Use the billing tools to list failed invoices for customer cus_42." Claude should call list_invoices and ask your permission first.

  4. Compare the output with the spec. If the response shape does not match the OpenAPI schema, fix the spec now. Every later step builds on it.

  5. Read the errors. A tool that fails to load is almost always a path, an environment variable, or a stdio server printing to stdout. Run the server command yourself in a terminal first. If it crashes there, Claude was never going to work.

One limit worth knowing: Claude Code warns when a single tool result passes 10,000 tokens and caps it at 25,000 by default (MAX_MCP_OUTPUT_TOKENS raises it). If list_invoices returns 3 MB of JSON, the fix is pagination and filters in the tool, not a bigger limit.

Decide Which Operations Claude Gets

This is the part that actually matters. The protocol is the easy bit.

My rules for which operations get exposed:

  1. Read-only first. GET endpoints, search and list operations. They give Claude the context it needs and cannot break anything.

  2. Writes need a human. POST, PUT and PATCH stay behind Claude Code's approval prompt, or run against staging only.

  3. Deletes and money stay out. Anything that deletes records, moves money or emails customers does not get a tool until you have a very good reason and a dry-run mode.

Claude Code's permission settings enforce this. In .claude/settings.json, MCP tools are named mcp__server__tool, so you can allow the safe ones without asking and deny the dangerous ones outright:

JSON
{
  "permissions": {
    "allow": ["mcp__billing__list_invoices", "mcp__billing__get_customer"],
    "deny": ["mcp__billing__create_refund"]
  }
}

Commit that file and the whole team gets the same guardrails. For exploratory work, plan mode is useful too: Claude reads, calls read-only tools and proposes changes, but does not edit anything until you approve the plan.

Then keep the list short. Every tool is another option for Claude to choose between and another schema in its context. Claude Code's tool search helps when you have lots of servers, but it is not a reason to expose 200 endpoints. Expose the 10 that do real work.

Three-tier ladder showing read-only billing tools allowed, write tools requiring approval, and refunds and deletes not exposed to Claude Code.

Pull Requests, Code Review and CI Failures with GitHub Actions

Once the local setup works, this is where a Claude Code integration pays for itself. The same agent that can call your API can run inside GitHub Actions and respond to issues, pull requests and failed builds.

Setup

The quickest route is to run /install-github-app inside Claude Code. It installs the Claude GitHub App on the repository and adds your ANTHROPIC_API_KEY as a repository secret. You need admin access to the repo. Manual setup works too: install the app, add the secret, and add a workflow that uses anthropics/claude-code-action@v1.

Workflow triggers decide when Claude runs: a label, a comment, a new PR or a failed build. After that, anyone can mention @claude in a pull request or issue comment and Claude will pick it up: answer a question, review the diff, or implement a fix and push it to a branch.

What I Would Automate

  • Issue to PR. When an issue gets one of the labels you choose (say claude-fix), Claude reads the issue body, explores the codebase, checks the contract through the billing tools, and opens a pull request with the code changes and a message that explains what changed and why.

  • Code review. On every PR, Claude reviews the diff with a narrow focus: does the client code match the OpenAPI contract, are authentication headers present, are status codes and errors handled, does anything call a deprecated endpoint. It posts the feedback as a review comment on the PR.

  • CI failures. When a build fails, Claude will analyze the logs, run tests, and either fix the failing test or explain the root cause in a comment. Contract mismatches are the classic one: the API now returns invoice_status, the client still expects status.

A review workflow looks roughly like this:

YAML
name: claude-review
on:
  pull_request:
    types: [opened, synchronize]
jobs:
  review:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v4
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Review the diff in this PR against openapi/v2/public.yaml.
            Flag wrong fields, missing auth headers, unhandled errors
            and deprecated endpoints. Comment only. Do not push changes.

The action knows which PR number triggered it, so the prompt does not need to.

The Bit Everybody Forgets

A GitHub Actions runner on ubuntu-latest cannot reach the MCP server on your laptop. Obviously. And yet somebody always ships the workflow first and discovers this from the error log.

For CI, either point the MCP config at a server the runner can reach (a staging API with a gateway in front of it, or a tunnel), or do not give CI the API tools at all. Most code review and CI triage only needs the spec file and the tests, which are already in the repository. My call: start CI with no MCP tools. Add them only when a job genuinely needs live data.

The other difference worth spelling out. In the terminal, you watch every step and approve tool calls as they happen. In a GitHub Action, the process runs on its own and you see the result as a comment or a PR. So the CI version should have fewer tools, narrower permissions and a prompt that says exactly what it may and may not do.

Flow from a labelled GitHub issue through GitHub Actions and Claude Code to a pull request reviewed by a human, with a note that CI cannot reach a local MCP server.

Security: Treat Claude Like a Service Account

Claude Code with API access is a service account that can write code. Treat it with the same controls, not fewer.

  • Least-privilege credentials. Give the MCP server a read-only API key to start with. Not your admin key "because setup was faster".

  • Allowlist tools and commands. Use the permission settings for MCP tools and for shell commands like curl, database CLIs and deployment scripts. Disabling capabilities you do not need is the cheapest security you will ever buy.

  • Branch protection on main. Claude-created commits land through reviewed pull requests, with code owners on sensitive components. No exceptions for the robot.

  • Secrets stay out of the repo. Environment variables locally, repository secrets in CI, a vault in production. Never in .mcp.json, never in CLAUDE.md, never in a prompt.

  • Treat every MCP server as a dependency. Version it, pin it and review updates, exactly like your other dependencies. Official reference servers have shipped security bugs too. Tool descriptions from a third-party server go straight into your model's context, which makes them a prompt injection route.

  • Watch for injection through data. If a tool returns user-written text (support tickets, issue comments), that text can contain instructions. Keep write tools behind approval so a malicious ticket cannot talk Claude into a refund.

I went into SSRF, token handling and tool policies in much more depth in my MCP server security guide. If the API runs inside your network, my article on running a self-hosted MCP server covers the deployment side.

Surprised Pikachu meme: a developer gives Claude Code an admin key and auto-approves every tool, then is shocked when it issues refunds in production.

Keep It Maintainable

A Claude Code integration rots like any other integration. These habits keep it working:

  • Keep CLAUDE.md short and specific. To ensure Claude actually follows it, tell Claude where the spec lives, which tools to use for what, and the API's rules: rate limits, idempotency keys, pagination. Short files get followed. A 2,000-line CLAUDE.md gets skimmed, by Claude and by you.

  • Package repeat jobs as skills or commands. "Add an endpoint", "update the request and response models", "regenerate the client after a spec change". Same steps every time, fewer surprises.

  • Use hooks for the boring checks. A hook that runs the spec validator and the linter before Claude finishes a task catches drift before it reaches a PR.

  • Regenerate tools when the spec changes. If you hand-wrote the server, that is a code change. With the gateway, it is another add-spec. Either way, put it in the same PR as the spec change.

  • Prune tools every few months. Every exposed endpoint increases surface area. If Claude has not called a tool in a month, remove it.

  • Trace what Claude actually calls. Which tools it uses, which fail, where it gets blocked waiting for approval. Without that, you are tuning on vibes.

That last one is also why I care about observability at Fetch Hive. The hosted gateway keeps request logs for every tool call, which is usually how you find out that one badly described tool is getting called for everything. If you want the architecture behind that, my piece on MCP gateway architecture explains where the logging and policy layer sits. It does not replace your own CI checks or code review. It just shows you what the agent did.

GIVE CLAUDE CODE YOUR API

Turn your OpenAPI spec into tools Claude Code can call.

Generate MCP tools from your OpenAPI spec in Fetch Hive and pick exactly which operations Claude Code gets. Test calls in the playground, then manage access tokens, limits and request logs in one place.

Practical Checklist

Do more of this:

  • Keep the OpenAPI spec in the repo and point CLAUDE.md at it.

  • Start with one non-critical service and three read-only tools. Do your testing against staging, not production.

  • Register servers with --scope project and commit .mcp.json with ${VAR} placeholders.

  • Allow read-only tools, deny money and deletes, in .claude/settings.json.

  • Test with claude mcp list, /mcp and one real prompt before you automate anything.

  • Start GitHub Actions in comment-only review mode on one repository.

  • Measure what changes (review time, CI fixes, rejected PRs) before you expand to more repos and more operations.

Avoid this:

  • Exposing every endpoint because the generator could.

  • Admin keys, committed secrets, or keys in tool arguments.

  • Letting a tool argument choose the host.

  • Auto-approving tools that write, delete or spend money.

  • Wiring CI to an MCP server that only exists on your laptop.

The Takeaway

Connecting an OpenAPI API to Claude Code is not hard. It is one MCP server, one claude mcp add, and a permissions file. The difficult part is deciding what Claude is allowed to touch, and that is a decision, not a technology.

Start read-only. Get the local setup boring. Then let Claude review pull requests and triage CI failures, with a human on the merge button.

Do that and Claude stops guessing what your API looks like. It reads the contract, calls the real thing, and shows its work in a PR. That is the whole point.

THE FETCH HIVE FIELD NOTES

Make your APIs useful to AI.

Get practical guides on MCP, API integrations and connecting AI tools, alongside lessons from building Fetch Hive.

Get Fetch Hive guides and occasional product updates. Unsubscribe anytime.

Share this post

THE FETCH HIVE FIELD NOTES

Make your APIs useful to AI.

Get practical guides on MCP, API integrations and connecting AI tools, alongside lessons from building Fetch Hive.

Get Fetch Hive guides and occasional product updates. Unsubscribe anytime.