Introducing Code Mode for Mastra Agents

Your agents can now run multi-tool computations with more accurate results.

Paul ScanlonPaul Scanlon·

Jun 9, 2026

·

2 min read

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:

note

Requires @mastra/core@1.38.0 or later, added in PR #17324.

TypeScriptsrc/mastra/agents/code-mode-agent.ts
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:

Share:
Paul Scanlon
Paul ScanlonTechnical Product Marketing Manager

Paul Scanlon sits between Developer Education and Product Marketing at Mastra. Previously, he was a Technical Product Marketing Manager at Neon and worked in Developer Relations at Gatsby, where he created educational content and developer experiences.

All articles by Paul Scanlon