Skip to main content

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

ParameterTypeRequiredDescription
optionsCreateMastraCodeOptionsNoConfiguration options

Returns

PropertyTypeDescription
controllerAgentControllerThe main orchestrator for modes, threads, messages, and tools
sessionSession<MastraCodeState>The wired local session. Pass this (with controller) to runMC
sessionIdstringIdentity of the eager local session
ownerIdstringOwner ID for the local session
storageStorageConfigThe resolved storage backend
memoryMemory | MemoryFactoryThe resolved memory instance or factory
observabilityobjectObservability handles
mcpManagerMCPManagerManager for MCP server connections
hookManagerHookManagerManager for lifecycle hooks
signalsPubSubPubSubPubSub used for signal routing
githubSignalsobjectGitHub PR signal handles
authStorageAuthStorageStorage for OAuth credentials
resolveModel(modelId: string, options?: { thinkingLevel?: ThinkingLevel; remapForCodexOAuth?: boolean; requestContext?: RequestContext }) => ResolvedModelModel resolution function
storageWarningstring | nullWarning message if storage fallback occurred
observabilityWarningstring | nullWarning message if observability setup fell back
builtinPacksModePack[]Built-in mode packs
builtinOmPacksOmPack[]Built-in Observational Memory packs
effectiveDefaultsobjectEffective default settings after merging
setActiveSession(session: Session<MastraCodeState>) => voidPublishes a session back into config closures

CreateMastraCodeOptions

OptionTypeDefaultDescription
cwdstringprocess.cwd()Working directory for project detection
homeDirstringos.homedir()Home directory for global config discovery
modesAgentControllerMode[]Build, Plan, FastOverride modes (model IDs, colors, which modes exist)
subagentsAgentControllerSubagent[]Explore, Plan, ExecuteOverride or extend subagent definitions
extraToolsRecord<string, Tool> | ((ctx) => Record<string, Tool>){}Extra tools merged into the dynamic tool set
disabledToolsstring[][]Tools removed from the dynamic tool set before exposure to the model
storageStorageConfigLocal LibSQLCustom storage config instead of auto-detected default
omScope'thread' | 'resource'Auto-detectedObservational Memory scope
settingsPathstringGlobal settingsPath to a custom settings.json file
initialStatePartial<MastraCodeState>Default stateInitial state overrides (yolo, thinkingLevel, etc.)
idGenerator() => stringDefaultOverride id generation for threads/messages (useful for deterministic tests)
intervalHandlersIntervalHandler[]gateway-syncOverride interval (background task) handlers
resolveModel(modelId: string, options?) => ResolvedModelDefault resolverCustom model resolution function
workspaceWorkspaceLocal FS + sandboxOverride the workspace
configDirstring.mastracodeOverride the config directory name
mcpServersRecord<string, McpServerConfig>{}Programmatic MCP server configs, merged with file-based configs
disableMcpbooleanfalseDisable MCP server discovery
disableHooksbooleanfalseDisable hooks
memoryMemory | MemoryFactory | falseBuilt-in gatewayOverride the memory instance or factory
browserBrowserProviderBrowser provider; when set the agent gains browser tools
pubsubPubSubPubSub for signal routing
unixSocketPubSubbooleanfalseUse the built-in Unix socket PubSub for local cross-process signal routing
crossProcessPubSubbooleanfalseMark the configured PubSub as cross-process-safe (skips file thread locks)

AgentControllerMode

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

AgentControllerSubagent

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
allowedControllerToolsstring[]NoTool IDs from controller tools this subagent can use
defaultModelIdstringNoDefault model for this subagent type
maxStepsnumberNoOptional maximum number of steps for the spawned subagent; defaults to 50
stopWhenLoopOptions['stopWhen']NoOptional stop condition for the spawned subagent loop

StorageConfig

Database connection configuration.

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

MastraCodeState

AgentController state fields available through initialState.

FieldTypeDefaultDescription
yolobooleanfalseAuto-approve all tool calls
thinkingLevel"off" | "low" | "medium" | "high" | "xhigh""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 {
  // 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.

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

OptionTypeRequiredDescription
controllerAgentControllerYesThe controller 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

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: {},
    },
  },
})