# API Reference The `createMastraCode()` factory function bootstraps Mastra Code and returns a configured harness, MCP manager, and other components. Use it to embed Mastra Code in custom applications or extend its functionality. ## `createMastraCode()` ```typescript import { createMastraCode } from 'mastracode' const { harness, mcpManager, hookManager, authStorage, resolveModel, storageWarning, builtinPacks, builtinOmPacks, effectiveDefaults, } = createMastraCode(options) ``` ### Parameters | Parameter | Type | Required | Description | | --------- | ------------------------- | -------- | --------------------- | | `options` | `CreateMastraCodeOptions` | No | Configuration options | ### Returns | Property | Type | Description | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- | | `harness` | `Harness` | The main orchestrator for modes, threads, messages, and tools | | `mcpManager` | `MCPManager` | Manager for MCP server connections | | `hookManager` | `HookManager` | Manager for lifecycle hooks | | `authStorage` | `AuthStorage` | Storage for OAuth credentials | | `resolveModel` | `(modelId: string, options?: { thinkingLevel?: ThinkingLevel; remapForCodexOAuth?: boolean; requestContext?: RequestContext }) => ResolvedModel` | Model resolution function | | `storageWarning` | `string \| null` | Warning message if storage fallback occurred | | `builtinPacks` | `ModePack[]` | Built-in mode packs | | `builtinOmPacks` | `OmPack[]` | Built-in Observational Memory packs | | `effectiveDefaults` | `object` | Effective default settings after merging | ### `CreateMastraCodeOptions` | Option | Type | Default | Description | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------- | ------------------------------------------- | | `cwd` | `string` | `process.cwd()` | Working directory for the agent | | `modes` | `HarnessMode[]` | Build, Plan, Fast | Custom mode configurations | | `extraTools` | `ToolsInput` | `{}` | Additional tools merged with built-in tools | | `subagents` | `HarnessSubagent[]` | Explore, Plan, Execute | Custom subagent definitions | | `storage` | `StorageConfig` | Local LibSQL | Database configuration | | `initialState` | `Partial` | Default state | Initial harness state values | | `heartbeatHandlers` | `HeartbeatHandler[]` | Default handlers | Background task definitions | | `resolveModel` | `(modelId: string, options?: { thinkingLevel?: ThinkingLevel; remapForCodexOAuth?: boolean; requestContext?: RequestContext }) => ResolvedModel` | Default resolver | Custom model resolution function | #### `HarnessMode` Each mode defines an agent configuration and display properties. | Property | Type | Required | Description | | ---------------- | ----------------------------- | -------- | ------------------------------------------------ | | `id` | `string` | Yes | Unique identifier (e.g., `"build"`, `"plan"`) | | `name` | `string` | No | Display name shown in the TUI | | `default` | `boolean` | No | Whether this mode is active on startup | | `defaultModelId` | `string` | No | Default model ID for this mode | | `color` | `string` | No | Hex color for mode indicator (e.g., `"#7c3aed"`) | | `agent` | `Agent \| ((state) => Agent)` | Yes | Agent instance or factory function | #### `HarnessSubagent` Subagent definitions for spawning focused child agents. | Property | Type | Required | Description | | --------------------- | ------------------------- | -------- | --------------------------------------------------------------------------- | | `id` | `string` | Yes | Unique identifier (e.g., `"explore"`) | | `name` | `string` | Yes | Display name in tool output | | `description` | `string` | Yes | What this subagent does | | `instructions` | `string` | Yes | System prompt for the subagent | | `tools` | `ToolsInput` | No | Tools available to this subagent | | `allowedHarnessTools` | `string[]` | No | Tool IDs from harness tools this subagent can use | | `defaultModelId` | `string` | No | Default model for this subagent type | | `maxSteps` | `number` | No | Optional maximum number of steps for the spawned subagent; defaults to `50` | | `stopWhen` | `LoopOptions['stopWhen']` | No | Optional stop condition for the spawned subagent loop | #### `StorageConfig` Database connection configuration. | Property | Type | Required | Description | | ----------- | -------- | -------- | ----------------------------------- | | `url` | `string` | Yes | Database URL (LibSQL or PostgreSQL) | | `authToken` | `string` | No | Auth token for remote LibSQL | #### `MastraCodeState` Harness state fields available through `initialState`. | Field | Type | Default | Description | | ---------------------- | ------------------------------------------------- | --------------------------- | -------------------------------------------- | | `yolo` | `boolean` | `false` | Auto-approve all tool calls | | `thinkingLevel` | `"off" \| "low" \| "medium" \| "high" \| "xhigh"` | `"off"` | Extended thinking depth for Anthropic models | | `smartEditing` | `boolean` | `true` | Use AST-based analysis for code edits | | `notifications` | `"bell" \| "system" \| "both" \| "off"` | `"off"` | Alert style when TUI needs attention | | `permissionRules` | `PermissionRules` | Default policies | Per-category and per-tool approval policies | | `observerModelId` | `string` | `"google/gemini-2.5-flash"` | Model for observational memory observer | | `reflectorModelId` | `string` | `"google/gemini-2.5-flash"` | Model for observational memory reflector | | `observationThreshold` | `number` | `30000` | Token count triggering observation pass | | `reflectionThreshold` | `number` | `40000` | Token count triggering reflection pass | #### `PermissionRules` Tool permission configuration. ```typescript interface PermissionRules { categories: { read: 'allow' | 'ask' | 'deny' edit: 'allow' | 'ask' | 'deny' execute: 'allow' | 'ask' | 'deny' mcp: 'allow' | 'ask' | 'deny' } tools: Record } ``` #### `HeartbeatHandler` Background task definition. | Property | Type | Required | Description | | ------------ | --------------------- | -------- | ------------------------------------------- | | `id` | `string` | Yes | Unique identifier for this handler | | `intervalMs` | `number` | Yes | Interval between executions in milliseconds | | `handler` | `() => Promise` | Yes | Async function to execute | ### Harness The `Harness` instance returned by `createMastraCode()` is the main orchestrator. See the [Harness Class reference](https://mastra.ai/reference/harness/harness-class) for the complete API. ## MastraTUI The `MastraTUI` class provides the terminal interface. Import it separately to build custom TUI applications: ```typescript import { createMastraCode } from 'mastracode' import { MastraTUI } from 'mastracode/tui' const { harness, mcpManager, hookManager, authStorage } = await createMastraCode() const tui = new MastraTUI({ harness, hookManager, authStorage, mcpManager, appName: 'My Agent', version: '1.0.0', }) tui.run() ``` ### `MastraTUIOptions` | Option | Type | Required | Description | | ------------- | ------------- | -------- | -------------------------------------- | | `harness` | `Harness` | Yes | The harness instance | | `hookManager` | `HookManager` | Yes | Hook manager from `createMastraCode()` | | `authStorage` | `AuthStorage` | Yes | Auth storage from `createMastraCode()` | | `mcpManager` | `MCPManager` | Yes | MCP manager from `createMastraCode()` | | `appName` | `string` | No | Application name shown in header | | `version` | `string` | No | Version shown in header | ## Examples ### Basic usage ```typescript import { createMastraCode } from 'mastracode' const { harness } = await createMastraCode({ cwd: '/path/to/project', }) await harness.init() await harness.selectOrCreateThread() harness.subscribe(event => { if (event.type === 'message_update') { console.log(event.message.content) } }) await harness.sendMessage({ content: 'Explain the auth module' }) ``` ### Custom mode ```typescript import { createMastraCode } from 'mastracode' import { Agent } from '@mastra/core/agent' const reviewAgent = new Agent({ id: 'review-agent', name: 'Review Agent', instructions: 'You are a code review specialist.', model: 'anthropic/claude-sonnet-4-6', }) const { harness } = await createMastraCode({ modes: [ { id: 'review', name: 'Review', default: true, defaultModelId: 'anthropic/claude-sonnet-4-6', color: '#f59e0b', agent: reviewAgent, }, ], }) ``` ### Custom tools ```typescript import { createMastraCode } from 'mastracode' import { createTool } from '@mastra/core/tools' import { z } from 'zod' const deployTool = createTool({ id: 'deploy', description: 'Deploy the current branch to staging', inputSchema: z.object({ environment: z.enum(['staging', 'production']), }), execute: async ({ environment }) => { // Deploy logic here return { content: `Deployed to ${environment}` } }, }) const { harness } = await createMastraCode({ extraTools: { deploy: deployTool }, }) ``` ### Remote storage ```typescript import { createMastraCode } from 'mastracode' const { harness } = await createMastraCode({ storage: { url: 'libsql://my-db.turso.io', authToken: process.env.TURSO_AUTH_TOKEN, }, }) ``` ### Disable YOLO mode ```typescript import { createMastraCode } from 'mastracode' const { harness } = await createMastraCode({ initialState: { yolo: false, permissionRules: { categories: { read: 'allow', edit: 'ask', execute: 'ask', mcp: 'deny', }, tools: {}, }, }, }) ```