# 3.4 Code Mode (programmatic tool calling)

The model writes code against tool APIs; intermediate results stay in the sandbox.

1. Same query over the same API records.
2. JSON tool loop: intermediate results transit the context.
3. Code Mode: a script filters inside a sandboxed runtime.
4. Only the final return value enters context.

- **Use when:** Pagination, joins, filtering and multi-tool composition.
- **Avoid:** Single small calls, or no isolated runtime.

```
// written by the model, run once in the sandbox
const orders = await shop.listOrders({ month: "May" });

const late = orders
    .filter(o => o.status === "late")
    .slice(0, 3);

return late;      // only this reaches the model
```

## References

- [Code Mode: the better way to use MCP](https://blog.cloudflare.com/code-mode/) (Cloudflare)
- [Code execution with MCP](https://www.anthropic.com/engineering/code-execution-with-mcp) (Anthropic)
- [Code Mode: an entire API in 1,000 tokens](https://blog.cloudflare.com/code-mode-mcp/) (Cloudflare)
- [Executable Code Actions Elicit Better LLM Agents](https://arxiv.org/abs/2402.01030) (Wang et al.)
- [Making Claude Code safer with sandboxing](https://www.anthropic.com/engineering/claude-code-sandboxing) (Anthropic)
