Use code mode when your agents touch multiple tools to perform complex computations. Code mode lets the model orchestrate your existing tools in an isolated sandbox and return their results as a single, more accurate response.
Before code mode, multi-tool queries run the agentic loop several times: The model decides what tool to call, reads the results, decides again and repeats. Each turn drops the full tool response into the agent's context window.
With code mode, the model writes a tailored function per user query that reduces or aggregates the results, and returns the answer in a single tool call. This reduces tokens in the context window and improves reasoning and accuracy.
You don't have to predict every analytical question your users will ask. A handful of focused tools like getOrders, getCustomer, or getProduct give code mode the raw data it needs to handle a wide range of analytical questions.
Get started
createCodeMode returns the tool plus generated instructions. With no id, the tool is named execute_typescript. Add both to your agent:
Requires @mastra/core@1.38.0 or later, added in PR #17324.
import { Agent } from "@mastra/core/agent";
import { createCodeMode } from "@mastra/core/tools";
import { LocalSandbox } from "@mastra/core/workspace";
import { getOrders } from "../tools/get-orders";
import { getCustomer } from "../tools/get-customer";
import { getProduct } from "../tools/get-product";
const { tool, instructions } = createCodeMode({
tools: { getOrders, getCustomer, getProduct },
sandbox: new LocalSandbox()
});
export const codeModeAgent = new Agent({
id: "code-mode-agent",
name: "Code Mode Agent",
instructions: [
`You are a data assistant for an e-commerce store.
Compose the provided tools to answer analytical questions.
`,
instructions
],
model: "anthropic/claude-sonnet-4-5",
tools: { execute_typescript: tool }
});
This example uses LocalSandbox for local development. For production, use a managed sandbox provider like E2B, Modal, or Daytona.
For more information and full configuration options, see:
