# Claude Code's Code Mode: How It Replaces Tool Calls with JavaScript

> Claude Code's Code Mode executes tools via local JavaScript scripts to eliminate context bloat, cut latency, and slash token overhead by up to 99.9%.

Source: https://camnangai.com/en/tools/claude-code-code-mode  
Published: 2026-11-28

**Code Mode** in Claude Code is an experimental execution mode that transforms step-by-step tool
  calls into executable JavaScript code blocks within an isolated local runtime.

Instead of executing turn-by-turn RPC message loops for every operation, Claude Code lets the model
write TypeScript scripts that orchestrate tool calls, process control flow, and filter data directly
inside an ephemeral V8 sandbox. By using Progressive Disclosure to inspect type schemas on demand,
Code Mode executes loops, parallel queries, and mathematical joins locally.

  Returning only explicit summaries to context drastically cuts context token bloat, eliminates
  network latency round trips, and preserves context window capacity.


![Illustration of Code Mode in Claude Code: replacing sequential tool calls with sandboxed JavaScript execution](https://camnangai.com/articles/code-mode-trong-claude-code/01-infographic-en.webp)

## The Token Tax and Limits of Traditional Tool Calling Loops


  When you deploy autonomous AI agents using standard JSON-RPC tool calling, your large language
  model operates essentially as an inefficient RPC router. In every interaction turn, the client
  must serialize and inject structured JSON schemas defining every available tool's name,
  description, and parameter bounds directly into the prompt context.

The model processes this overhead, emits a single JSON tool invocation payload, halts its reasoning
pass to await host-side client execution, and ingests the raw, unformatted result back into
conversation history. As your system's tool catalog expands and task depth deepens, this
message-passing topology triggers severe performance degradation.

The first structural wall you encounter is Token Tax 1 (Schema Bloat). Upfront tool schema definitions consume critical context window space long before runtime execution begins. A modest agent deployment exposing 50 tools across internal microservices absorbs between 9,400 and 55,000 tokens per turn purely to declare static interface capabilities. At enterprise scale (such as exposing Cloudflare's platform catalog of over 2,500 REST API endpoints), traditional JSON-RPC schemas require roughly 1.17 million tokens. Ingesting this schema overhead consumes available context budgets instantly, forcing severe context truncation and degrading model reasoning quality before your system processes a single user prompt.

As your agent executes multi-step workflows, you encounter Token Tax 2 (Intermediate Result Degradation & N+1 Latency). Tasks requiring iterative operations (such as inspecting thousands of spreadsheet rows, parsing hundreds of expense receipts, or running broken link verification across local documentation) force megabytes of transient raw JSON payloads directly into conversation history. Because standard setups re-transmit prior conversation turns on every cycle, this architecture triggers `O(N^2)` exponential context accumulation while compounding network round-trip latency across `N+1` model turns. Furthermore, asking an LLM to perform string filtering, array joins, and floating-point arithmetic natively across raw text responses leads to calculation errors and hallucinations, whereas executing deterministic code in a local runtime guarantees mathematical precision.

![Diagram comparing the traditional JSON-RPC tool calling bottleneck with schema bloat and N+1 round-trip latency](https://camnangai.com/articles/code-mode-trong-claude-code/02-en.webp)

## What Code Mode Is and How It Replaces Tool Calls with JavaScript


  **Code Mode** fundamentally restructures your agentic architecture by collapsing dozens or
  hundreds of individual JSON tool definitions into a single programmatic interface: an `exec` or
  REPL tool.

Rather than generating isolated JSON objects across fragmented model turns, the LLM authors
complete, idiomatic TypeScript or JavaScript scripts. These scripts execute directly within an
isolated local runtime sandbox, shifting the model's operational role from a high-latency RPC broker
to an autonomous software engine that writes its own orchestration logic.

To maintain minimal upfront context footprint without sacrificing operational depth, Code Mode relies on Progressive Disclosure and standard protocol specifications. Modern Model Context Protocol (MCP) servers ship explicit `outputSchema` definitions alongside `inputSchema` contracts. This structural type awareness allows Code Mode to expose tool capabilities on demand via typed disk files (such as `./servers/google-drive/getDocument.ts`) or dynamic interface declarations (`declare namespace tools`). Because the model inspects `outputSchema` return types prior to runtime execution, it performs static AST validation to chain asynchronous calls (`await tools.service.method()`) inside a single script without needing to observe intermediate response payloads turn-by-turn.

Actual execution occurs inside an ephemeral runtime sandbox, such as a V8 isolate, QuickJS engine, or WebAssembly (WASM) isolate. Within this environment, standard JavaScript handles execution control flow using `for` and `while` loops, concurrent promises via `Promise.all`, conditional branching, regular expressions, and native array operations like `.filter()` and `.slice()`. Instead of relying on prompt context for state management, host-exposed primitives (`store()`, `load()`, and pre-authenticated capability proxies) let your scripts persist data pointers and key-value references outside of conversation history. Multi-megabyte raw API responses and intermediate iteration variables remain isolated in local memory; only explicit return values, console outputs, or pruned summary objects cross the host-guest bridge into the model's context window.

![Code Mode Architecture: Progressive disclosure of TypeScript stubs and local tool orchestration via JavaScript](https://camnangai.com/articles/code-mode-trong-claude-code/03-en.webp)

## Real-World Gains: Slashing Context Bloat and Eliminating Round-Trip Latency

Transitioning your agent architecture from turn-by-turn message passing to programmatic script execution yields massive, measurable context savings across real-world workloads. When managing enterprise API surfaces, upfront schema token overhead collapses from ~1.17 million tokens down to approximately 1,000 tokens—a 99.9% structural reduction. Across multi-turn integration workflows, conversation payload overhead drops from ~14,000 raw API tokens to just 500 summary tokens (a 96.4% savings), while complex multi-document retrieval tasks drop context consumption from 150,000 tokens to 2,000 tokens (a 98.7% reduction).

Beyond cutting token budgets, **Code Mode** eliminates model turns and round-trip network latency by executing complex iterative logic inside a single pass. For example, executing 100 sequential build operations (which typically forces 100 distinct model inference passes to issue shell calls and parse build output logs) can be expressed as a single JavaScript `for` loop that runs locally to completion in 2 minutes and 23 seconds. The model receives a single consolidated status summary at the end of the script, skipping 99 intermediate inference turns and avoiding their associated prompt processing delays.

Code Mode also provides a native Background Execution feature when configured in auto-permission mode (`--permission-mode auto`). When long-running execution scripts begin, such as bulk build operations or extensive codebase security scans, the execution thread automatically shifts to the background. This allows you to continue asking questions, executing queries, and conversing interactively with Claude while background scripts run concurrently in your session for up to 2 hours.

![Metrics chart showing token savings and latency reduction of Code Mode across real-world workloads](https://camnangai.com/articles/code-mode-trong-claude-code/04-en.webp)

## Enabling Code Mode and Navigating Its Security Guardrails

Activating experimental **Code Mode** requires explicit user-level environment configuration. You can launch a single terminal session by setting `CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude`, or persist the setting across sessions by adding `"CLAUDE_CODE_EXPERIMENTAL_CODE_MODE": "1"` inside the `env` block of your user-level configuration file at `~/.claude/settings.json`. To prevent untrusted cloned repositories from enabling local code execution automatically, Claude Code strictly ignores this environment variable if declared within project-level settings files.

When configuring your deployment, you must navigate specific operational edge cases:

- **CI Environment Restrictions:** If your terminal environment exports `CI=1` or runs inside a continuous integration runner, Code Mode fails initialization. You must explicitly run `unset CI` before launching the CLI.
- **Agent Teams Compatibility:** On CLI builds prior to version `2.1.326`, setting `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` conflicts with Code Mode. You must upgrade to `2.1.326+` or temporarily override your settings using `claude --settings '{"env":{"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS":"0"}}'`.
- **System Prerequisites:** You must run a native CLI build (version 2.1.323+), connected directly to Anthropic API endpoints via a subscription or Console account. Code Mode is incompatible with Amazon Bedrock, Google Cloud Vertex AI, third-party LLM gateways, or custom `ANTHROPIC_BASE_URL` proxies. Supported models include Opus 5.5, Sonnet 5.5, Haiku 5.5, and Fable 5.2. Execution is restricted to interactive CLI sessions and cannot be used with print mode (`-p`), the Agent SDK, VS Code extensions, Desktop applications, or cloud sessions.

Operational security is governed by strict runtime safeguards. Sessions initialized in Code Mode enforce a session lock: transcripts started under Code Mode can only be resumed if Code Mode remains active (`CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude --continue`). In terminal sessions, generated JavaScript blocks are hidden behind collapsed UI logs (e.g., "Read 8 files, ran 16 shell commands"); engineers can press `Ctrl+O` to open the transcript viewer and inspect full script execution blocks. In auto-permission mode, an automated security classifier inspects the generated JavaScript code once prior to execution. However, underlying tool calls (such as `Bash` invocations inside scripts) continue to trigger standard `PreToolUse` hooks and permission rules. Hook authors must account for script execution patterns: shell commands may prepend directory changes (such as `cd 'app' && git push`), requiring hooks to parse multi-part command chains rather than matching simple string prefixes. Hooks inspecting REPL execution directly must parse JavaScript source code directly from `tool_input.code`.

## When to Enable Code Mode and When to Stick with the Default Loop

Code Mode is the optimal architecture when you build complex, multi-step, or data-intensive development workflows. You should enable Code Mode when performing batch refactoring across dozens of source files, aggregating or joining datasets where raw API responses must stay out of prompt history, executing multi-step link or build verification loops, and running long background tasks while maintaining active conversation threads in your terminal session.

Conversely, you should retain the default JSON-RPC tool loop for simple, single-step operations (such as inspecting a single file or querying a single command) where script generation adds unnecessary abstraction overhead. You must also stick with the standard tool loop if your deployment operates behind enterprise LLM gateways, routes requests through cloud provider platforms like Amazon Bedrock, relies on custom Agent SDK implementations, or requires active integration with Chrome browser debugging, Remote Control, or desktop computer use capabilities, as these features are disabled while Code Mode is active.

![Decision matrix: When to enable Code Mode versus when to retain the default tool loop](https://camnangai.com/articles/code-mode-trong-claude-code/05-en.webp)

## References

- [Claude Code Overview Documentation](https://code.claude.com/docs/en/overview)
- [Claude Code Settings and Configuration](https://platform.claude.com/docs/en/agents-and-tools/claude-code/settings)
- [Code execution with MCP for efficient agents — Anthropic](https://www.anthropic.com/research/code-execution-with-mcp)
- [Code execution with MCP: Building more efficient agents — Simon Willison](https://simonwillison.net/2025/Nov/4/code-execution-with-mcp/)
- [How to use Code Mode in Claude Code — Flavio Copes](https://flaviocopes.com/claude-code-code-mode/)
- [Introducing advanced tool use on the Claude Developer Platform — Anthropic](https://www.anthropic.com/research/advanced-tool-use)
- [What Is Code Mode: How to Cut AI Agent Context by 99% Using Code Instead of JSON-RPC — DEV Community](https://dev.to/volodymyr_nehir/what-is-code-mode-how-to-cut-ai-agent-context-by-99-using-code-instead-of-json-rpc-4klf)
- [Why Agents Are Soon Only Going to Have 1 Tool — Philschmid](https://www.philschmid.de/code-mode)
