API Reference
The createMastraCode() factory function bootstraps Mastra Code and returns a configured controller, MCP manager, and other components. Use it to embed Mastra Code in custom applications or extend its functionality.
createMastraCode()
import { createMastraCode } from 'mastracode'
const {
controller,
mcpManager,
hookManager,
authStorage,
resolveModel,
storageWarning,
builtinPacks,
builtinOmPacks,
effectiveDefaults,
} = await createMastraCode(options)
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
options | CreateMastraCodeOptions | No | Configuration options |
Returns
| Property | Type | Description |
|---|---|---|
controller | AgentController | The main orchestrator for modes, threads, messages, and tools |
session | Session<MastraCodeState> | The wired local session. Pass this (with controller) to runMC |
sessionId | string | Identity of the eager local session |
ownerId | string | Owner ID for the local session |
storage | StorageConfig | The resolved storage backend |
memory | Memory | MemoryFactory | The resolved memory instance or factory |
observability | object | Observability handles |
mcpManager | MCPManager | Manager for MCP server connections |
hookManager | HookManager | Manager for lifecycle hooks |
signalsPubSub | PubSub | PubSub used for signal routing |
githubSignals | object | GitHub PR signal handles |
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 |
observabilityWarning | string | null | Warning message if observability setup fell back |
builtinPacks | ModePack[] | Built-in mode packs |
builtinOmPacks | OmPack[] | Built-in Observational Memory packs |
effectiveDefaults | object | Effective default settings after merging |
setActiveSession | (session: Session<MastraCodeState>) => void | Publishes a session back into config closures |
CreateMastraCodeOptions
| Option | Type | Default | Description |
|---|---|---|---|
cwd | string | process.cwd() | Working directory for project detection |
homeDir | string | os.homedir() | Home directory for global config discovery |
modes | AgentControllerMode[] | Build, Plan, Fast | Override modes (model IDs, colors, which modes exist) |
subagents | AgentControllerSubagent[] | Explore, Plan, Execute | Override or extend subagent definitions |
extraTools | Record<string, Tool> | ((ctx) => Record<string, Tool>) | {} | Extra tools merged into the dynamic tool set |
disabledTools | string[] | [] | Tools removed from the dynamic tool set before exposure to the model |
storage | StorageConfig | Local LibSQL | Custom storage config instead of auto-detected default |
omScope | 'thread' | 'resource' | Auto-detected | Observational Memory scope |
settingsPath | string | Global settings | Path to a custom settings.json file |
initialState | Partial<MastraCodeState> | Default state | Initial state overrides (yolo, thinkingLevel, etc.) |
idGenerator | () => string | Default | Override id generation for threads/messages (useful for deterministic tests) |
intervalHandlers | IntervalHandler[] | gateway-sync | Override interval (background task) handlers |
resolveModel | (modelId: string, options?) => ResolvedModel | Default resolver | Custom model resolution function |
workspace | Workspace | Local FS + sandbox | Override the workspace |
configDir | string | .mastracode | Override the config directory name |
mcpServers | Record<string, McpServerConfig> | {} | Programmatic MCP server configs, merged with file-based configs |
disableMcp | boolean | false | Disable MCP server discovery |
disableHooks | boolean | false | Disable hooks |
memory | Memory | MemoryFactory | false | Built-in gateway | Override the memory instance or factory |
browser | BrowserProvider | — | Browser provider; when set the agent gains browser tools |
pubsub | PubSub | — | PubSub for signal routing |
unixSocketPubSub | boolean | false | Use the built-in Unix socket PubSub for local cross-process signal routing |
crossProcessPubSub | boolean | false | Mark the configured PubSub as cross-process-safe (skips file thread locks) |
AgentControllerMode
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 |
AgentControllerSubagent
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 |
allowedControllerTools | string[] | No | Tool IDs from controller 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
AgentController 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.
interface PermissionRules {
// Keyed by category (e.g. "read", "edit", "execute", "mcp")
categories: Record<string, 'allow' | 'ask' | 'deny'>
// Keyed by tool id, overriding the category policy
tools: Record<string, 'allow' | 'ask' | 'deny'>
}
IntervalHandler
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 |
AgentController
The AgentController instance returned by createMastraCode() is the main orchestrator. See the AgentController 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 { controller, mcpManager, hookManager, authStorage } = await createMastraCode()
const tui = new MastraTUI({
controller,
hookManager,
authStorage,
mcpManager,
appName: 'My Agent',
version: '1.0.0',
})
tui.run()
MastraTUIOptions
| Option | Type | Required | Description |
|---|---|---|---|
controller | AgentController | Yes | The controller 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
createMastraCode boots the controller and returns a ready-to-use session. Subscribe to events and send messages on the session:
import { createMastraCode } from 'mastracode'
const { session } = await createMastraCode({
cwd: '/path/to/project',
})
session.subscribe(event => {
if (event.type === 'message_update') {
const text = event.message.content
.filter(p => p.type === 'text')
.map(p => p.text)
.join('')
process.stdout.write(text)
}
})
await session.sendMessage({ content: 'Explain the auth module' })
For one-shot/headless runs, prefer runMC, which wraps this subscribe/send/aggregate loop and resolves to a typed result.
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-6',
})
const { controller } = await createMastraCode({
modes: [
{
id: 'review',
name: 'Review',
default: true,
defaultModelId: 'anthropic/claude-sonnet-4-6',
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 { controller } = await createMastraCode({
extraTools: { deploy: deployTool },
})
Remote storage
import { createMastraCode } from 'mastracode'
const { controller } = await createMastraCode({
storage: {
url: 'libsql://my-db.turso.io',
authToken: process.env.TURSO_AUTH_TOKEN,
},
})
Disable YOLO mode
import { createMastraCode } from 'mastracode'
const { controller } = await createMastraCode({
initialState: {
yolo: false,
permissionRules: {
categories: {
read: 'allow',
edit: 'ask',
execute: 'ask',
mcp: 'deny',
},
tools: {},
},
},
})