Skip to main content

createCodeMode()

Added in: @mastra/core@1.38.0

The createCodeMode() function returns a tool and generated instructions that let an agent run multi-tool computations as one TypeScript function. The generated code runs in a workspace sandbox, and each external_* call runs the real tool on the host with validation, request context, and tracing.

For a conceptual overview, see Code mode.

Usage example
Direct link to Usage example

Create a code mode tool, add its generated instructions to the agent, and register the returned tool with the same id.

src/mastra/agents/shop-agent.ts
import { Agent } from '@mastra/core/agent'
import { createCodeMode, createTool } from '@mastra/core/tools'
import { LocalSandbox } from '@mastra/core/workspace'
import { z } from 'zod'

const getTopProducts = createTool({
id: 'getTopProducts',
description: 'Get top selling products',
inputSchema: z.object({ limit: z.number() }),
outputSchema: z.object({
products: z.array(z.object({ id: z.string(), name: z.string(), totalSales: z.number() })),
}),
execute: async ({ limit }) => fetchTopProducts(limit),
})

const getProductRatings = createTool({
id: 'getProductRatings',
description: 'Get ratings for a product',
inputSchema: z.object({ productId: z.string() }),
outputSchema: z.object({ ratings: z.array(z.object({ score: z.number() })) }),
execute: async ({ productId }) => fetchRatings(productId),
})

const { tool, instructions } = createCodeMode({
tools: { getTopProducts, getProductRatings },
sandbox: new LocalSandbox(),
})

export const shopAgent = new Agent({
name: 'shop-assistant',
instructions: ['You are a helpful shopping assistant.', instructions],
model: 'openai/gpt-5.5',
tools: { execute_typescript: tool },
})

Parameters
Direct link to Parameters

config:

CodeModeConfig
Configuration for the code mode tool and generated instructions.
CodeModeConfig

tools:

ToolsInput
Tools exposed to the generated code as `external_<id>` functions. Only these tools can be called.

sandbox?:

WorkspaceSandbox
Sandbox used to execute the generated code. Required unless the agent runs in a workspace that provides a sandbox. Pass `new LocalSandbox()` to run on the host explicitly.

timeout?:

number
Execution timeout in milliseconds.

id?:

string
The generated tool id.

transport?:

CodeModeTransport
Optional transport implementation used to run the generated code in the sandbox. The default transport uses stdio JSON-RPC over the workspace sandbox process API.

Returns
Direct link to Returns

Returns a CodeModeResult object.

tool:

Tool<any, any>
The generated code mode tool. By default, its id is `execute_typescript`.

instructions:

string
Generated model instructions with typed `external_*` declarations for the configured tools.

CodeModeToolResult
Direct link to CodeModeToolResult

The generated tool returns a CodeModeToolResult.

success:

boolean
Whether the generated code ran to completion without throwing.

result?:

unknown
The value returned by the generated code.

logs?:

string[]
Captured console output from `console.log`, `console.info`, `console.warn`, and `console.error`, in order.

error?:

{ message: string; name?: string; line?: number }
Error details when the generated code throws or fails to execute.
{ message: string; name?: string; line?: number }

message:

string
Error message.

name?:

string
Error name, when available.

line?:

number
Line number associated with the failure, when available.

Inspecting instructions
Direct link to Inspecting instructions

Use createCodeModeInstructions() to inspect the exact prompt content generated for a set of tools.

src/mastra/tools/code-mode-instructions.ts
import { createCodeModeInstructions } from '@mastra/core/tools'

console.log(
createCodeModeInstructions({
tools: { getTopProducts, getProductRatings },
}),
)

The instructions include the usage contract and one typed declare function external_<id>(...) line for each configured tool. Tool ids are sanitized into valid TypeScript function names, and conflicting sanitized names throw an error.

createCodeModeTool()
Direct link to createCodeModeTool()

Use createCodeModeTool() when you only need the tool and want to manage instructions separately. Most agents should use createCodeMode() so the tool and matching instructions stay together.

src/mastra/tools/code-mode-tool.ts
import { createCodeModeTool } from '@mastra/core/tools'
import { LocalSandbox } from '@mastra/core/workspace'

export const codeModeTool = createCodeModeTool({
tools: { getTopProducts, getProductRatings },
sandbox: new LocalSandbox(),
})