The Problem With Tool-Per-Endpoint MCP

If you've built anything with MCP (Model Context Protocol), you know the drill: every API endpoint becomes a separate tool the LLM calls one at a time. The model picks a tool, sends JSON, waits for the response, reads it, picks the next tool, sends more JSON — rinse and repeat.

This works fine when you have 10 tools. It falls apart when you have 2,500.

Cloudflare hit exactly this wall. Their API has over 2,500 endpoints. Registering each one as an MCP tool would consume over 2 million tokens of context just for the tool definitions. That's before the model even starts thinking.

Enter Code Mode 🔧

Code Mode flips the entire model. Instead of registering thousands of tools, you give the LLM two things:

  1. TypeScript type declarations for your API (~1,000 tokens)
  2. A sandbox to execute code

That's it. The model writes a JavaScript program that chains API calls with loops, conditionals, and variables — then executes the whole thing in one shot. No multi-round-trip tool calling. No context window bloat.

// Traditional MCP: 5 separate tool calls, 5 round trips tool_call("list_zones") → result tool_call("get_zone_settings", zone_id) → result tool_call("get_dns_records", zone_id) → result tool_call("get_firewall_rules", zone_id) → result tool_call("summarize", all_data) → result // Code Mode: 1 program, 1 execution const zones = await api.listZones(); const zone = zones.find(z => z.name === "example.com"); const [settings, dns, firewall] = await Promise.all([ api.getZoneSettings(zone.id), api.getDnsRecords(zone.id), api.getFirewallRules(zone.id) ]); console.log({ settings, dns, firewall }); 

Architecture: Two Patterns 🏗️

Cloudflare documents two architectural patterns for Code Mode servers:

Pattern 1: Single Code Tool

Wrap an existing MCP server with codeMcpServer(). It auto-generates TypeScript declarations for every upstream tool and exposes a single code tool. Best for APIs with a manageable number of operations.

Pattern 2: Search and Execute

For massive APIs, use openApiMcpServer() backed by an OpenAPI document. This exposes two tools:

  • search — runs model-generated code against the OpenAPI spec inside the sandbox to discover relevant operations (no actual API calls)
  • execute — runs code with an authenticated request function to actually hit the API

The full OpenAPI spec never leaves the sandbox. Only what search returns enters the model's context. This is the key insight: the model explores the API surface programmatically instead of loading it all upfront.

The Sandbox: Security Without Compromise 🔒

Letting an LLM write and execute arbitrary code sounds terrifying. Here's how it's locked down:

✅ Code runs in an isolated environment — QuickJS compiled to WASM locally, or V8 isolates on Cloudflare Workers

✅ The sandbox starts empty: no fetch, no process, no require, no timers, no filesystem

✅ Only console (for output) and a single bridge function to the host are injected

✅ API keys and server URLs stay on the host — generated code never sees credentials

✅ Each run is capped at 64 MB memory and a 30-second deadline

✅ Responses are truncated at ~6,000 estimated tokens — the code is expected to filter and aggregate before returning

The model can only reach external systems through the host-provided bridge. It can't fetch() arbitrary URLs or open network connections.

The Research: Code Actions Beat JSON by Up to 20%

This isn't just a Cloudflare opinion. The CodeAct paper tested executable code actions against JSON/text tool calling across 17 LLMs on the API-Bank and M3ToolEval benchmarks. Code-based invocation achieved up to 20% higher success rates.

Why? Four advantages:

✅ Composability — nest actions and define reusable functions within a single turn

✅ Object management — handle complex outputs like images or nested data structures naturally

✅ Generality — express any computable task, not just what a tool schema anticipated

✅ Natural fit — LLM training data is already full of code, so models are good at writing it

The control and data flow that code provides — variables, loops, conditionals — lets the model compose multi-step workflows in a single action. With JSON tool calling, every input needs a separate round trip.

Who's Using It Today

Cloudflare is the pioneer, with Code Mode baked into their MCP SDK and Agents framework. It's marked experimental but publicly documented and usable.

claude-code-mode (gabe4coding/claude-code-mode) is a community plugin that brings Code Mode to Claude Code. Their benchmarks report the same accuracy at 43% lower cost per task using Haiku 3.5.

HuggingFace smolagents implements a similar pattern with a custom LocalPythonExecutor that operates on the AST, disallows unauthorized imports, and caps operations to prevent infinite loops. For stronger isolation, it supports E2B, Docker, Blaxel, and Modal sandboxes.

The major AI editors — Cursor, Cline, and Windsurf — all support MCP but still use the conventional tool-per-endpoint approach. None have adopted a code-mode pattern yet.

The Tradeoffs Are Real

Code Mode shifts complexity from the MCP layer to the execution environment:

  • Sandbox security becomes critical — you're running LLM-generated code, not just parsing JSON parameters
  • Debugging gets harder — a 20-line program has more failure modes than a single tool call
  • Model capability matters more — weaker models may struggle to write correct multi-step programs
  • Supply chain risk — a compromised model could attempt to exploit the sandbox

The smolagents team puts it plainly: "No local Python sandbox can ever be completely secure." For production use, remote sandboxing (WASM, V8 isolates, containerized runtimes) is the way.

Why This Matters For You

If you're building agents that interact with large APIs, Code Mode is worth evaluating now. The pattern is simple:

  1. Generate typed SDK declarations from your API spec
  2. Inject them into the system prompt
  3. Provide a sandboxed execute_code tool
  4. Let the model write programs instead of calling tools

The context savings alone can be transformative. And the composability advantage means your agent can handle complex, multi-step workflows that would require dozens of sequential tool calls in the traditional approach.

Are you running Code Mode in your agent workflows, or still on traditional MCP tools?

👇 Drop your experience in the comments — I'm curious how many people are using this daily.