Stop Exposing Every Endpoint: How to Design an MCP Server That Scales
An opinion, backed by the numbers: what Cloudflare's search() and execute() server gets right, where code mode costs more than it saves, and the design I would pick for each kind of MCP server.
DILJOT SINGH · TECHNICAL LEADMost MCP servers are built the same way. Take an API, write one tool per endpoint, give each tool a JSON Schema, and register them all. It is the obvious design, it is what most SDK examples show, and for a server with a handful of tools it works well.
It stops working when the API is large. Every tool definition a server returns from tools/list usually ends up in the model's context window before the model has read the user's request. In February 2026, Cloudflare put a number on how bad that gets for its own API. An MCP server exposing every Cloudflare endpoint as a separate tool would take about 1.17 million tokens, more than the full context window of current frontier models. Their alternative exposes the whole API through two tools, search() and execute(), in roughly 1,000 tokens (Cloudflare, "Code Mode: give agents an entire API in 1,000 tokens").
That post has been widely read as "code mode is the right way to build MCP servers". I think that reading is half right. This article is for backend engineers and tech leads who are deciding how to put their own API, or their company's internal systems, behind MCP. It looks at what Cloudflare actually built, what the independent benchmarks say about code mode's performance, and what it costs in security and operations.
My position, up front:
The best MCP server shows the model as little as possible up front and lets it pull in detail on demand. Code execution is one way to do that, and it is the right one for large APIs and long, data-heavy tasks. It is not a default. For small tool sets it costs more, and for most single servers a deterministic "search and call" design gets most of the context savings without running model-written code.
The rest of the article is the evidence for that position, and the places where it could be wrong.
What an MCP server costs before it does anything
The Model Context Protocol defines how an AI application (the client) discovers and calls capabilities exposed by a server. Tools are the main capability. A client calls tools/list, gets back each tool's name, description and input schema, and most clients put those definitions into the model's prompt so the model can decide which tool to call.
The protocol itself has moved quickly. The current revision, 2026-07-28, made MCP stateless: it removed the initialize handshake and protocol-level sessions from Streamable HTTP, moved tasks into an official extension, and asks servers to return tools/list in a deterministic order so clients can cache it and get better prompt-cache hit rates (MCP specification changelog, 2026-07-28). None of those changes alter the basic economics. Whatever a server puts in its tool list is a fixed cost paid on every request that uses the server.
That fixed cost has two effects.
It costs tokens. Anthropic has reported seeing tool definitions take 134K tokens in its own setups before optimization, and gives the example of a Jira server alone using about 17K (Anthropic Engineering, "Introducing advanced tool use", Nov 2025). Its November 2025 post on code execution walks through an agent connected to many servers where tool definitions and intermediate results reach 150,000 tokens for a task that needs about 2,000 (Anthropic Engineering, "Code execution with MCP", 4 Nov 2025).
It costs accuracy. More tools means more chances to pick the wrong one. In the RAG-MCP paper, retrieving only the relevant tools before prompting more than tripled tool selection accuracy on their MCP stress test, from 13.62% to 43.13%, while cutting prompt tokens by more than half (Gan and Sun, arXiv:2505.03275, May 2025). Anthropic reported a similar direction for its own tool search feature: on MCP evaluations with large tool libraries, Opus 4 went from 49% to 74% accuracy when tools were discovered on demand instead of loaded up front (Anthropic Engineering, Nov 2025). Those are vendor and preprint numbers on specific benchmarks, not guarantees, but they point the same way.
Measuring it on a real API
To check the size of the problem on an API that most engineers know, I ran a small measurement for this article. I took GitHub's published REST API description (OpenAPI 3.0.3, info.version 1.1.4, downloaded on 3 December 2026), which has 1,288 operations, and generated three tool lists from it:
- ▸One MCP tool per operation, with full input schemas (path and query parameters plus the JSON request body,
$refs inlined). - ▸One tool per operation with only required parameters, similar to the "required params only" variant Cloudflare reports.
- ▸The two-tool
search_operationsandcall_operationserver shown later in this article.
I counted tokens with the cl100k_base encoding (the gpt-tokenizer npm package), so the numbers are comparable in method to Cloudflare's tiktoken figures, not to any particular model's billing.
| GitHub REST API, 1,288 operations | Tokens in tools/list |
|---|---|
| One tool per operation, full schemas | 473,222 |
| One tool per operation, required parameters only | 90,042 |
Two tools (search_operations, call_operation) | 430 |
Two things stand out. Even the stripped-down version is 90K tokens, which is most of a 200K context window spent before any work. And stripping schemas does not solve the problem anyway: a model that only sees required parameters can't use optional filters it doesn't know exist. The scripts and method are in the code section so you can check the numbers or run them on your own API.
What Cloudflare actually built
Cloudflare's server is a good design, and it is worth being precise about what it is, because a lot of commentary has blurred it with earlier work.
The two tools
The server exposes two tools, and each takes a single argument: a string of JavaScript (Cloudflare, Feb 2026).
- ▸
search(code)runs model-written JavaScript against aspecobject, which is Cloudflare's full OpenAPI document with every$refalready resolved. The model filters endpoints by product, path or tag in code. The spec itself never enters the model's context; only what the code returns does. - ▸
execute(code)runs model-written JavaScript against acloudflare.request()client that makes authenticated API calls. Inside one call, the code can paginate, check responses and chain several requests.
In the post's worked example, an agent set up DDoS protection in four tool calls: it searched for WAF and ruleset endpoints, inspected a schema to find valid ruleset phases, listed existing rulesets, and fetched the managed configurations.
Cloudflare's developer docs describe the server as covering more than 2,500 endpoints. They also give a more conservative comparison than the headline: a native MCP server with 2,594 tools and only required parameters would be about 244,000 tokens, against about 1,000 for code mode (Cloudflare docs, MCP servers for Cloudflare). That is still a reduction of more than 99%. It is the number I would quote in an architecture review, because it compares against a reasonable baseline rather than the worst one.
The sandbox and the credentials
The part of the design that makes it safe enough to ship is not the two tools. It is where the code runs and what it can reach.
- ▸Code runs in a Dynamic Worker, a V8 isolate with no filesystem and no environment variables. Outbound
fetch()is disabled by default (Cloudflare, Feb 2026). - ▸Cloudflare's guide for building your own version says the executor blocks direct
fetch()andconnect()calls, so generated code can only reach the outside world through the tools or a host-side request callback. The bearer token is attached in that host callback and never enters the sandbox (Cloudflare docs, Build a Code Mode MCP server). - ▸Authentication is OAuth 2.1 through the Workers OAuth Provider, with the token narrowed to the permissions the user approved when connecting (Cloudflare, Feb 2026).
Where the idea came from
The idea predates this server. In September 2025, Kenton Varda and Sunil Pai at Cloudflare argued that models are better at writing code that calls MCP tools than at calling the tools directly, because they have seen far more real code than synthetic tool-call examples, and because chained calls in code don't push every intermediate result back through the model (Cloudflare, "Code Mode: the better way to use MCP", 26 Sep 2025). That first version converted MCP tool schemas into TypeScript and loaded the whole generated API into context. Its authors noted that a more dynamic way to browse the API could come later. They reported no benchmark numbers.
Anthropic described the same pattern independently in November 2025, presenting MCP servers to the agent as code files it can browse, and reported the 150,000 to 2,000 token example (98.7%) for one task (Anthropic Engineering, Nov 2025). The academic root is older: the CodeAct paper at ICML 2024 found that letting agents act through executable Python instead of JSON tool calls gave up to 20% higher success rates across 17 models (Wang et al., ICML 2024).
What the February 2026 server adds is the move from client-side to server-side. Earlier designs needed the agent to bring its own sandbox. Cloudflare's server brings the sandbox with it, so any MCP client gets the fixed-size tool surface without changing anything. Cloudflare's own comparison is fair about the alternatives: client-side code mode needs the agent to ship a secure sandbox, CLIs need a shell and a much broader attack surface, and dynamic tool search needs a search function that someone must maintain and evaluate, with every matched tool still costing tokens (Cloudflare, Feb 2026).
What the performance numbers actually say
Token reduction on the tool list is the easiest metric to measure and the least informative on its own. What matters for a production system is cost per completed task, latency, and success rate. Here is what independent and semi-independent measurements show.
| Study | Setup | What changed with code execution |
|---|---|---|
| AIMultiple (Alper; data dated Dec 2025) | GPT-4.1, Bright Data MCP server with 63 tools, 2 browsing tasks, 50 runs each | Input tokens per call -78.5% (15,417 to 3,310); output tokens +120% (87 to 192); latency +7% (9.66s to 10.37s); success 100% in both (AIMultiple) |
| Felendler et al., Ben-Gurion University (arXiv, Feb 2026) | MCP-Bench, 10 servers, GPT-4o, GPT-4.1, GPT-4.1 mini | Fewer tokens on every model and server, larger savings on multi-server tasks; lower average latency with more outliers; task quality comparable, but lower on some three-server tasks where code missed conditional branches (arXiv:2602.15945) |
| Mbat, IJCA vol. 187 no. 136 (Aug 2026) | 8 models, 6 scenarios, native MCP vs TypeScript code mode | Tokens -37.6%, cost -40.7%; pass rate 59.4% to 63.6% overall, but Gemini models roughly halved; attempts per cell +48%; worst case +14.3% tokens for code mode (IJCA) |
| Pydantic (Pfaffenberger, 28 Oct 2026) | 8 models, 5 small CRUD apps, 5,276 graded runs, deterministic grading | Long multi-step tasks: cost -58%, wall time -51%, success +16 points. Single operations: cost +8%, time +16%. Five-item jobs: +21% to +38% cost on three of five tasks (Pydantic) |
Four conclusions hold across these studies.
1. Savings grow with the length of the task. Pydantic's scaling test is the clearest. At 200 items per task, cost dropped by 47% to 75% across models. For the one model they broke out per task, success stayed at 92% to 100% with code mode, while direct tool calling fell to 62% to 79% (Pydantic, Oct 2026). Felendler et al. saw the same shape: the savings were largest on two- and three-server tasks (arXiv:2602.15945). The mechanism is the one Cloudflare and Anthropic describe: intermediate data stays in the sandbox instead of passing through the model.
2. On small jobs, code mode costs more. Code mode adds instructions and type information to every request. On Pydantic's single-operation controls, that overhead made code mode 8% more expensive and 16% slower, and on five-item jobs it cost 21% to 38% more on three of five tasks (Pydantic, Oct 2026). If most of your traffic is "look up one record", you are paying for machinery you don't use.
3. Output tokens and latency don't always improve. Writing code takes more output tokens than emitting a tool call: AIMultiple measured 2.2 times more, and output tokens are usually priced higher than input. Their latency went up 7% even as input tokens fell 78.5% (AIMultiple). The IJCA study found higher latency per round trip for code mode and attributed it to regenerating programs after failures, not to sandbox startup (Mbat, IJCA 2026).
4. Code mode moves the failure mode. With direct tool calls, a bad call fails alone and the model retries it. With code mode, one broken program invalidates every call it contained. The IJCA study names this "retry amplification" and shows it as the source of code mode's worst-case token penalty, along with compile errors, sandbox API misuse and tool-ordering mistakes (Mbat, IJCA 2026). Pydantic saw a more dangerous version of the same thing: a script re-run after a partial failure repeated writes, producing duplicate records (Pydantic, Oct 2026). It also matters which model you run: in the IJCA study, non-Gemini models improved by 16.7 points while Gemini models got worse.
A caveat that applies to all of the above: none of these is a large, peer-reviewed, multi-vendor benchmark. AIMultiple tested two tasks on one model. Pydantic's benchmark code is not public and runs on its own tooling. The IJCA study ran under a $15 API budget. The arXiv paper reports most of its numbers only in charts. The direction is consistent across them; the exact percentages are not something to put in a business case.
The cost nobody puts in the headline: security
Running model-written code is a new attack surface, and the MCP ecosystem already has a security problem.
Tool metadata is already an injection channel. Invariant Labs showed in April 2025 that instructions hidden in a tool's description can make an agent read and exfiltrate private files, and named the attack "tool poisoning" (summarised in MCPTox, arXiv:2508.14925). Follow-up work has shown that a poisoned tool can steer an agent even when the poisoned tool itself is never called (MCP-ITP, arXiv:2601.07395). The Cloud Security Alliance's July 2026 note traces these attacks to one structural cause: clients inherit trust from the servers they connect to without verifying it (CSA research note, July 2026).
Code execution widens that surface. The Ben-Gurion paper is the most useful source here because it measured performance and attacks together. Its threat model lists 16 threat classes across tool discovery, code generation, execution, result validation and runtime impact. In their tests, attacks on a code-execution agent produced factually wrong results and, in one case, the creation of an unauthorized admin account. A layered defence (static checks before execution, sandboxing with limits, and an LLM judge screening discovery artifacts and results) blocked every attack they demonstrated, but they did not test adaptive attackers (Felendler et al., arXiv:2602.15945).
Cloudflare's own guide is candid about the limits too. Code Mode does not provide durable per-operation approval, so authorization has to be enforced in the upstream handlers or the host callback. Secrets must not appear in the OpenAPI document or in API results, because model-written code can read both. Responses are capped at about 6,000 estimated tokens, and the SDK is marked experimental (Cloudflare docs).
There is also an operational point that matters to anyone who has to run this in a regulated environment. Speakeasy argues that a script making many calls is one opaque step, whereas direct tool calls can each be logged, approved or blocked (Speakeasy, 11 Nov 2026). In a healthcare or insurance system, "the agent ran a script that touched 40 records" is a much harder audit entry than 40 individually authorized calls.
None of this means code mode is unsafe. Cloudflare's design (isolates, no network, credentials outside the sandbox, scoped OAuth) is a strong answer. It means the sandbox is now part of your security boundary, and you have to be able to build, run and monitor it before you take on the pattern.
My position: on-demand discovery always, code execution when it pays
Here is where I land, and why.
1. Small server: keep plain tools, and design them well
If a server has a modest number of tools, the right design is the boring one: a small set of tools shaped around tasks rather than endpoints, with clear descriptions, an outputSchema so results are predictable, and annotations such as readOnlyHint and destructiveHint so clients can decide what needs approval. Anthropic's own guidance says its tool search feature helps most when there are 10 or more tools or definitions exceed 10K tokens, and is less useful for small libraries (Anthropic Engineering, Nov 2025). Pydantic's data says the same thing from the other side: on single operations, code mode is slower and more expensive.
Speakeasy, which earlier built progressive disclosure into servers and reported about a 90% token reduction from it, now recommends against adding a second search layer inside a single server, because harnesses increasingly do tool search themselves and a server-side search competes with it (Speakeasy, Nov 2026). I agree for small and medium servers. For large APIs, I don't, because a client cannot search a tool list that is too big to send.
2. Large API: two tools over the spec, always
If your server wraps hundreds or thousands of operations, one tool per endpoint is simply the wrong design. Figure 1 is the whole argument: 473K tokens for GitHub is not a tool list, it is a context overflow. Any large-API server should expose a fixed, small surface (search the spec, then act) so its context cost does not grow with the API. This is the part of Cloudflare's design I would copy without reservation.
3. Code execution: only when tasks chain calls or move data, and only if you can run the sandbox
The second half of Cloudflare's design, running model code to act, is a separate decision. It pays off when tasks chain many calls, paginate, filter large results, or move data from one system to another. That is where every benchmark above shows large savings and better success rates. It needs a real sandbox, resource limits, and a way to make writes idempotent. If your typical request is "get this invoice" or "update this ticket", a deterministic call_operation tool gets you the context savings of the two-tool design without any of the code-execution risk, and every call stays individually auditable.
4. Many servers: put code mode in the harness or the gateway
Cloudflare acknowledges that a two-tool server solves context cost for one API, and that agents usually connect several servers, each of which adds context pressure again. Their answer is MCP server portals (Cloudflare, Feb 2026), and portals have since gained a code mode setting, turned on by default, that replaces all upstream tools with a single code tool (Cloudflare changelog, 26 Mar 2026). That is the right layer. Code execution across many servers belongs in one place that already holds credentials and enforces policy, such as the agent harness or a gateway, not reimplemented inside every server. Speakeasy makes the same argument and adds a warning worth repeating: don't enable code mode in both the harness and the gateway for the same agent (Speakeasy, Nov 2026).
A Python implementation of "search and call"
Most of the published code mode tooling is TypeScript on Workers. Many backend teams, including Python and Django shops, need the large-API pattern without adopting a new runtime or a code sandbox. Here is a complete server that exposes any OpenAPI 3.x API through two tools, built on the official MCP Python SDK. Download it as server.py.
Prerequisites: Python 3.11 or later, mcp 2.x (tested with 2.3.0, where the old FastMCP class is now called MCPServer), httpx, and jsonschema.
pip install "mcp>=2,<3" httpx jsonschema"""
A "search and call" MCP server for a large REST API, without running model-written code.
The model sees two tools, whatever the size of the API:
- search_operations: find operations in the OpenAPI spec and return only their schemas
- call_operation: call one operation by operationId, validated against the spec
Requires: Python 3.11+, mcp>=2.0, httpx, jsonschema
Run: OPENAPI_SPEC=./openapi.json API_BASE_URL=https://api.example.com API_TOKEN=... \
python server.py
"""
from __future__ import annotations
import json
import math
import os
import re
from dataclasses import dataclass, field
from typing import Any
from urllib.parse import quote
import httpx
import jsonschema
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
MAX_RESULT_CHARS = 8_000 # cap what goes back into the model's context
ALLOW_WRITES = os.getenv("ALLOW_WRITES", "false").lower() == "true"
READ_METHODS = {"get", "head"}
@dataclass
class Operation:
operation_id: str
method: str
path: str
summary: str
tags: list[str]
parameters: list[dict[str, Any]]
body_schema: dict[str, Any] | None
search_text: str = field(repr=False, default="")
def _tokens(text: str) -> set[str]:
return set(re.findall(r"[a-z0-9]+", text.lower()))
def _validate(value: Any, schema: dict[str, Any], label: str) -> None:
# Validation errors go back to the model as tool errors so it can correct itself.
try:
jsonschema.validate(value, schema)
except jsonschema.ValidationError as exc:
raise ToolError(f"Invalid {label}: {exc.message}") from None
def resolve_refs(node: Any, root: dict[str, Any], seen: tuple[str, ...] = ()) -> Any:
"""Inline local $refs so every schema the model sees is self-contained."""
if isinstance(node, dict):
ref = node.get("$ref")
if isinstance(ref, str) and ref.startswith("#/"):
if ref in seen: # recursive schema: stop expanding
return {"type": "object"}
target: Any = root
for part in ref[2:].split("/"):
target = target[part.replace("~1", "/").replace("~0", "~")]
return resolve_refs(target, root, seen + (ref,))
return {k: resolve_refs(v, root, seen) for k, v in node.items()}
if isinstance(node, list):
return [resolve_refs(v, root, seen) for v in node]
return node
def load_operations(spec: dict[str, Any]) -> dict[str, Operation]:
"""Flatten an OpenAPI 3.x document into one record per operation."""
spec = {"paths": resolve_refs(spec.get("paths", {}), spec)}
ops: dict[str, Operation] = {}
for path, item in spec.get("paths", {}).items():
shared = item.get("parameters", [])
for method, op in item.items():
if method not in {"get", "post", "put", "patch", "delete", "head"}:
continue
body = (
op.get("requestBody", {})
.get("content", {})
.get("application/json", {})
.get("schema")
)
record = Operation(
operation_id=op["operationId"],
method=method,
path=path,
summary=op.get("summary", ""),
tags=op.get("tags", []),
parameters=shared + op.get("parameters", []),
body_schema=body,
)
record.search_text = " ".join(
[record.operation_id, path, record.summary, " ".join(record.tags),
op.get("description", "")]
)
ops[record.operation_id] = record
return ops
def build_index(operations: dict[str, Operation]):
"""Weight rare words above common ones (IDF), and the summary and id above the
long description, so "list pull requests" finds pulls/list, not every list call."""
docs = {
op_id: (_tokens(op.operation_id + " " + op.summary), _tokens(op.search_text))
for op_id, op in operations.items()
}
df: dict[str, int] = {}
for strong, weak in docs.values():
for tok in strong | weak:
df[tok] = df.get(tok, 0) + 1
n = len(docs)
idf = {tok: math.log(1 + n / count) for tok, count in df.items()}
def score(op_id: str, query_tokens: set[str]) -> float:
strong, weak = docs[op_id]
return sum(idf.get(t, 0.0) * (2.0 if t in strong else 1.0 if t in weak else 0.0)
for t in query_tokens)
return score
def create_server(spec: dict[str, Any], http: httpx.Client) -> MCPServer:
operations = load_operations(spec)
score_op = build_index(operations)
mcp = MCPServer(
name="api-search-call",
instructions=(
"Call search_operations first to find the operationId and its parameters, "
"then call call_operation with exactly those parameters."
),
)
@mcp.tool(annotations=ToolAnnotations(read_only_hint=True))
def search_operations(query: str, tag: str | None = None, limit: int = 5) -> list[dict]:
"""Search the API's operations by keywords (for example "list open invoices").
Returns operationId, method, path, summary and the parameter schema of the
best matches. Use the returned operationId with call_operation."""
wanted = _tokens(query)
scored = []
for op in operations.values():
if tag and tag not in op.tags:
continue
score = score_op(op.operation_id, wanted)
if score > 0:
scored.append((score, op))
scored.sort(key=lambda pair: (-pair[0], pair[1].operation_id))
return [
{
"operationId": op.operation_id,
"method": op.method.upper(),
"path": op.path,
"summary": op.summary,
"parameters": [
{"name": p["name"], "in": p["in"], "required": p.get("required", False),
"schema": p.get("schema", {})}
for p in op.parameters
],
"body": op.body_schema,
"readOnly": op.method in READ_METHODS,
}
for _, op in scored[: max(1, min(limit, 10))]
]
@mcp.tool(annotations=ToolAnnotations(read_only_hint=False, destructive_hint=True))
def call_operation(
operation_id: str,
path_params: dict[str, Any] | None = None,
query: dict[str, Any] | None = None,
body: dict[str, Any] | None = None,
) -> dict:
"""Call one API operation found with search_operations. Arguments are
validated against the API spec before any request is sent."""
op = operations.get(operation_id)
if op is None:
raise ToolError(f"Unknown operationId '{operation_id}'. Use search_operations.")
if op.method not in READ_METHODS and not ALLOW_WRITES:
raise ToolError(f"'{operation_id}' changes data and writes are disabled on this server.")
path_params, query = path_params or {}, query or {}
for p in op.parameters:
source = path_params if p["in"] == "path" else query if p["in"] == "query" else None
if source is None:
continue
if p.get("required") and p["name"] not in source:
raise ToolError(f"Missing required {p['in']} parameter '{p['name']}'.")
if p["name"] in source and "schema" in p:
_validate(source[p["name"]], p["schema"], f"{p['in']} parameter '{p['name']}'")
if op.body_schema is not None:
_validate(body or {}, op.body_schema, "request body")
url = op.path
for name, value in path_params.items():
url = url.replace("{" + name + "}", quote(str(value), safe=""))
if "{" in url:
raise ToolError(f"Unresolved path parameters in {url}.")
response = http.request(op.method.upper(), url, params=query,
json=body if op.body_schema is not None else None)
text = response.text
truncated = len(text) > MAX_RESULT_CHARS
try:
payload: Any = json.loads(text) if not truncated else text[:MAX_RESULT_CHARS]
except json.JSONDecodeError:
payload = text[:MAX_RESULT_CHARS]
return {"status": response.status_code, "truncated": truncated, "data": payload}
return mcp
if __name__ == "__main__":
with open(os.environ["OPENAPI_SPEC"], encoding="utf-8") as fh:
spec = json.load(fh)
client = httpx.Client(
base_url=os.environ["API_BASE_URL"],
headers={"Authorization": f"Bearer {os.environ['API_TOKEN']}"}, # never shown to the model
timeout=15.0,
)
create_server(spec, client).run() # stdio by defaultWhat each design choice is for
- ▸The model never sees the full spec.
search_operationsreturns at most ten operations, with resolved schemas, so the model gets exact parameter definitions for the few operations it needs. On the GitHub spec, a three-result search returned between 417 and 888 tokens. - ▸Validation happens before any request. Unknown operations, missing path parameters, bad enum values and invalid bodies are rejected with a clear message. These are raised as
ToolErrorso they come back as tool execution errors the model can correct, which is what the MCP specification asks servers to do with input validation errors (MCP changelog, 2025-11-25). - ▸Writes are off by default. Any method other than GET or HEAD is refused unless
ALLOW_WRITES=true. In a real deployment I would go further and keep an explicit allowlist of operationIds the server may call. - ▸Credentials stay in the server. The bearer token lives in the
httpx.Clientheaders and never appears in tool definitions, arguments or results. This is the same principle as Cloudflare's host callback, without a sandbox in between. - ▸Results are capped.
MAX_RESULT_CHARSstops a huge list response from flooding the context. This is the main thing you give up compared with code mode: the model can't filter a 5,000-row response before reading it. If your users regularly need that, that is the signal to move to code execution.
Search quality is the product
The first version of search_operations scored operations by counting shared words. On the GitHub spec it found the right operation in the top three for only two of four test queries: "list pull requests for a repository" returned three Checks API operations, because "list", "for" and "repository" appear in hundreds of descriptions. Weighting rare words more heavily (IDF) and giving extra weight to matches in the summary and operationId fixed both misses, and all four queries then had the correct operation in the top three.
That is a small, informal test, not an evaluation. But it shows the trade-off Cloudflare points out about dynamic tool search: somebody has to own and evaluate the search function. If the search is bad, the model either calls the wrong operation or searches again, and both cost more than the tokens you saved. Before shipping a server like this, I would build a set of 50 to 100 realistic queries with their expected operations and track top-3 hit rate on every spec change. Cloudflare's design sidesteps part of this problem by letting the model write the search as code, which is one of its real advantages.
Testing it
The test file runs the server through the real MCP client against a mocked upstream API (httpx.MockTransport), so no network is needed:
python test_server.pyIt checks that the client sees exactly two tools, that a search for "list open invoices" returns listInvoices, that a valid call reaches the API with the bearer token, that path parameters are URL-encoded, and that an invalid enum, a missing path parameter and a blocked write each come back as a tool error with a useful message. All of these passed with mcp 2.3.0 on Python 3.13.
Reproducing the measurement
build_tool_lists.py generates the three tool lists from any OpenAPI JSON file, and count.js counts them with cl100k_base:
npm install gpt-tokenizer
python -I build_tool_lists.py ./api.github.com.json ./out ./path-to-server
node count.js ./outGitHub's spec is published in the github/rest-api-description repository. Run it on your own API before you decide anything: the numbers depend heavily on how verbose your descriptions and schemas are.
Production checklist for any MCP server
Whichever design you choose, these apply:
| Area | What to do |
|---|---|
| Protocol version | Target the current revision (2026-07-28) and Streamable HTTP. The old HTTP+SSE transport is formally deprecated (MCP changelog). |
| Tool list | Keep it small or fixed-size. Return tools in a deterministic order for client and prompt caching. |
| Authorization | OAuth with scopes narrowed to what the user approved. Never put tokens in tool arguments, results or specs. |
| Writes | Annotate destructive tools, allowlist write operations, and make them idempotent so a retried call or re-run script can't duplicate work. |
| Errors | Return input validation failures as tool errors with a clear message, so the model can self-correct. |
| Result size | Cap and paginate responses. If users need to filter large results, that is the case for code execution. |
| Observability | Log every tool call with its arguments and outcome. The 2026-07-28 revision documents OpenTelemetry trace context in _meta. |
| Third-party servers | Treat tool descriptions from servers you don't control as untrusted input. Review and pin them. |
| Code execution (if used) | Isolate, block network access, set CPU, memory and time limits, keep credentials outside the sandbox, and enforce authorization outside the model's code. |
Where this opinion could be wrong
Three things could change this analysis.
Models may get much better at writing correct code on the first try. Much of code mode's worst-case cost comes from failed programs being regenerated. If first-attempt success rises far enough, code mode's penalty on small tasks shrinks and the "default to direct tools" advice weakens. Pydantic's data already shows wide variation between models, so this is worth re-testing with whichever models you actually use.
Clients may standardize code execution. If MCP clients ship secure, well-understood sandboxes by default, server authors won't need to choose. The trend points that way: Pydantic notes that some coding agents now route MCP tools through code mode by default (Pydantic, Oct 2026). Then the best server design is simply clean, well-described tools, and the client does the rest.
The benchmarks are thin. Every study above is small, recent, or run by a party with an interest in the result. A large, open, multi-vendor benchmark could shift the numbers in either direction.
Conclusion
Cloudflare's search and execute server is a strong design, and its most important idea is not code execution. It is that an MCP server's cost to the model should not grow with the size of the API behind it. Any server wrapping a large API should adopt that idea, and the GitHub numbers above show why: 473,222 tokens for one tool per operation, 430 for two tools that discover on demand.
Whether the model should also write and run code is a separate decision, and the evidence says it depends on the work. For long, multi-step, data-heavy tasks, code mode cuts cost by half or more and improves success rates. For single lookups it costs more, adds a sandbox to your security boundary, and turns a set of auditable calls into one opaque script. Pick the design for the traffic you actually have, measure it on your own API, and put code execution where it can be secured once: in the harness or the gateway, not in every server you write.
References
- ▸Carey, M. "Code Mode: give agents an entire API in 1,000 tokens." Cloudflare Blog, 20 February 2026. Company engineering publication. https://blog.cloudflare.com/code-mode-mcp/. The search and execute server, sandbox, OAuth, token figures and comparison of approaches.
- ▸MCP servers for Cloudflare. Cloudflare developer documentation. https://developers.cloudflare.com/agents/model-context-protocol/cloudflare/servers-for-cloudflare/. 2,500+ endpoints; 2,594 tools and ~244,000 tokens with required parameters only.
- ▸Build a Code Mode MCP server. Cloudflare developer documentation. https://developers.cloudflare.com/agents/model-context-protocol/guides/build-codemode-mcp-server/. Executor network restrictions, host request callback, no per-operation approval, response cap, experimental status.
- ▸Code mode for MCP server portals. Cloudflare changelog, 26 March 2026. https://developers.cloudflare.com/changelog/post/2026-03-26-mcp-portal-code-mode/. Portal-level code mode, on by default.
- ▸Varda, K., Pai, S. "Code Mode: the better way to use MCP." Cloudflare Blog, 26 September 2025. https://blog.cloudflare.com/code-mode/. Original code mode argument and isolate sandbox design.
- ▸"Code execution with MCP: Building more efficient agents." Anthropic Engineering, 4 November 2025. https://www.anthropic.com/engineering/code-execution-with-mcp. 150,000 to 2,000 token example.
- ▸"Introducing advanced tool use." Anthropic Engineering, 24 November 2025. https://www.anthropic.com/engineering/advanced-tool-use. Tool definition overhead, tool search accuracy (49% to 74% for Opus 4), when tool search helps.
- ▸Gan, T., Sun, Q. "RAG-MCP: Mitigating Prompt Bloat in LLM Tool Selection via Retrieval-Augmented Generation." arXiv:2505.03275, May 2025. Preprint. https://arxiv.org/abs/2505.03275.
- ▸Wang, X. et al. "Executable Code Actions Elicit Better LLM Agents." ICML 2024. Peer-reviewed. https://arxiv.org/abs/2402.01030.
- ▸Felendler, Y., Gandhi, P. A., Habler, I., Elovici, Y., Shabtai, A. "From Tool Orchestration to Code Execution: A Study of MCP Design Choices." arXiv:2602.15945, February 2026. Preprint. https://arxiv.org/abs/2602.15945. Performance on MCP-Bench and a 16-class threat model.
- ▸Mbat, A. "Benchmarking LLM Tool Orchestration in Resource-Constrained Agentic Workflows: Native MCP Function Calling vs Code Mode." International Journal of Computer Applications 187(136), August 2026. https://ijcaonline.org/archives/volume187/number136/mbat-ijca-2026-e10508249e55.pdf.
- ▸Pfaffenberger, M. "Why code mode could cut your agent bill." Pydantic, 28 October 2026. Vendor benchmark (code not public). https://pydantic.dev/articles/why-code-mode-is-the-future.
- ▸Alper, Ş. "Code Execution with MCP: A New Approach to AI Agent Efficiency." AIMultiple (data dated December 2025). Independent benchmark. https://aimultiple.com/code-execution-with-mcp.
- ▸Rooney, T. "Code mode is overkill for your MCP server. It's not for your gateway." Speakeasy, 11 November 2026. https://www.speakeasy.com/blog/code-mode-mcp-gateway.
- ▸Model Context Protocol specification, key changes (2026-07-28). https://modelcontextprotocol.io/specification/latest/changelog. Stateless protocol, deterministic tool ordering, deprecated HTTP+SSE, OpenTelemetry in
_meta. - ▸Model Context Protocol specification, key changes (2025-11-25). https://modelcontextprotocol.io/specification/2025-11-25/changelog. Input validation errors returned as tool execution errors.
- ▸"MCPTox: A Benchmark for Tool Poisoning Attack on Real-World MCP Servers." arXiv:2508.14925, 2025. Preprint. https://arxiv.org/abs/2508.14925. Background on Invariant Labs' tool poisoning attack.
- ▸"MCP-ITP: An Automated Framework for Implicit Tool Poisoning in MCP." arXiv:2601.07395, January 2026. Preprint. https://arxiv.org/abs/2601.07395.
- ▸"Poisoned MCP Tool Descriptions: A Silent Exfiltration Path." Cloud Security Alliance research note, 11 July 2026. https://labs.cloudsecurityalliance.org/wp-content/uploads/2026/07/CSA_research_note_mcp-tool-description-poisoning_20260711-csa-styled.pdf.
- ▸GitHub REST API description (OpenAPI). GitHub. https://github.com/github/rest-api-description. Source spec for this article's token measurement.
Comments
Comments are public and moderated after posting. Keep it on topic and kind. Your display name is shown with each comment; see the privacy notice.