cd /news/ai-agents/mcp-vs-direct-api-integrations-and-c… · home › topics › ai-agents › article
[ARTICLE · art-182349] src=flaviocopes.com ↗ pub= topic=ai-agents verified=true sentiment=· neutral

MCP vs direct API integrations (and CLIs): when each one wins

A benchmark on Node.js 22 comparing direct HTTP API calls, local CLIs and MCP servers found that MCP's M+N integration math only pays off when an AI agent crosses an ownership or runtime boundary, and that scaling an MCP server from 3 tools to 15 tools inflates prompt token overhead. The author measured startup time, per-call latency, prompt token overhead with OpenAI gpt-4.1-mini and lines of glue code for the same 3-operation local HTTP task service built each way, concluding that teams with a single AI host (M=1) add a protocol layer and an extra network or pipe hop for portability they don't need. The analysis argues MCP wins when exposing a product to third-party AI hosts or when several AI hosts run on one machine and need a stateful or authenticated integration.

recommendation

Default to direct API tool functions when your backend is the only AI host, and adopt MCP only when exposing tools to third-party hosts or sharing stateful integrations across multiple hosts.

more in playbook: Designing agent systems
read33 min views1 publishedDec 5, 2026
MCP vs direct API integrations (and CLIs): when each one wins
Image: Flaviocopes (auto-discovered)

By Flavio

Tagged: AI

Compare direct HTTP APIs, local CLIs, and MCP servers with real latency and token benchmarks, auth and versioning tradeoffs, and a practical decision guide.

When you connect an AI agent to an external system, you have three options. You can call the HTTP API directly from your own tool functions, wrap the system in a local CLI and let the agent run shell commands, or put an MCP server in front of it.

A lot of teams now reach for MCP by default. Others avoid it completely because one bloated server ate a third of their context window. Both reactions miss the engineering tradeoffs.

Each pattern puts the work in a different layer. Direct API calls keep everything inside your application process. A CLI pushes tool discovery to --help and pays a process spawn cost on every command.

An MCP server adds a standard protocol boundary between the AI host and your integration. That gives you portability and credential isolation, at the cost of extra wiring and, if you expose too many tools, heavy prompt overhead.

I wanted real numbers instead of opinions, so I wired the same 3-operation local HTTP task service using each approach on Node.js 22. I measured startup time, per-call latency, prompt token overhead with OpenAI gpt-4.1-mini, and lines of glue code.

Then I scaled the MCP server from 3 tools to 15 tools to see what happens to the token budget.

In this post, we’ll look at the M-by-N integration math and the benchmark data. We’ll also cover the parts a latency chart hides: authentication, multi-tenancy, versioning, error recovery, debugging, and hybrid patterns like deferred and Code Mode.

The M-by-N promise, and when M is 1 #

The original pitch for MCP comes down to simple arithmetic. Suppose you have M AI applications (Claude Code, Cursor, Codex, a desktop assistant) and N external systems (GitHub, Postgres, Sentry, Stripe, Linear).

Without a shared protocol, every AI app needs its own custom integration for every external system. That leaves you with M * N connectors to build, authenticate, and maintain.

MCP puts a standard contract in the middle. Each AI host implements one MCP client layer, and each external system ships one MCP server.

That drops the total number of integrations from M * N to M + N. Once you build a server, every compatible host can discover its tools right away without custom glue.

The math holds up, and it explains why MCP caught on so quickly with SaaS vendors and editor makers. Astro built one docs MCP server and it immediately worked in Claude Code, Cursor, and Codex.

The trap is applying M * N thinking when M = 1.

Say you’re building an AI support assistant or a workflow agent inside your own web app. There’s only one AI host here: your backend.

Your backend already owns the prompt loop, calls the model provider SDK, and runs tool handlers. It also already talks to your Postgres database, billing API, and internal microservices.

Plug M = 1 into both formulas. Direct integrations need 1 * N = N tool adapters. Adding MCP requires 1 + N moving parts: an MCP client inside your backend plus N separate MCP servers, along with their transports, auth tokens, process supervision, and schema versioning.

You end up adding a protocol layer and an extra network or pipe hop to solve a cross-host portability problem you don’t have.

Even when M = 2, like a backend API and an internal Slack bot in the same TypeScript monorepo, importing a shared internal package with typed functions is easier than running JSON-RPC between your own services.

MCP only starts paying back its protocol overhead when you cross an ownership or runtime boundary. That happens in two cases:

  • You’re exposing your product to third-party AI hosts you don’t control.
  • You use several AI hosts on your own machine and want to configure a stateful or authenticated integration once instead of rewriting it per editor.

Before you pick a protocol, count M. If M is 1 and stays 1, a plain function calling an HTTP API or SDK is almost always the right starting point.

Three ways to wire the same service #

Before we look at the numbers, let’s clear up a common misconception. The language model itself doesn’t speak MCP, HTTP, or bash.

At the model API boundary, every integration boils down to the same tool calling loop. The host sends an array of JSON tool definitions, and the model replies with a tool name and JSON arguments. Then the host runs the tool and feeds the text result back into the next turn.

The difference between direct APIs, CLIs, and MCP lives entirely between your agent host and the target service:

In the direct API pattern, your agent harness registers one tool definition per operation right in code. When the model requests update_task, your code validates the JSON arguments in memory, calls fetch() (or an official SDK client), and returns a trimmed JSON string.

There’s no child process, no extra protocol framing, and no discovery handshake.

In the local CLI pattern, your harness gives the model a single generic shell tool (or a dedicated CLI runner). A small script or binary wraps the service, parses flags, calls the HTTP API, and prints JSON or plain text to stdout.

Instead of every endpoint schema into the prompt upfront, you give the agent a short skill description or let it run tasks --help when needed. Every call spawns a fresh OS process, runs the command, and exits.

In the MCP server pattern, the host creates a protocol client that talks to a separate server. That connection runs over stdio (a long-lived child process speaking newline-delimited JSON-RPC 2.0) or Streamable HTTP (an HTTP endpoint returning JSON or Server-Sent Events).

At startup or on demand, the host calls tools/list, converts the server’s schemas into model tool definitions, and forwards each tool call as a tools/call JSON-RPC request. The server makes the real HTTP request and returns structured content plus text blocks.

Notice what moves as you go from left to right:

  • Direct APIs : the host owns the code, types, credentials, and schemas.
  • Local CLI : the shell runs commands, and the binary owns its flags and help text.
  • MCP : the server owns the schemas, execution, and credentials, while the host only speaks JSON-RPC.

Measuring the three patterns on the same task service #

Diagrams make every option look tidy. Real numbers show where the friction sits.

To compare the three patterns fairly, I built a small local HTTP task service with three operations: listing tasks, reading one task by ID, and updating a task’s status. Every adapter hit that same localhost HTTP service on Node.js 22, keeping network jitter and database speed constant.

I also wanted real prompt token counts instead of rough character-to-token estimates. So I sent the tool definitions for each setup through OpenAI gpt-4.1-mini and recorded the measured prompt tokens.

First, let’s see how thin the integration layer is for each setup.

The direct fetch() wrapper needs zero transport boilerplate. You define the three tool schemas for the model and map each tool name to a fetch() call:

const BASE = 'http://127.0.0.1:4010'

export async function runDirectTool(name, args) {
  if (name === 'list_tasks') {
    const q = args.status ? `?status=${encodeURIComponent(args.status)}` : ''
    return fetch(`${BASE}/tasks${q}`).then((r) => r.json())
  }
  if (name === 'get_task') {
    return fetch(`${BASE}/tasks/${encodeURIComponent(args.id)}`).then((r) => r.json())
  }
  if (name === 'update_task') {
    return fetch(`${BASE}/tasks/${encodeURIComponent(args.id)}`, {
      method: 'PATCH',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ status: args.status }),
    }).then((r) => r.json())
  }
  throw new Error(`Unknown tool: ${name}`)
}

That entire adapter is 14 lines of glue code. Every type, header, and error check lives right next to your agent loop.

The local CLI wrapper is almost as small at 16 lines of glue, and the model only sees one shell tool on the host side. On disk, a Node.js script parses process.argv, hits the same local HTTP endpoints, and prints JSON to stdout:

#!/usr/bin/env node
const [cmd, arg1, arg2] = process.argv.slice(2)
const BASE = 'http://127.0.0.1:4010'

if (cmd === 'list') {
  const q = arg1 ? `?status=${encodeURIComponent(arg1)}` : ''
  console.log(await fetch(`${BASE}/tasks${q}`).then((r) => r.text()))
} else if (cmd === 'get') {
  console.log(await fetch(`${BASE}/tasks/${encodeURIComponent(arg1)}`).then((r) => r.text()))
} else if (cmd === 'update') {
  const res = await fetch(`${BASE}/tasks/${encodeURIComponent(arg1)}`, {
    method: 'PATCH',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ status: arg2 }),
  })
  console.log(await res.text())
} else {
  console.error('Usage: tasks <list [status]|get <id>|update <id> <status>>')
  process.exit(1)
}

For the MCP stdio server, you import the MCP SDK, create a server instance, and connect the stdio transport. Then you register each tool with its input schema and a handler that returns MCP content blocks.

Even for three simple operations, that takes 38 lines of glue code, and it grows with every tool you add. I also measured a second MCP setup exposing 15 tools on the same stdio server, representing a modest real-world API surface like tasks plus comments, labels, assignees, and milestones.

Here is the raw terminal output from running the benchmark harness on Node.js 22:

Putting those numbers in a table makes the tradeoffs jump off the screen:

Pattern p50 Call p95 Call Cold Start Prompt Tokens / Turn Glue LOC
Direct fetch() tool (3 tools) 0.42 ms 2.15 ms 0 ms 133 14
Local CLI (spawn per call) 84.7 ms 109.72 ms 84.7 ms 52 (1 shell tool) 16
MCP stdio (3 tools) 0.43 ms 1.73 ms 54.1 ms 133 38
MCP stdio (15 tools) 0.43 ms 1.73 ms 54.1 ms 901 38+

This chart makes the split between latency cost and token cost even clearer:

Two results here tend to surprise people who debate MCP from theory alone. First, persistent MCP stdio adds almost zero latency per call once it’s running. Second, a 3-tool MCP server uses the same number of prompt tokens as 3 direct API tools, while a 15-tool server multiplies your per-turn prompt overhead nearly sevenfold.

Let’s unpack each axis, starting with latency.

Startup cost vs per-call latency #

Look closely at the latency column in the table. Direct fetch() and persistent MCP stdio both sat right around 0.42 ms median (with p95 around 2 ms).

That 0.01 ms median gap is noise. Once an MCP stdio server is running, sending a JSON-RPC message over an open OS pipe, parsing it in Node.js, calling localhost HTTP, and writing the reply to stdout costs almost nothing. Anyone telling you to skip local MCP servers because “JSON-RPC over stdio is slow” hasn’t measured it.

Where MCP stdio does pay a latency cost is startup. Spawning the Node.js server process and getting it ready took 54.1 ms cold start in this test.

Because the server stays alive for the whole session, you only pay that 54.1 ms once. Be careful with your launcher, though: starting a server with npx -y instead of a local binary pushes startup much higher.

In my MCP walkthrough, spawning the filesystem server locally took 121 to 128 ms. Using npx -y jumped that to 317 to 341 ms warm and 518 ms on a cold cache.

The local CLI sits at the other extreme. Because the shell tool forks a fresh Node.js process on every call, its cold start and median per-call latency are identical: 84.7 ms, with a p95 of 109.72 ms. Per call, spawning a Node.js CLI is roughly 200 times slower than calling fetch() in process or messaging a warm stdio server.

Does 84.7 ms matter? It depends on your workload.

In an interactive coding session, a frontier model spends 2 to 10 seconds thinking and streaming before making a tool call. Adding 84.7 ms to run tasks list or git status is less than 2 percent of the turn, and you’ll never notice it. Even 5 CLI calls across a 3-minute debugging session add up to under half a second of spawn overhead.

Now consider a programmatic agent workflow or a data-processing loop inside your backend. Say a pipeline processes 50 items and makes one tool call per item.

With direct fetch() or a warm MCP server, 50 local calls add around 21 ms of adapter overhead. With a Node.js CLI spawned per call, 50 calls burn 50 * 84.7 ms = 4.23 seconds just booting V8 fifty times before doing any work.

If your CLI is written in Python with heavy imports or launched through uv run, that spawn tax can easily hit 300 to 600 ms per call. Compiling a CLI to a native binary in Go, Rust, or Swift shrinks startup to a few milliseconds, though you still pay OS process creation on every call.

Remote MCP over Streamable HTTP has a different latency profile. Every tools/call crosses the public internet, paying DNS, TLS, and network round-trip latency on top of the upstream request.

Deploying the remote MCP server on a serverless platform or a stateless HTTP worker avoids sticky-session bottlenecks across load balancers, while inheriting cold starts whenever a region scales from zero. In what is MCP, calling Astro’s public HTTP MCP server from Italy took 209 to 289 ms just for tools/list and 487 to 522 ms for a single search call.

The latency rule is easy to remember:

  • Direct API calls pay 0 ms startup and minimal per-call overhead.
  • Local stdio MCP pays startup once (54.1 ms here) and runs near direct-call speed (0.43 ms ) after that.
  • A local CLI pays startup on every call (84.7 ms here), which disappears in human-paced chat and hurts in tight loops.
  • Remote HTTP MCP pays a full network hop on every discovery and tool call.

The context window tax: 52 tokens vs 901 tokens #

Context consumption breaks more agent integrations than latency ever does.

Look at the token counts from our benchmark again. Both the 3-tool direct API adapter and the 3-tool MCP stdio server injected 133 prompt tokens per turn into gpt-4.1-mini.

That makes sense once you remember how tool calling works: the model receives the same JSON Schema definitions either way. MCP adds zero per-tool token bloat when both setups expose the same three narrow schemas.

The problem starts because production MCP servers rarely stop at three tools. Teams wrapping a SaaS REST API often auto-generate one tool per endpoint or expose the entire product surface to cover every possible workflow.

In our benchmark, growing the MCP server from 3 tools to 15 tools pushed prompt overhead from 133 to 901 tokens per turn. That’s a 6.8x jump for one modest server.

Meanwhile, the local CLI wrapper stayed flat at 52 tokens per turn. The model only ever receives one shell tool schema, whether the CLI has 3 subcommands or 40.

Now multiply those numbers across a 20-turn conversation. Stateless LLM APIs resend the full tool list and message history on every turn:

  • Local CLI wrapper (1 shell tool): 52 * 20 = 1,040 schema tokens across 20 turns.
  • Direct API or focused MCP server (3 tools): 133 * 20 = 2,660 schema tokens across 20 turns.
  • Moderate MCP server (15 tools): 901 * 20 = 18,020 schema tokens across 20 turns.

And 15 tools is small compared to many real MCP servers. When I ran /context in Claude Code on this repository (documented in what is MCP), four real servers produced these footprints:

  • Railway MCP server: 71 tools, 37,264 tokens (one tool alone, update-service , took roughly 3,300 tokens).
  • Borumi video editor MCP server: 49 tools, 13,394 tokens.
  • Polar MCP server: 5 tools, 3,264 tokens.
  • Claude Docs MCP server: 8 tools, 2,132 tokens.

Just those four servers totaled 133 tools and 56,054 tokens before a single user message entered the window. Even the official filesystem MCP server with 16 tools takes 3,635 tokens.

People often point to prompt caching as the fix. Caching does cut your dollar cost on repeated prefixes, since cached input tokens get a steep discount after turn 1.

Still, caching only solves part of the problem. Even with a 90 percent cache hit rate, three costs stick around:

  1. Cached tokens still eat context window space. Starting 56,000 tokens deep leaves less room for source files, diffs, and test logs before the host has to compact the conversation.
  2. Tool selection gets less accurate as the menu grows. Asking a model to pick from 71 tools with overlapping parameter names wastes reasoning steps and causes more malformed calls.
  3. Dynamic tool lists break the cache prefix. If an MCP server advertises listChanged: true and swaps tools mid-session, or if your harness toggles servers between turns, you invalidate the cached prefix and pay full cache-write prices again.

A local CLI skips eager schema completely. The host sends the 52-token shell tool schema, plus a short skill line if you use one (my Things CLI skill description is 264 characters).

If the user never mentions tasks, the agent spends zero tokens learning the task flags. When the user asks to update a task, the agent runs tasks --help or tasks capabilities once, reads the exact syntax for that turn, and executes the command.

Here is how those three schema strategies play out across turns:

Look at the third section of that diagram: **deferred MCP **. Modern hosts like Claude Code stopped injecting every MCP schema upfront for this reason.

On that 56,054-token setup, Claude Code loaded only 631 tokens upfront and deferred the remaining 55.4k tokens behind an internal ToolSearch tool. When the model needs a Railway or filesystem tool, it searches for the name, pulls that one schema into context, and calls it.

Deferred narrows the gap between a big MCP server and a CLI, at the cost of one extra model turn to search before calling. If you own the host or build your own agent backend, direct API tools are even simpler: pass only the 3 to 5 tools needed for the current route or workflow state, keeping both prompt tokens and discovery turns near zero.

Authentication, secrets, and permission boundaries #

If latency and tokens were the whole story, direct APIs and CLIs would win almost every time. Authentication and trust boundaries change the picture.

Each pattern stores credentials in a different place. That decides both who can steal a secret and how cleanly you can serve multiple users.

Direct API: tightest multi-tenant boundary

In a direct API integration inside your own backend, credentials never cross a process boundary to an external host and never enter anything the model can read. Your server authenticates the request with a session cookie or JWT, fetches that user’s scoped OAuth token or API key from your secrets store, and injects it into fetch().

The model also can’t forge identity. If a user asks the agent to update task 42, your handler reads taskId from the model’s arguments and takes userId and workspaceId from your authenticated server session.

Even if a prompt injection hidden in a task description tells the model to pass another customer’s accountId, the tool schema doesn’t even accept an accountId field.

For multi-tenant SaaS products running internal AI agents, direct in-process API calls give you the clearest authorization model.

Local CLI: convenient for one developer, risky for shared shells

A local CLI flips that security model. It runs as a child process under your OS user account, usually reading credentials from environment variables, dotfiles like ~/.config/, or the macOS Keychain.

On your own laptop, while you’re supervising a coding agent, that feels great. Tools like gh, wrangler, and custom scripts authenticate once and work in any terminal.

The downside is how much damage a generic shell tool can cause. If an agent calls your CLI through Bash, it holds shell access in that same environment.

Unless you isolate the agent or put secrets behind a broker, a prompt injection inside a fetched web page or GitHub issue can tell the model to run printenv, cat ~/.netrc, or read a token from a config file. Keeping deployment secrets out of agent environments takes real work once the shell has ambient credentials.

Multi-tenancy is awkward with a local CLI too. Switching between three customer accounts or workspaces means juggling profile flags, environment variables, or separate config directories, and trusting the model to pass --profile staging instead of --profile production every time.

MCP server: credential isolation and standardized user auth

MCP draws a clean line between the AI host and the credentials.

With a local stdio MCP server, the host starts the server with only the environment variables assigned to it in config, or the server reads a specific entry from the macOS Keychain. The model never sees the API key, and other MCP servers on the same host can’t read it either. If the Railway server holds a Railway token and the filesystem server reads a folder, neither can touch the other’s secrets.

With a remote Streamable HTTP MCP server, the protocol defines OAuth 2.1 authorization flows. When a user connects your SaaS product to Claude Code or Cursor, the host opens a browser consent screen showing the exact workspace and scopes being granted.

The user can revoke that connection anytime from your settings page. Every request arrives at your server with a per-user bearer token, giving you the same server-side tenancy checks as your regular web API.

MCP also supports protocol-level hooks that a plain CLI can’t easily match. Elicitation lets a server mid-call and ask the host to show a structured confirmation form before running a dangerous or irreversible action.

In my Registrar MCP server (detailed in MCP server design), buying a domain can’t happen from model arguments alone. The server asks the host to display the exact domain, USD total, and a non-refundable checkbox before charging Cloudflare.

There are two security caveats to remember for real MCP deployments:

First, MCP tool annotations (readOnlyHint, destructiveHint, openWorldHint) are only advisory hints written by the server, so the host can’t treat them as kernel-level enforcement. A buggy or malicious server can label a destructive tool as read-only, which means you still need server-side authorization and host-side approval rules.

Second, a local stdio MCP server still runs under your local user account unless you sandbox it. On macOS, a background stdio process that reads another app’s protected container folder can trigger repeated OS permission dialogs every time a new agent session starts.

I ran into that problem myself and replaced my Things MCP server with a CLI. things-mcp opened the Things SQLite database on disk and tripped macOS’s “access data from other apps” dialog all day. A small CLI talking to the running Things app over AppleScript asked once and never bothered me again.

Versioning, error handling, and debugging #

Day one is about getting a tool call to return JSON. Month six is about what happens when an upstream API changes a field, a request times out at 2 a.m., or the agent gets stuck retrying a bad argument.

Versioning and coupling

Direct API integrations give you tight, compile-time coupling. Your tool schemas, request payloads, and response parsers live in the same repo as your agent loop.

If you use TypeScript and Zod, changing a response field or upgrading an SDK breaks tsc --noEmit in CI before anything ships. You only have one version number to track: your app’s commit SHA.

Local CLIs sit in the middle, where the contract is the subcommand name, flags, exit code, and --json stdout structure. That loose coupling works well when one CLI serves both humans in a terminal and agents via a skill file.

You can ship CLI updates independently of your agent host, as long as you keep existing flags and JSON keys backward-compatible and update --help or capabilities when you add new subcommands.

MCP introduces three version axes that can drift on their own:

  1. The protocol revision , such as2026-07-28 stateless requests versus older2025-11-25 or2025-06-18`` initialize handshakes. A modern-only client talking to an older server gets a400 and has to negotiate down.
  2. The SDK version , like moving from v1’s monolithic@modelcontextprotocol/sdk to v2’s split@modelcontextprotocol/server packages.
  3. The server’s tool schemas and behavior . If your host config runsnpx @some-vendor/mcp@latest , an upstream publish can silently rename tools or change required fields the next time your editor restarts. Pinning exact package versions and diffingtools/list on upgrades is good hygiene.

Error handling and recovery

Models recover well from concise, specific error messages. They spiral into retry loops when handed vague status strings or giant stack traces.

With a direct API wrapper, you control the full HTTP layer. Your code sees exact 401, 404, 409, 429, or 503 status codes, reads Retry-After headers, and handles exponential backoff for transient 503 errors invisibly inside the harness.

You only pass a clean domain error to the model when it needs to change course (like “Task 99 does not exist. Call list_tasks to check valid IDs.”). You also decide which errors are safe to retry using idempotency keys (unique request IDs that prevent duplicate writes).

With a local CLI, errors flow through exit codes (0 vs non-zero) and stderr. Modern coding models have seen millions of terminal errors during training.

So exit code 1 plus a crisp stderr line like Error: unknown status "archived". Expected one of: todo, in_progress, done is usually enough for the model to fix its next command on the first retry.

The rough edge is existing CLIs that dump 50 lines of Node or Python stack traces, ANSI color escape codes, or interactive spinners onto stderr. That burns tokens and confuses the model unless you pass --no-color or wrap the tool cleanly.

With MCP, errors split across two wire channels (covered in how to build an MCP server). Protocol-level failures (unknown method, missing _meta, invalid protocol version, unknown tool name) return a JSON-RPC error object with numeric codes like -32602. Most hosts log those internally instead of showing them cleanly to the model.

Application-level failures (invalid arguments caught by Zod, missing records, denied permissions) return a normal JSON-RPC result with isError: true and an explanation inside content. The model sees isError: true results and can self-correct.

Pay attention to unhandled exceptions in handlers, though. The SDK catches them and sends the raw error message back to the model, which can leak internal file paths or database details unless you catch and sanitize errors at the handler boundary.

MCP also lets a server return both content (text for humans and models) and structuredContent (JSON validated against an outputSchema). That helps programmatic hosts parse responses without fragile regexes over prose.

Debugging and testability

When something breaks at runtime, how fast you can reproduce it decides how fast you fix it.

Direct API integrations are the easiest to test and debug. You can run standard unit tests with mocked fetch() calls, set IDE breakpoints inside your tool handler, attach correlation IDs to structured logs, and inspect raw HTTP traffic in your normal APM or proxy.

Local CLIs are a close second, and often the fastest to debug by hand. When an agent call fails, you copy the command from the transcript, paste it into your terminal, and run it.

You see stdout, stderr, and the exit code in one second. You can pipe output through jq or head, benchmark it with time, and write shell integration tests without a protocol harness.

MCP servers add an extra layer to debug because you can’t just paste a tool call into bash. For stdio servers, stdout is reserved strictly for JSON-RPC frames. One stray console.log() from your code or a dependency corrupts the wire stream and makes strict clients drop the connection, so every log line has to go to stderr.

To isolate whether a bug lives in the server, the host, or the model, you have three main tools: the official MCP Inspector (web UI or --cli mode), the host’s debug mode (claude --debug), or piping raw JSON-RPC into stdin by hand.

Once you wire the Inspector CLI into your test script, testing is repeatable, even though it takes more setup than calling a function or running a CLI command.

Architectural comparison across the three patterns

Here is how the three approaches compare across the engineering dimensions that matter in production:

Dimension Direct HTTP / SDK API Local CLI + Skill MCP Server (stdio / HTTP)
Best host topology Single app backend ( M = 1 ) Local coding agents with shell access Multiple AI hosts ( M > 1 ) or external users
Cold start (measured) 0 ms 84.7 ms on every call 54.1 ms once per stdio session
Warm per-call latency (measured) 0.42 ms p50 / 2.15 ms p95 84.7 ms p50 / 109.72 ms p95 0.43 ms p50 / 1.73 ms p95 (stdio); RTT on HTTP
Prompt schema overhead (measured) 133 tok (3 tools); scales linearly 52 tok (1 shell tool); help loaded on demand 133 tok (3 tools); 901 tok (15 tools) unless deferred
Glue code complexity (measured) Lowest (14 LOC for 3 ops) Low (16 LOC + skill/help text) Highest (38+ LOC, SDK, transport wiring)
Credentials and multi-tenancy Server-side per-request auth; strongest tenancy Local env, config files, or Keychain; weak multi-tenancy Process isolation (stdio) or OAuth 2.1 (HTTP)
Long-lived stateful sessions In-process memory or DB session Stateless per invocation Native persistent connection (stdio / stateful HTTP)
Error control Full HTTP status, headers, retries Exit codes + stderr text Split JSON-RPC protocol errors vs isError: true
Debugging experience Standard tests, IDE breakpoints, HTTP logs Copy-paste exact command in terminal MCP Inspector, stderr logs, JSON-RPC wire traces
Cross-host portability None (tied to your app code) High (any agent with a shell) Highest (standard contract across hosts)

Hybrid patterns: getting the best of both worlds #

You don’t have to treat direct APIs, CLIs, and MCP as mutually exclusive camps. Most strong production setups mix them to avoid the worst failure mode of each pure pattern. Three hybrid patterns work well today.

1. Deferred and gateway catalogs

Say you need MCP’s cross-host portability and OAuth boundary, but your server (or group of servers) exposes dozens of tools. Eager schema injection will eat your context budget alive.

The fix is turning tool discovery into a two-step lookup: search -> describe -> call.

Some hosts do this out of the box now. Claude Code defers MCP tool definitions automatically and exposes a lightweight ToolSearch tool, so the model only loads the JSON Schema for the specific tool it wants to call.

If you use several hosts (like Codex, Cursor, and Claude Code) or need multiple accounts for the same service (say three Notion workspaces or Stripe accounts), you can move that catalog into a local or remote gateway like Executor.

Each host connects to one MCP endpoint, and the gateway indexes MCP servers, OpenAPI specs, and GraphQL endpoints behind one searchable catalog with named account connections and per-tool approval rules. Your agent starts with a tiny tool footprint instead of 50,000 tokens of schemas, and your credentials stay in one place.

2. Coarse workflow tools and Code Mode

A huge chunk of MCP bloat has nothing to do with the protocol. It comes from wrapping a granular CRUD REST API one-to-one into 40 tiny tools: list_projects, get_project, list_tasks, get_task, list_comments, create_comment, and so on.

Every tiny call forces another LLM round trip, dumps raw unfiltered JSON into the context window, and bloats the upfront tool list.

You have two clean ways out. The first is designing coarse, task-oriented tools. Instead of exposing 12 low-level endpoints, expose 3 or 4 workflow operations that match real jobs (like fetching a task with its recent comments already joined, or applying a validated batch update in one call).

Both direct API wrappers and MCP servers get cheaper and more accurate when you cut 15 tools down to 4.

The second is Code Mode. Instead of making the model run 16 sequential tool calls and read 1,000 lines of raw JSON into context, the host lets it write a short JavaScript snippet. That script calls tools, loops over lists, runs independent calls with Promise.all(), filters noise, and returns one compact summary.

When I tested Code Mode in Claude Code, checking broken local links across 8 Markdown files dropped from 35 seconds to 15 seconds. All 8 file reads and 16 shell checks collapsed into one script, and the 1,394-line README never entered the model’s context. Even 100 consecutive production builds ran inside one for loop and returned a tiny summary object.

Code Mode pairs well with both APIs and CLIs. Instead of exposing 30 narrow tools, you expose a typed SDK or a small set of scriptable primitives and let the model compose them in code.

3. One core service, thin adapters

If you own a product and want both an internal AI feature and external agent access for customers, don’t duplicate business logic inside an MCP server or a CLI.

Put every domain rule, authorization check, credit limit, rate limit, and idempotency guard inside one shared service layer or your primary HTTP API. Then wrap thin, boring adapters around it:

  • Your web app’s AI assistant calls the service functions directly in process (0 ms cold start, full compile-time types, zero protocol overhead).
  • Power users and local coding agents get a small CLI calling the same HTTP endpoints with --json output and acapabilities command.
  • External AI hosts get a focused MCP server translating OAuth tokens and JSON-RPC tool calls into the same service operations.

Because each adapter only handles argument parsing and formatting, a bug fix or permission check in the core service protects your web UI, direct agent tools, CLI, and MCP server at once.

A practical decision tree

When a new integration lands on your desk, answer four questions in order:

You can also map the choice directly to common project shapes:

Scenario Best fit Why it wins Main tradeoff to watch
AI assistant inside your own web app ( M = 1 ) Direct HTTP / SDK tool functions Zero extra hops, 0 ms cold start, strict server-side multi-tenancy, compile-time typing Tied to your codebase; not pluggable into external editors
SaaS exposing product actions to customers’ editors ( M > 1 ) Remote Streamable HTTP MCP server Standard OAuth 2.1 login, per-user revocation, works across Claude Code, Cursor, and Codex Keep tool count small or pair with deferred search; maintain protocol versions
Local developer utility or one-shot Mac automation Local CLI ( --json +capabilities ) + skill Tiny 52 -token upfront footprint, no background process, trivial terminal debugging 84.7 ms spawn cost per Node call; weak credential isolation if shell is untrusted
Long-lived stateful desktop app (e.g., video editor) Local stdio MCP server Persistent connection holds transactions and timeline state with 0.43 ms warm calls Requires process lifecycle management and schema budgeting
Multiple accounts of the same service across 3 editors MCP gateway (e.g., Executor) with deferred search Named per-account connections, one auth store, lazy search -> describe -> call schemas Adds a local or remote daemon you have to keep running
High-frequency batch agent pipeline (50+ calls/run) Direct API functions or Code Mode script Eliminates repeated process spawns and collapses multi-step tool turns into one script Code Mode requires careful sandboxing and approval rules on dynamic scripts

How I choose across my own apps and coding agents #

I use each of the three patterns in my own work, and my rule of thumb has gotten shorter over the past year.

Whenever I build an AI feature inside one of my web apps or backend workers, I skip MCP completely and write direct API or database tool functions. I own the host, the credentials already live in my server environment, and I only want to give the model the 3 to 5 tools needed for the current job. Putting a JSON-RPC server between my own code and my own API would only add glue code (38 lines instead of 14) and another failure surface for no benefit.

For my personal coding agents (Claude Code, Codex, Cursor) talking to developer tools or one-shot Mac utilities, a CLI plus a short skill is my default. Tools like wrangler already cover Cloudflare far better than juggling three separate MCP servers.

When I build my own small utilities, I give every one --json output and a capabilities subcommand. That lets any agent learn the commands in one read without burning thousands of tokens in unrelated chats.

Replacing things-mcp (22 tools in a background Python server) with my 598-line JavaScript Things CLI paid off right away. It stopped a constant macOS folder-permission prompt, cut the startup context to a 264-character skill summary, and made every failing command easy to reproduce in my terminal.

A CLI stops being a good fit in two cases, and I drop it as soon as I hit either one:

  • The integration needs a tight loop of dozens of rapid calls (where spawning a Node.js script at 84.7 ms per call adds up to seconds of wasted time) or operates on big stateful objects inside a running app.
  • The agent has no shell access (like a hosted chat client or a locked-down sandbox) or must never share an environment with the credentials.

That’s where I keep and build MCP servers. Borumi, my video editor, stays on a local stdio MCP server with 49 tools because editing a timeline is a long, stateful conversation: open a transaction, inspect tracks, trim segments, commit. Spawning a stateless CLI on every edit would be miserable.

My Registrar server for Cloudflare domains stays on MCP for a different reason. It isolates a narrowly scoped billing token away from the agent’s shell and uses MCP elicitation to show an explicit confirmation form with the exact USD price before spending money.

And if I ship a hosted web product that customers want to drive from their own AI editors, I’d build a small, focused Streamable HTTP MCP server backed by OAuth 2.1, reusing the same service functions as the web app.

When you pick an approach for a new project, start with the simplest layer that respects your security boundary. If you own the host, call the API directly. If your coding agents have a shell and each command stands on its own, ship a --json CLI and a short skill.

Reach for MCP when you need portability across multiple hosts, isolated OAuth or Keychain credentials, protocol-level approvals, or a persistent stateful session. And when you do, keep the tool surface tight enough to earn every token it puts in the prompt.

For shaping those tool schemas cleanly and stopping runaway loops, see tool schemas and stopping conditions, and for tracking how extra tool definitions affect monthly bills, see token pricing and budgeting.

Want me to talk about your product? You can sponsor this site.

── more in #ai-agents 4 stories · sorted by recency
── more on @mcp 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/mcp-vs-direct-api-in…] indexed:0 read:33min 2026-12-05 · —