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()
import { createMastraCode } from 'mastracode'
const { harness, mcpManager, hookManager, authStorage } = 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 |
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<MastraCodeState> | Default state | Initial harness state values |
heartbeatHandlers | HeartbeatHandler[] | Default handlers | Background task definitions |
resolveModel | (id: string) => LanguageModel | 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 |
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 | true | Auto-approve all tool calls |
thinkingLevel | "off" | "low" | "medium" | "high" | "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.
interface PermissionRules {
categories: {
read: 'allow' | 'ask' | 'deny'
edit: 'allow' | 'ask' | 'deny'
execute: 'allow' | 'ask' | 'deny'
mcp: 'allow' | 'ask' | 'deny'
}
tools: Record<string, 'allow' | 'ask' | 'deny'>
}
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<void> | Yes | Async function to execute |
Harness
The Harness instance returned by createMastraCode() is the main orchestrator. See the Harness Class reference for the complete API.
MastraTUI
The MastraTUI class provides the terminal interface. Import it separately to build custom TUI applications:
import { createMastraCode } from 'mastracode'
import { MastraTUI } from 'mastracode/tui'
const { harness, mcpManager, hookManager, authStorage } = 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
import { createMastraCode } from 'mastracode'
const { harness } = 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
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',
})
const { harness } = createMastraCode({
modes: [
{
id: 'review',
name: 'Review',
default: true,
defaultModelId: 'anthropic/claude-sonnet-4',
color: '#f59e0b',
agent: reviewAgent,
},
],
})
Custom tools
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 } = createMastraCode({
extraTools: { deploy: deployTool },
})
Remote storage
import { createMastraCode } from 'mastracode'
const { harness } = createMastraCode({
storage: {
url: 'libsql://my-db.turso.io',
authToken: process.env.TURSO_AUTH_TOKEN,
},
})
Disable YOLO mode
import { createMastraCode } from 'mastracode'
const { harness } = createMastraCode({
initialState: {
yolo: false,
permissionRules: {
categories: {
read: 'allow',
edit: 'ask',
execute: 'ask',
mcp: 'deny',
},
tools: {},
},
},
})