C4 · Code agent
Family: Single agent
Instead of JSON tool calls, the agent writes a program that composes the tools itself.
Principle
The agent writes executable code, in Python or TypeScript for instance, that calls several tools, handles loops and errors, and filters the data before reporting back. One block of code replaces several round trips, and large intermediate results stay out of the context.
The problem it solves
With separate tool calls, every intermediate result goes back through the model’s context, costing tokens and round trips.
When to use it
- The agent must compose many tools or chain processing steps with loops and conditions.
- You are analysing data and intermediate results are large: better not to pass them through the context.
When to avoid it
- You cannot provide an execution sandbox (isolation, resource limits): the pattern widens the security surface.
- A few simple tools are enough: stay with classic tool calls (A2).
Common pitfalls
The anti-patterns that misuse this pattern, best established first. Each sheet describes the symptoms, the public incidents and the remedies.
Tools and agent-computer interface
- AP19 · Excessive tool functionality — An open-ended tool (raw SQL, shell, free-form HTTP) where the task needs only a few bounded actions.
Loop, stopping and orchestration
- AP37 · Fire-and-forget actions — An action fails silently, and the agent carries on as if it had succeeded.
Security and permissions
- AP64 · Unseparated environments — The development agent can reach production, and the backups share its blast radius.
- AP65 · Agent that rewrites its own configuration — The agent can write to the files that set its permissions: an injection no longer bypasses approval, it switches it off.
- AP66 · Confirmations disabled outside a sandbox — The agent runs with no confirmations at all on a machine that holds secrets and keeps open network access.
- AP68 · Secrets within the agent’s reach — Credentials are readable by the agent, in its context or its files, instead of being injected outside the model.
Synonyms by vendor
- CodeAct (Wang et al. (ICML 2024))
- Code agents (Hugging Face smolagents)
- Code-then-execute (version sécurité) (Beurer-Kellner et al. (2025))
- Outils MCP exposés comme API de code (Anthropic (2025))
- Appel programmatique d’outils (Anthropic (2025))
Neighbouring patterns
Sources
- Executable Code Actions Elicit Better LLM Agents — X. Wang et al. (ICML 2024), 2024
- Code execution with MCP — Anthropic
- Introducing advanced tool use — Anthropic, 2025-11-24
Content reviewed on 2026-10-02