Let an AI agent write and run code when a task means filtering large data, chaining many tool calls or handling records the model should not see. Keep direct tool calls for short, single actions. Code execution saves context and protects data, but only inside a locked-down sandbox with limits, logging and reviewed permissions.
What code execution changes for an agent
In the usual pattern, an agent calls one tool, reads the full result, then decides on the next call. Every result passes through the model's context, and every tool definition sits there from the start of the session.
With code execution, the agent writes a short program instead. The program calls the tools, loops over the results, filters them and returns only what the model needs to see. Anthropic's engineering team describes this approach as presenting MCP servers as code APIs, so the agent loads tool definitions on demand and processes data before it reaches the model. Cloudflare calls the same idea Code Mode.
The model still makes the decisions. What moves is the plumbing: loops, joins, retries and formatting happen in code rather than in a long chain of model turns.
When code execution pays off
Large results that need filtering
If a tool returns a long export, a full ticket history or a large spreadsheet, passing it whole to the model wastes context and money. A short script can pick the matching rows, total a column or compare two lists, then hand back a small result. This fits well with deciding what goes in the context window.
Many steps with simple logic between them
Fetch a record, check a field, update another system, repeat for each item. Written as code, the loop runs in one go. Done as separate tool calls, each step costs a model turn and adds another chance for the agent to lose track.
Data the model does not need to read
Intermediate results can stay in the execution environment. A script can move customer records from one system to another without the raw values ever entering the prompt, which helps when you are working to keep personal data out of AI agent logs.
Work you want to reuse
Once a script works, it can be saved as a reviewed function the agent calls next time, rather than being written fresh on every run.
When direct tool calls are the safer choice
Code execution is not free. Anthropic's post is clear that running agent-written code needs a secure execution environment, with sandboxing, resource limits and monitoring, and that this adds operational overhead that direct tool calls avoid.
Stay with plain tool calls when:
- The task is a single action, such as looking up one order or sending one message.
- Each step needs a human decision, because a script that runs end to end skips the checkpoints you designed.
- The action is hard to reverse, such as a payment or a deletion, where you want each call visible and approved.
- Your team cannot yet run a sandbox in production with the controls below.
Well-designed tools still matter either way. Code only helps if the functions it calls are clear, narrow and safe, which is the same discipline as designing tools an AI agent can use.
The controls a code sandbox needs
Treat agent-written code as untrusted code from an unknown author, because in effect it is.
Isolation
Run each session in its own container or micro virtual machine, with no access to the host, other sessions or production credentials. Throw the environment away when the task ends.
Network and permissions
Block outbound network access by default and allow only the specific services the task needs. Give the sandbox its own scoped credentials, never a shared admin key, and route writes through the same approved tools the agent would otherwise call.
Limits
Set limits on run time, memory, processor use and the number of tool calls a script can make. A loop that never ends should fail quickly rather than run up a bill, the same concern as stopping runaway AI agent loops.
Logging and review
Record every script the agent wrote, what it called and what it returned. Without that, you cannot audit what an AI agent did when someone asks why a record changed.
Testing before production
Try code execution first against copies of real systems. A sandbox for testing write actions shows how the agent behaves before it touches live data.
How to decide for your agent
Start with direct tool calls. Move a workflow to code execution when you can point to a specific problem it solves: context filling up with tool results, long chains of repetitive calls, or sensitive data passing through the model. Pilot it on one read-heavy task, compare the results and the running cost against the tool-call version, and expand only once the sandbox controls are in place and reviewed.
If you are weighing this for an agent in production, our team can help through enterprise AI product engineering, or you can contact us to talk it through.
Frequently asked questions
What is code execution for AI agents?
It is a pattern where the agent writes a short program to call its tools, instead of calling each tool directly and reading every result. The program runs in a sandbox, does the looping, filtering and joining, and returns only the result the model needs. The model still plans the task and decides what to do, while the code handles the mechanical steps between tool calls.
Is letting an AI agent run code safe?
It can be, if the code runs in an isolated sandbox with no host access, blocked network by default, scoped credentials, resource limits and full logging. Without those controls, agent-written code is a real risk, because a prompt injection or a simple mistake could read data or call systems it should not. Treat every script as untrusted code and review the permissions the sandbox holds.
Does code execution reduce the cost of running an agent?
It often reduces context use, because large tool results are filtered in code rather than passed whole to the model, and tool definitions load only when needed. That usually means fewer tokens per task. It also adds the cost of running and monitoring a sandbox. Compare both on a real workload before assuming a saving, since short single-action tasks gain little from it.
Do we need MCP to use code execution?
No. The pattern works with any set of tools that can be wrapped as functions the agent's code can call. MCP makes it easier, because servers already describe their tools in a standard way that can be presented as a code library. If your agent uses direct API integrations, you can expose those as functions in the sandbox instead, with the same permission controls.



