# 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](https://mastra.ai/docs/agents/code-mode).

## Usage example

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

```typescript
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

**config** (`CodeModeConfig`): Configuration for the code mode tool and generated instructions.

**config.tools** (`ToolsInput`): Tools exposed to the generated code as \`external\_\<id>\` functions. Only these tools can be called.

**config.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.

**config.timeout** (`number`): Execution timeout in milliseconds.

**config.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

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

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.

**error.message** (`string`): Error message.

**error.name** (`string`): Error name, when available.

**error.line** (`number`): Line number associated with the failure, when available.

## Inspecting instructions

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

```typescript
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()

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.

```typescript
import { createCodeModeTool } from '@mastra/core/tools'
import { LocalSandbox } from '@mastra/core/workspace'

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

## Related

- [Code mode](https://mastra.ai/docs/agents/code-mode)
- [createTool()](https://mastra.ai/reference/tools/create-tool)
- [Workspace overview](https://mastra.ai/docs/workspace/overview)