Skip to main content

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

ParameterTypeRequiredDescription
optionsCreateMastraCodeOptionsNoConfiguration options

Returns

PropertyTypeDescription
harnessHarnessThe main orchestrator for modes, threads, messages, and tools
mcpManagerMCPManagerManager for MCP server connections
hookManagerHookManagerManager for lifecycle hooks
authStorageAuthStorageStorage for OAuth credentials

CreateMastraCodeOptions

OptionTypeDefaultDescription
cwdstringprocess.cwd()Working directory for the agent
modesHarnessMode[]Build, Plan, FastCustom mode configurations
extraToolsToolsInput{}Additional tools merged with built-in tools
subagentsHarnessSubagent[]Explore, Plan, ExecuteCustom subagent definitions
storageStorageConfigLocal LibSQLDatabase configuration
initialStatePartial<MastraCodeState>Default stateInitial harness state values
heartbeatHandlersHeartbeatHandler[]Default handlersBackground task definitions
resolveModel(id: string) => LanguageModelDefault resolverCustom model resolution function

HarnessMode

Each mode defines an agent configuration and display properties.

PropertyTypeRequiredDescription
idstringYesUnique identifier (e.g., "build", "plan")
namestringNoDisplay name shown in the TUI
defaultbooleanNoWhether this mode is active on startup
defaultModelIdstringNoDefault model ID for this mode
colorstringNoHex color for mode indicator (e.g., "#7c3aed")
agentAgent | ((state) => Agent)YesAgent instance or factory function

HarnessSubagent

Subagent definitions for spawning focused child agents.

PropertyTypeRequiredDescription
idstringYesUnique identifier (e.g., "explore")
namestringYesDisplay name in tool output
descriptionstringYesWhat this subagent does
instructionsstringYesSystem prompt for the subagent
toolsToolsInputNoTools available to this subagent
allowedHarnessToolsstring[]NoTool IDs from harness tools this subagent can use
defaultModelIdstringNoDefault model for this subagent type

StorageConfig

Database connection configuration.

PropertyTypeRequiredDescription
urlstringYesDatabase URL (LibSQL or PostgreSQL)
authTokenstringNoAuth token for remote LibSQL

MastraCodeState

Harness state fields available through initialState.

FieldTypeDefaultDescription
yolobooleantrueAuto-approve all tool calls
thinkingLevel"off" | "low" | "medium" | "high""off"Extended thinking depth for Anthropic models
smartEditingbooleantrueUse AST-based analysis for code edits
notifications"bell" | "system" | "both" | "off""off"Alert style when TUI needs attention
permissionRulesPermissionRulesDefault policiesPer-category and per-tool approval policies
observerModelIdstring"google/gemini-2.5-flash"Model for observational memory observer
reflectorModelIdstring"google/gemini-2.5-flash"Model for observational memory reflector
observationThresholdnumber30000Token count triggering observation pass
reflectionThresholdnumber40000Token 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.

PropertyTypeRequiredDescription
idstringYesUnique identifier for this handler
intervalMsnumberYesInterval between executions in milliseconds
handler() => Promise<void>YesAsync 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

OptionTypeRequiredDescription
harnessHarnessYesThe harness instance
hookManagerHookManagerYesHook manager from createMastraCode()
authStorageAuthStorageYesAuth storage from createMastraCode()
mcpManagerMCPManagerYesMCP manager from createMastraCode()
appNamestringNoApplication name shown in header
versionstringNoVersion 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: {},
},
},
})