Explainer
Code Mode: when an agent writes code to call its tools
Claude Code's experimental Code Mode has Claude write JavaScript that calls its tools. How it works and what it changes for permissions, hooks and sandboxing.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
Code Mode is an experimental Claude Code setting in which Claude writes a piece of JavaScript that makes several tool calls in one step, instead of asking for each tool call and reading each result. You turn it on with CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 on Claude Code v2.1.323 or later. The code runs through a tool called REPL, and that one change moves where your permission rules, hooks and sandbox apply. If you run Claude Code with hooks or in auto mode, read the section on permissions before you switch it on.
The same idea exists on the Claude API as programmatic tool calling, and outside Anthropic as Cloudflare’s “Code Mode” for MCP. This article explains the pattern, what it buys you, and what it changes for anyone who relies on per-call review. Facts were checked against the Claude Code Code Mode docs and the programmatic tool calling docs on 25 November 2026. Code Mode is marked experimental and “may change or be removed in any release”, so check the docs again before you build on any detail here.
The idea: code as the glue between tool calls
In ordinary tool calling, every call is a round trip. The model asks for Read, the host runs it, the whole result goes back into the context, and the model decides what to do next. Ten related calls means ten trips and ten results in the context window, even when the model only needed one line from each.
The alternative is to let the model write a short program. The program calls the tools, filters and combines the results, and returns only what the model needs to read. Cloudflare put it in one sentence in September 2025: “Convert the MCP tools into a TypeScript API, and then ask an LLM to write code that calls that API.” Anthropic’s engineering team made the same argument for MCP in November 2025, with an example where loading tools on demand and processing data in code cut one workflow “from 150,000 tokens to 2,000 tokens”.
Models are trained on a lot of code. Loops, conditionals and Promise.all are a more natural way to express “check these 20 files and tell me which ones fail” than 20 separate tool requests.
What Code Mode looks like in Claude Code
You still type an ordinary prompt. Claude answers by writing JavaScript, and Claude Code runs it in your session. The docs give this example for “raise the retry limit”:
const files = await $`rg -l "function retryPolicy" src`.text();
const target = files.trim().split("\n")[0];
await edit(target, "maxAttempts: 3", "maxAttempts: 5");
({ edited: target, tests: $`npm test -- retryPolicy`.nothrow() });
One piece of code finds the file, edits it, runs the tests and returns the path and the test output. In the conversation you see the tool calls (the edit’s diff, the commands), not the code. Press Ctrl+O to open the transcript viewer, where each piece of code is a collapsed Code row you can expand.
To try it, start a session with the variable set:
CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude
Claude Code asks you to confirm before the first Code Mode session, then shows Code Mode (experimental) is on near the top. You can also set the variable in the env block of ~/.claude/settings.json. Claude Code ignores it in a project’s settings files, so a repository you clone cannot switch Code Mode on for you.
Requirements and limits
The docs list a long set of conditions. The ones most readers will hit:
- Version and model. Claude Code v2.1.323 or later on the native build, with Claude Opus 5.5, Sonnet 5.5, Haiku 5.5 or Fable 5.2. Cloud providers such as Amazon Bedrock need v2.1.331 or later; gateways are not supported.
- Surface. An interactive
claudesession in a terminal. Not the VS Code panel, the Desktop app or cloud sessions. - Organisation. Not available under the HIPAA configuration or zero data retention.
- Resuming. A Code Mode session can only be resumed with Code Mode on. Sessions started without it resume without it.
- Long-running code. Unless code runs in the background (auto or
bypassPermissionsmode), Claude waits for it and it stops after ten minutes. Background code can run for up to two hours. - Features you lose. Remote Control, Claude in Chrome and computer use do not work in a Code Mode session.
What changes for permissions
This is the part that matters for safety. Without Code Mode, every tool call is a separate event that your permission mode, rules and hooks see in turn. With Code Mode, there are two layers: the REPL call that runs the code, and the tool calls the code makes.
Per the docs:
- Rules and hooks still apply per tool. A
denyoraskrule forBash(git push *), or aPreToolUsehook onBash, still fires for agit pushinside the code. Write them under the tool’s usual name. - Auto mode reviews the code, not each call. The auto-mode classifier looks at the JavaScript before it runs. It does not see values computed at run time, such as a path taken from search output. Keep explicit rules or hooks for calls you must control.
- Prompting modes still prompt per call. In the modes that ask, you are asked about each tool call that would have prompted you anyway.
- You can approve the code itself. An
askrule forREPLmakes Claude Code ask before each piece of code starts. PressCtrl+Oto read it before you answer.
{
"permissions": {
"ask": ["REPL"]
}
}
There is one subtle change for shell hooks. A PreToolUse hook that allows or blocks commands must check each part of a compound command, because in Code Mode a git push in a folder named app can reach your hook as cd 'app' && git push. A hook that only matches the start of the string will miss it. Our hooks tutorial shows how to split and check each part.
What changes for hooks
Two hook behaviours are new:
- A
PreToolUsehook onREPLreceives the JavaScript intool_input.code. That is the place for a policy check on the code as a whole, for example refusing code that reads~/.ssh. - A
PostToolUsehook onREPLreceives what the code returned intool_response(code,result,stdout,stderr,toolsUsed). It can redact secrets by returning a changed copy asupdatedToolOutput. Keep the shape (strings forcode,stdoutandstderr), or Claude gets the original output.
Hook failures behave differently inside code. By default, a PreToolUse hook that times out refuses the call, and a hook that fails another way (a missing script, say) lets the call go on to the permission checks. If a hook guards something important, set "onFailure": "block" on it so that any failure refuses the call. And if you used a UserPromptSubmit hook to inspect tool output, move that check: from v2.1.328, UserPromptSubmit hooks no longer receive code output.
What changes for the sandbox
Claude Code’s sandbox limits shell commands. In Code Mode it still applies to the shell commands the code runs. The JavaScript itself, and its file, web and MCP tool calls, run outside that sandbox. The docs’ advice is to run Claude Code in a container or virtual machine if you need those isolated too, and to turn on strict sandbox mode so that code cannot ask to run a command unsandboxed.
That is the same rule the site gives for any agent: the sandbox is the boundary that holds when a rule is bypassed. Code Mode does not weaken it for shell commands, but it adds a new kind of code, the agent’s own JavaScript, that runs with your session’s permissions. Run AI-generated code in a sandbox covers isolating that kind of code in your own applications.
Programmatic tool calling on the API
On the Claude API the same pattern is called programmatic tool calling. You add the code execution tool (version code_execution_20260120 or later) and mark tools that code may call with allowed_callers:
{
"name": "query_database",
"description": "Run a read-only SQL query. Returns rows as a JSON array of objects.",
"input_schema": {
"type": "object",
"properties": { "sql": { "type": "string" } },
"required": ["sql"]
},
"allowed_callers": ["code_execution_20260120"]
}
Claude writes Python that runs in Anthropic’s code execution container. Each call to your tool pauses the response with a tool_use block whose caller field names the code execution run. You run the tool and send the result back, and the code carries on. Only the code’s final output enters Claude’s context, and tool results from programmatic calls do not count towards input or output tokens.
Anthropic’s own figures, from that page: on a 75-tool project-management benchmark, billed input tokens fell by roughly 38% with no change in accuracy; on τ²-bench, where each turn makes one or two sequential calls, scores were unchanged and cost went up by roughly 8%. Treat those as the vendor’s numbers, not ours, and measure on your own traffic as the page suggests.
Two details from the docs are worth knowing before you rely on it:
allowed_callers“is not a hard API-level block on direct calls”. Claude is strongly guided to respect it, but your client must still handle a directtool_usefor any tool you define. Do not use it as a security boundary.- Programmatic tool calling runs on code execution containers, so it is not eligible for zero data retention; container data is kept for up to 30 days.
When it helps and when it does not
The pattern pays off when one task means many related tool calls:
- the same change across many files,
- a search whose results need filtering before anyone reads them,
- several independent commands that can run at once,
- fan-out lookups (20 records, 50 endpoints) with large results.
It does not help, and can cost more, when each call depends on the model reasoning about the previous result, or when there are only one or two small calls. That matches both Anthropic’s τ²-bench result and the docs’ “weak fit” list.
It also changes how you design tools. A model writing code needs to know the shape of what a tool returns, so document the output format (JSON fields and types) as carefully as the input, and keep outputs structured. Design tools an AI agent can use well works through that on a real tool.
Should you turn it on?
For exploratory, many-file work in a repository you trust, Code Mode is worth trying, and the cost of trying is low: it is one environment variable, and you can turn it off with CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=0. Expect it to change between releases.
Hold off, or prepare first, if any of these apply:
- You depend on hooks that only match the start of a shell command, or on
UserPromptSubmithooks that inspect output. - You run auto mode and rely on the classifier rather than explicit rules for sensitive commands.
- You need zero data retention, HIPAA configuration, a gateway or Remote Control.
Administrators who want to wait can block it for everyone by setting the variable to 0 in managed settings. A 0 in any settings source wins over a 1 elsewhere.
Checklist before you enable it for a team
- Add
askordenyrules for the commands that must never run unreviewed (git push, deploy scripts, package publishing). - Make shell hooks split compound commands and check each part.
- Set
"onFailure": "block"on hooks that enforce policy. - Add a
PostToolUsehook onREPLif outputs can contain secrets. - Turn on the sandbox, in strict mode, or run the agent in a dev container.
- Re-read the Code Mode page after each Claude Code update while it is experimental.
Next steps
- Write and test the hooks this article mentions in Claude Code hooks, and keep the hooks reference open while you do.
- Set up rules, the sandbox and dev containers with permissions and sandboxing for coding agents.
- Make your own tools easier to call from code with design tools an AI agent can use well.
- Isolate model-written code in your own product with run AI-generated code in a sandbox.
- See how the auto mode classifier decides, and how to steer it, in Claude Code auto mode explained.
Covers
Related
- Claude Code hooks: run checks around every tool call
Write Claude Code PreToolUse and PostToolUse hooks that block destructive shell commands, format every file Claude edits and log each command for later audit.
- Permissions and sandboxing for coding agents
Set up Claude Code permission modes and rules, the Codex sandbox and approvals, and a dev container, so an agent can work without free rein.
- Design tools an AI agent can use well
Take one badly designed agent tool, fix its names, descriptions, arguments, errors and output size, and measure the difference with a small eval you can rerun.
- Run AI-generated code in a sandbox
Run model-written Python in a throwaway Docker container, then in an E2B sandbox, with time, memory, network and file limits, and a test suite of hostile code.
- Tool calling
A model emitting a structured request to call a defined function, which your code runs and whose result is then fed back to the model.