You add a server because one task needs it. Then another. Soon the coding agent starts each session carrying a map of tools it may never call, and every long result gets packed into the conversation anyway.
Short answer: Code execution with MCP lets an agent call tools from generated code, so it can compose calls and filter intermediate data before showing a result to the model. It targets two different token costs: tool definitions loaded into context and tool results passed back through context. Measure each before changing your setup: tool search defers definitions, while code execution is most useful when several calls can be joined or large results can be reduced before the model sees them. Anthropic’s original design explains the pattern; this guide measures it from a coding agent’s side.
What does code execution with MCP change?
It changes how an agent uses tools, not the MCP protocol itself. In the direct pattern, the client shows the model each tool's name, description, and schema, then returns the result to the model after every call. Code execution puts a small code interface in front of those calls: the model writes a script, the runtime invokes MCP tools, and only selected output returns to the model.
An MCP server can stay exactly as it is while the agent changes how it discovers and calls the server's tools. The agent still needs permission to reach the server, and the code runtime needs a safe place to run. Anthropic’s explanation uses a filesystem of TypeScript wrappers; newer API features such as tool search and programmatic tool calling provide other ways to defer tools or run tool calls from code.
The working boundary is: agent writes code → code calls MCP tools → sandbox keeps intermediate data → model receives only the returned value. If there's no sandbox, the execution step is an untrusted-code boundary, not a token optimization to switch on casually.
Where do MCP tokens go in a coding-agent session?
They go into two buckets: the available tool definitions and the results returned to the model. A third issue, repeated billing for a stable definition prefix, is affected by prompt caching but doesn't make that prefix disappear from the context window. Anthropic’s context guide separates these controls for the same reason.
| Token bucket | What to count | The first control to try |
|---|---|---|
| Definitions loaded before a task | Names, descriptions, and argument schemas for tools the agent can see | Prune or allowlist tools; use deferred loading if most are rarely needed |
| Results returned during a task | Tool output, plus any intermediate data the model must pass into another call | Filter, paginate, or summarize at the source; use code to transform large intermediate results |
| Repeated input billing | Stable tool definitions and prompt text sent again on later API requests | Prompt caching; this reduces repeated input cost, not context size |
Don't equate a server's number of tools with its token footprint. Ten verbose schemas can cost more than fifty small ones. And one get_document call that returns a whole archive can cost more than its definition many times over.
How can I measure the MCP token cost in Claude Code and Codex?
Use the client's context view for a session-level reading, then isolate a server with a fresh-session comparison. For an exact API preflight, count the same request once without tools and once with the server's tools array.
Claude Code: Start a clean session, run /context, and record the MCP/tool-definition portion before doing the task. Run the same task with the relevant MCP server connected, then check /context again. With current Claude Code tool search, MCP tools are deferred and discovered on demand by default on supported first-party setups, so a definition may appear after the agent searches for it; take a reading both before and after the task. The command reference documents /context, and the MCP reference documents the default tool-search behavior and its exceptions.
Here is what the first reading looks like. In a clean test on October 4, 2026 (Claude Code 2.1.289, an empty project, five servers connected), claude -p "/context" listed every MCP tool with its estimated definition size before any task ran:
| Server | Tools | Definition tokens | Largest tool |
|---|---|---|---|
| Playwright MCP 0.0.83 | 25 | ~6.8k | browser_take_screenshot, 578 |
| Octobrain 0.14.4 | 4 | ~4.2k | memorize, 1.7k |
| Octocode 0.26.4 | 4 | ~3.5k | structural_search, 1.8k |
| Octofs 0.16.0 | 6 | ~3.3k | view, 1.0k |
| MCP reference filesystem server 2026.8.31 | 14 | ~3.1k | read_text_file, 321 |
All 20.8k tokens of those definitions sat in the deferred row, outside the session's 12.5k starting total. Two runs differed by 1–3% per server. Tool count is a poor proxy for cost here: the reference filesystem server's 14 short tools cost less than Octofs's 6, and one long description can outweigh a dozen short ones.
For the client setup itself, use our Claude Code and Codex MCP walkthrough; this measurement procedure assumes the server is already connected.
Codex: In a fresh thread, record /status and /mcp, run a representative task, then compare /status after starting a fresh thread with the same server disabled or its tool list narrowed. Change one server at a time.
Codex documents session context usage in /status and connected servers in /mcp; the documented status is a whole-session figure and doesn't attribute schema tokens to each server. Treat the difference between controlled runs as an estimate because project instructions, prompt history, and other tools also occupy context. Codex’s current reference lists those commands.
For a Messages API request, use Anthropic's POST /v1/messages/count_tokens endpoint with your actual tools array and system prompt. Make one count with the tools and a second with the same request minus those tools; subtract the totals to estimate the definition overhead.
The endpoint returns the token count for the messages, system prompt, and tools together, and doesn't create a model response. To measure result cost too, repeat the count with representative tool_result content included. This is a preflight count; compare it with the response's actual usage when tuning a real workflow. Anthropic’s token-count reference defines the request and returned input_tokens field.
Write down four numbers: initial context before MCP use, context after the task, definitions loaded, and returned result tokens. Repeat on the same task with one server at a time. That gives you a baseline you can check after changing tools.
Has Anthropic shipped tool search since the 2025 MCP article?
Yes. As of October 4, 2026, Anthropic documents deferred tool loading in the Messages API and says Claude Code enables MCP tool search by default on supported first-party setups. The API version requires the tool search tool and marks eligible definitions defer_loading; Claude Code handles that path for connected MCP servers. The API guide describes the request shape, while the current Claude Code MCP docs describe when it falls back to loading tools up front.
That's a meaningful update to the older post, but tool search doesn't remove every tool definition from the request: the API still receives deferred definitions so it can search and expand them when needed. It keeps most definitions out of the model's initial context and trades that space for an extra discovery step. Anthropic's tool search guide says plain tool calling fits better with fewer than 10 tools, when you use every tool on every request, or when all definitions together stay under 100 tokens; its tool-context overview places tool search at sets of 20 or more. Between those marks, measure before you switch.
OpenAI exposes a similar tool_search path in the Responses API; the current guide says it's supported on gpt-5.4 and later and uses defer_loading: true on the MCP tool definition. That's an API feature. In the Codex CLI, use /status to inspect overall session context and narrow exposed server tools with its MCP configuration. OpenAI’s tool-search guide describes the API feature; the Codex config reference lists enabled_tools.
Which should I choose: direct MCP calls, tool search, or code execution?
Choose based on where your measurement found the cost and how much control you need over each action. These approaches can also be combined: search can keep rarely used schemas out of context, and code can filter the result of a multi-call workflow.
| Choose | When it fits | Tradeoff to plan for |
|---|---|---|
| Direct calls | A small, stable tool set is used on nearly every task, or a human should review each individual action | Definitions stay available; large outputs and call-by-call roundtrips still use context |
| Tool search / deferred loading | The catalog is large but each task uses only a few tools | One discovery step; the API still receives definitions for searching |
| Code execution | A task chains several tools, loops over records, or can return a compact summary instead of raw intermediate data | Requires an execution environment with sandboxing, limits, and monitoring; code can make several tool calls in one run |
A quick rule: if the baseline MCP section is large, try deferred loading first. If the baseline is small but task results dominate, narrow or summarize outputs. If a workflow copies a large result from one tool into another, prototype a code path and compare the actual task — not just the schema count. Keep direct calls for actions that need a separate human decision or approval.
The source numbers are useful as examples, not forecasts. Anthropic's 2025 engineering post reports a drop from 150,000 to 2,000 tokens (98.7%) in its design example. Cloudflare's February 2026 post reports about 1,000 tokens for its two-tool Cloudflare API Code Mode, compared with 1.17 million for its equivalent native tool set; Cloudflare says that comparison used tiktoken. Those are each vendor's own reported results, and the server, schemas, runtime, and task shape differ. Anthropic’s post and Cloudflare’s post don't establish an expected saving for your setup.
A separate AIMultiple benchmark, updated August 2026, reports 78.5% fewer input tokens and 7% higher average latency in its Bright Data MCP / GPT-4.1 test. The output tokens rose in that benchmark. This is a reminder to track input, output, latency, and task success separately; "fewer tokens" alone isn't a complete result.
How do I cap tool output without hiding useful data?
Cap output at the layer that knows what the task needs. A server can paginate or return excerpts; an MCP client can limit an individual tool result; the model can ask code to select fields and aggregate rows before printing a result.
Claude Code warns when an MCP tool returns more than 10,000 tokens and has a 25,000-token default maximum where the tool doesn't declare its own result-size limit. Codex exposes per-tool output_token_limit and a general tool_output_token_limit for outputs stored in history. These limits bound what reaches conversation context; they don't make a broad tool schema smaller. See Claude Code’s MCP output controls and Codex’s configuration reference.
A Codex TOML example with a small exposed tool set and a per-tool output budget. To confirm the allow-list took effect, codex mcp get <server> --json prints the resolved enabled_tools (checked on Codex CLI 0.160.0); it also prints the server's environment variables unmasked, so keep that output out of tickets and chat logs:
[mcp_servers.example]
enabled_tools = ["search", "read"]
[mcp_servers.example.tools.read]
output_token_limit = 2000
The configured limit is a budget, not a hard ceiling and not a target: Codex applies output_token_limit before a standard 20% serialization allowance, so a stored result can run somewhat past it. Keep the result shape useful: request only the fields needed, paginate records, and return a count or a few representative rows when the full data isn't needed. OpenAI's MCP guide also supports the Responses API's allowed_tools filter.
What does code execution change about security and approvals?
It moves some work from visible, one-at-a-time tool calls into a program the model writes and a runtime executes. That can keep private intermediate data out of the model's context, but it also means the code environment is part of your security boundary.
Anthropic's API now offers programmatic tool calling in a managed sandbox. For a self-built implementation, Anthropic warns that client-side execution runs untrusted code outside a sandbox and can be a code-injection vector; self-managed sandboxing adds isolation but takes infrastructure work. Cloudflare's Worker-based Code Mode for MCP denies general network access by default and exposes specific services as bindings. These examples show two patterns: isolate execution, and grant it narrowly scoped capabilities. See Anthropic’s programmatic tool-calling guide and Cloudflare’s original Code Mode design.
Don't route an irreversible write through a broad code tool just to save a model turn. Keep write permissions narrow, preserve a confirmation boundary where a human must approve an action, and log which underlying tools the code invokes. If you can't audit or sandbox the code path, direct calls with approvals are easier to reason about.
What does this look like for a small MCP tool surface?
A small surface can still benefit from output shaping, but it may not need code execution. We build octofs, a filesystem MCP server with six tools, among them view and batch_edit; batch_edit applies up to 50 non-overlapping edits to one file in one call and returns fresh line ids, so the agent doesn't have to re-read the file. Octocode, our code-search server, exposes four tools by default (semantic search, structural search, signature views and a code graph) and adds six LSP tools only when you configure a language server. Octobrain, our memory server, has four. In the measurement above they came to about 3.3k, 3.5k and 4.2k definition tokens: more per tool than the reference filesystem server, and all deferred until a task needs them. For the broader safety boundary when giving an agent filesystem access, see our filesystem security guide.
The measurement decides the next move. If definitions dominate, expose fewer tools or defer them. If outputs dominate, filter them closer to the server. If intermediate data dominates across a chain, prototype code execution behind a sandbox and compare it with the same task under direct calls.
— Don
Try the measurement on one recurring task and keep the before-and-after numbers beside your server configuration. Octofs and Octocode are open source; if their tool surfaces cost more context than they should in your setup, open an issue with your numbers.



