Code as Protocol: Reducing Token Consumption in AI Agent Tool Calls

    This article explains why AI agents that call tools one step at a time consume large numbers of tokens, and how Code Mode moves orchestration into local scripts to reduce context size and model round trips. It also outlines the trade-offs, including task fit, error handling, sandboxing, and rollout.

    Developers who have used AI coding assistants often have a similar experience: the quality of completed tasks is good, but the bill grows fast. To understand where costs can be reduced, first look at what makes the traditional agent workflow so heavy.

    In a common orchestration pattern, the model sits at the center of the task. It calls a search tool to locate files, a read tool to view their contents, and an edit tool to modify the code. When each step depends on the result of the previous one, the tool output must be sent back to the model so it can decide the next action. This design, where every step passes through the model, creates two hidden but large costs.

    1. Static overhead: tool definitions resent every turn

    To teach the model how to use tools, each request must include the full tool definitions, including function signatures, parameter descriptions, and usage constraints. An independent evaluation that broke down request payloads showed that, without optimization, each request includes more than a dozen built-in tool definitions by default. The first request alone can reach tens of thousands of tokens. The key issue is that, as long as the session continues, this “manual” is resent unchanged in every request, even when the model already knows how to use the tools.

    2. Dynamic overhead: every intermediate result stays in history

    The second cost arises during task execution. Many tool outputs only need a quick scan: pulling error lines out of a build log, or picking a few useful fields from a batch of database records. But under the turn-by-turn calling mechanism, the entire log or the entire set of raw records must be written into the conversation history. It is then billed again as context in every subsequent turn. For example, if a model pulls over a hundred support tickets from an external data source and totals the refund amounts, the turn-by-turn approach drags all of those records into the context in full.

    The combined effect is that the more turns a task takes, the more token usage snowballs. Changing one or two functions shows little of this problem. But once a task involves debugging across dozens of files, or batch-fetching external data through MCP-style protocols, the cost curve rises sharply.

    2. A New Approach: Delegating Orchestration to Local Code

    A recent update to a mainstream AI coding tool introduced an experimental direction worth watching, commonly called “Code Mode.” Its core idea can be summarized in one sentence:

    When code becomes the communication protocol between an agent and its tools, orchestration can happen outside the model.

    Concretely, instead of having the model issue tool calls one at a time, the model writes an entire set of operations as one local script. The script runs in the local environment, and tool calls, result filtering, and intermediate aggregation all happen inside it. The model sees only the final, condensed result, not the full raw output.

    Advantage 1: Much smaller context

    Intermediate data produced during script execution no longer enters the conversation history. The 120 records the model would otherwise need to “read” may now require only one line of aggregated output. For example:

    1. # The model only generates this script instead of reading each record turn by turn
    2. tickets=$(fetch_tickets --status=refund)
    3. total=$(jq '[.[].amount] | add' <<< "$tickets")
    4. echo "Total refunds: $total"

    Third-party tests show that, without changing the model, enabling this kind of mode for multi-step development tasks can reduce API bills by about 20%. In scenarios with frequent external tool calls, the total number of tokens the model processes can drop by more than 60%.

    Advantage 2: More efficient batching and branching

    In the traditional mode, branching logic such as “if condition A, do X, otherwise do Y” requires the model to take part in every decision. In a script, that control flow runs in local code without any model calls. Loops, batch processing, and parallel calls also shrink from multi-turn conversations into a single generation and a single execution. This reduces inference latency and the number of requests.

    3. Scope and Practical Recommendations

    Code Mode is not a cure-all. In practice, weigh the following points:

    1. Task fit. Batch data processing, multi-file search, and cross-tool aggregation benefit most. Tasks that depend heavily on the model making step-by-step judgments, where each step’s result is highly uncertain, gain less from scripting.
    2. Error handling. When a script fails, the model can only rewrite it based on the error message. Build in thorough logging and assertions so that a “black box” failure does not lead to more retries, which would cost more.
    3. Security boundaries. Delegating orchestration means running more complex code locally. Always run it in a sandbox or with restricted permissions, so that accidental changes cannot affect the file system or external services.
    4. Versions and feature flags. These capabilities are often offered as experimental features that are off by default. After upgrading to a newer version, enable them explicitly in the settings, and compare the same set of tasks before and after to measure the actual benefit.

    Conclusion

    Until now, cutting agent costs meant one of two options: waiting for cheaper models, or downgrading to smaller ones. The first is passive, and the second sacrifices quality. Code Mode offers a third path. Without changing the model’s capabilities, it reduces wasted context by changing how the model and tools communicate. The idea behind it, letting deterministic logic run in code and letting the model focus on decisions that actually require reasoning, is likely to become a common design pattern for next-generation agent architectures.