Implement Code Mode for TypeScript AI Agents: Batch Tool Calls and Cut Token Burn (2026)
Claude Code shipped experimental Code Mode. Build the same pattern in your own Next.js and Node.js agents with the AI SDK code-mode package: concurrent tools, filtered results, and a QuickJS sandbox.
By Mussawar Hayat
Batch Tool Calls Instead of Chatting With Every Result
On November 12, 2026 Claude Code 2.1.323 added experimental Code Mode. Instead of emitting one tool call, reading the full result, and deciding the next step, Claude writes a short JavaScript program that calls several tools, filters the output, and returns only what the model needs. Intermediate data stays out of the context window.
The same problem exists in every production agent you write with the AI SDK or a custom loop. A ten-step job becomes ten model turns and a growing transcript. Code mode collapses that. This guide shows the production shape for TypeScript backends: the official AI SDK code-mode package, QuickJS isolation, execution limits, and the security boundary you must keep.
What You Will Learn
- Why sequential tool calling burns tokens and latency
- How Claude Code Code Mode and the AI SDK code-mode package differ
- A production pattern that routes tools through code mode while keeping approval-gated tools direct
- Execution limits, concurrent worker caps, and what the QuickJS sandbox actually prevents
- Where node:vm fails as a sandbox and why you should not copy Claude Code’s in-process approach
Table of Contents
- The sequential tool-call problem
- How code mode works
- Step-by-step implementation
- Best practices
- Security considerations
- Performance notes
- Common mistakes
- Real use cases
- FAQ
- Summary
1. The Problem
Classic agent loops treat every tool as a separate model turn. The model asks for a read, receives the full file, reasons, asks for a search, receives every match, reasons again. Large tool results and repeated system prompts dominate cost. Parallel independent work is impossible because each call waits for the previous result to re-enter the context.
Claude Code’s Code Mode (experimental, off by default, Claude Code v2.1.323+) and Anthropic’s programmatic tool calling both attack this. The AI SDK’s experimental @ai-sdk/code-mode package gives the same capability to any TypeScript application: the model writes JavaScript or type-stripped TypeScript that calls your tools as async functions. Only the final JSON-serializable return value (plus optional console output) returns to the model.
2. How Code Mode Works
You declare a tool set. You mark which tools may be called from generated code via experimental_toolCallers. The code-mode tool receives a TypeScript-shaped catalog of those tools. The model emits a program. The package runs it in a fresh QuickJS context. Nested tool calls execute in your host process (outside the sandbox) after schema validation. The program’s return value becomes the tool result the model sees.
Supported features include top-level await, Promise.all, standard control flow, JSON.parse/JSON.stringify, and the four common console methods. Detached promises that outlive the return fail the run. The sandbox has no process, require, filesystem, fetch, or eval. Any network or system capability must be a tool you explicitly provide.
Claude Code implements its own Code Mode with an in-process node:vm context (on Bun). Node’s own documentation states that vm is not a security boundary. One constructor escape reaches the host. The AI SDK package uses QuickJS instead. Prefer that isolation for application code you do not fully control.
3. Step-by-Step Implementation
3.1 Install
Requires Node.js 22 or later. Not available in the browser or edge runtimes.
pnpm add ai @ai-sdk/code-mode zod3.2 Define tools and route them through code mode
Keep tools that need human approval or that perform irreversible actions as direct tools. Code mode does not integrate with the AI SDK’s tool-approval flow; a nested approval request is rejected rather than paused.
import { generateText, tool } from 'ai'
import { codeModeTool, DIRECT_TOOL_CALL } from '@ai-sdk/code-mode'
import { anthropic } from '@ai-sdk/anthropic'
import { z } from 'zod'
const getInventory = tool({
description: 'Return current stock for a product SKU',
inputSchema: z.object({ productId: z.string() }),
execute: async ({ productId }) => {
// replace with real data access
return { productId, availableUnits: 42 }
},
})
const getDemand = tool({
description: 'Return requested units for the same SKU',
inputSchema: z.object({ productId: z.string() }),
execute: async ({ productId }) => {
return { productId, requestedUnits: 15 }
},
})
const sendAlert = tool({
description: 'Send an irreversible ops alert. Requires human approval.',
inputSchema: z.object({ message: z.string() }),
execute: async ({ message }) => {
// approval-gated path stays direct
return { sent: true, message }
},
// needsApproval: true — keep this tool out of code mode
})
const codeMode = codeModeTool({
executionPolicy: {
timeoutMs: 30_000,
cpuTimeoutMs: 10_000,
memoryLimitBytes: 64 * 1024 * 1024,
maxResultBytes: 1024 * 1024,
maxBridgeRequests: 50,
maxInFlightBridgeRequests: 8,
},
})
const result = await generateText({
model: anthropic('claude-sonnet-5.5'),
tools: {
codeMode,
getInventory,
getDemand,
sendAlert,
},
experimental_toolCallers: {
getInventory: ['code_mode'],
getDemand: ['code_mode'],
// sendAlert stays directly callable only
},
prompt: 'Check whether SKU sku_123 has enough stock for current demand. Return remaining units. Do not send alerts.',
})
The model can then emit a program such as:
const [inventory, demand] = await Promise.all([
tools.getInventory({ productId: 'sku_123' }),
tools.getDemand({ productId: 'sku_123' }),
])
return {
sufficient: inventory.availableUnits >= demand.requestedUnits,
remaining: inventory.availableUnits - demand.requestedUnits,
}
Only that final object enters the conversation. The two tool payloads do not.
3.3 Optional: stable tool definitions for caching
By default the code-mode tool description changes when the set of host tools changes. Set toolDiscovery: 'conversation' so the provider-visible tool definition stays fixed and the catalog arrives as a user message. Actual cache hits still depend on the provider.
3.4 Cap concurrent workers
import { experimental_setMaxWorkers as setMaxWorkers } from '@ai-sdk/code-mode'
setMaxWorkers(4)
Without a cap the package chooses a value based on available memory, up to 32 workers.
4. Best Practices
- Route only pure, idempotent, or easily reversible tools through code mode. Keep writes that need approval or audit as direct tools.
- Write precise Zod schemas and descriptions. The generated TypeScript signatures come from them. Vague schemas produce broken programs.
- Return the smallest useful value. The whole point is to filter before the model sees the data.
- Set tight
executionPolicyvalues in production. Defaults exist; override them to the minimum that still finishes real jobs. - Pair code mode with the same project rules and permission model you already use for Claude Code or the OpenAI Agents SDK. Code mode does not replace authorization inside each tool.
- Log the generated source (size-capped) for debugging. Do not log full tool payloads that may contain secrets.
- Link related internal posts: Claude Code Mods in TypeScript and OpenAI Agents SDK multi-agent workflows. For implementation help see the services page.
5. Security Considerations
- The QuickJS context is a fresh isolate. It cannot reach Node globals, the filesystem, or the network by itself. Treat it as defense in depth, not the only control.
- Every tool you expose is available to the generated program. Enforce authentication, authorization, and input validation inside the tool’s
executefunction. Schema validation happens beforeexecute, but business rules still belong in the tool. - Do not implement code mode with
node:vmorvm2. Node documents that thevmmodule is not a security mechanism. Community reports on Claude Code’s implementation correctly flag this. - Code mode currently rejects nested tools that require user approval. Do not work around that by removing the approval requirement.
- Cap
maxBridgeRequests,maxInFlightBridgeRequests, timeouts, and result size. An unbounded loop of tool calls is a denial-of-wallet vector. - Abort signals from the parent generation are forwarded. Still set your own timeouts so a hung tool cannot hold a worker forever.
6. Performance Notes
Promise.all lets independent tools run concurrently. That is the main latency win. Token savings come from two places: fewer model turns and the absence of intermediate tool results in the context. Claude Code’s own documentation and early user measurements show the fixed tool list shrinks as well; the AI SDK package produces a similar effect when you route most tools through code mode.
CPU time inside the sandbox is limited separately from wall-clock time spent waiting on tools (cpuTimeoutMs vs timeoutMs). Memory and result-size limits prevent a single program from exhausting the host.
7. Common Mistakes
- Exposing every tool, including destructive ones, to code mode.
- Returning large arrays or full documents from the program. Filter first.
- Forgetting top-level await or leaving promises un-awaited. The run fails.
- Assuming TypeScript is type-checked. The package only strips type syntax.
- Running the package on Node < 22 or in an edge runtime.
- Copying Claude Code’s
node:vmapproach into application code.
8. Real Use Cases
- Inventory and pricing checks that need two or three reads before a decision.
- Log or trace analysis where the model should see only matching lines, not the full file.
- Multi-file refactors that search, filter, and edit without re-reading every intermediate result.
- Data aggregation across internal APIs where only the final summary matters.
FAQ
Does Claude Code Code Mode use the AI SDK package?
No. Claude Code has its own experimental implementation (v2.1.323+) that runs generated JavaScript in-process. The AI SDK package is a separate, QuickJS-based option for your own applications.
Can I use code mode with models other than Claude?
Yes. The package works with any model the AI SDK supports, provided the model can emit valid JavaScript or type-stripped TypeScript.
Is the sandbox a complete security boundary?
No. It prevents the generated program from directly reaching Node APIs. Tools still run with the privileges of your server process. Authorization belongs in each tool.
What happens if the generated code needs user approval?
Nested approval is not supported. Keep those tools as direct tools.
Summary
Code Mode, whether in Claude Code or via the AI SDK’s @ai-sdk/code-mode package, is the practical response to chatty agents. Batch the tool calls, filter the results, and return only the value the model needs. Use QuickJS isolation, tight execution limits, and keep irreversible tools out of the generated program.
Key Takeaway
Treat code mode as a context-control and concurrency tool, not a sandbox that replaces authorization.
Next step
If you need this pattern wired into an existing Next.js or Node service, including guardrails and observability, see the services page or read the related guides on Claude Code mods and least-privilege agent identities.

Written by
Mussawar Hayat
Next.js & Web3 Full-Stack Developer
I build production SaaS platforms, dashboards and smart-contract front ends with Next.js, TypeScript, PostgreSQL and Solidity, working remotely with teams in North America and Europe. The guides here come from problems I've solved on client and personal projects.
