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
optionsMastraCodeConfigNoConfiguration 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

MastraCodeConfig​

OptionTypeDefaultDescription
cwdstringprocess.cwd()Working directory for project detection
homeDirstringos.homedir()Home directory for global config discovery
modesAgentControllerMode[] | falsebuild, plan, fast (displayed as Explore)Override modes (model IDs, colors, which modes exist). false runs every session as a single Build agent
subagentsAgentControllerSubagent[][]Subagent definitions to register. None are registered by default. Pass [...builtinSubagents] to enable Explore, Plan and Execute
extraToolsRecord<string, Tool> | ((ctx) => Record<string, Tool> | Promise<Record<string, Tool>>)—Extra tools merged into the dynamic tool set
postToolObserver(context: ToolAfterHookContext) => void | Promise<void>—Observes completed tool calls without replacing tools. Errors are logged without failing successful tool calls
inputProcessorsInputProcessor[] | ((ctx) => InputProcessor[] | Promise<InputProcessor[]>)—Processors prepended before Mastra Code's built-in input processors
outputProcessorsOutputProcessor[] | ((ctx) => OutputProcessor[] | Promise<OutputProcessor[]>)—Processors appended after Mastra Code's built-in output processors
disabledToolsstring[][]Tools removed from the dynamic tool set before exposure to the model
disableBuiltinToolsBuiltinToolId[][]Agent controller built-in tools (for example, submit_plan) removed from every session. Tool guidance skips disabled tools, and plan mode writes the plan file instead of calling submit_plan when it's disabled
storageStorageConfig | MastraCompositeStoreLocal LibSQLCustom storage config instead of auto-detected default, or a pre-built store
storageBackend'libsql' | 'pg'Inferred for LibSQL and PostgresBackend for an injected store. Inferred for LibSQLStore and PostgresStore; required for any other MastraCompositeStore
vectorMastraVectorDefault recall storePre-built vector store for recall search
knowledge{ key: string; instance: Knowledge }—Host-owned Knowledge instance registered on the mounted Mastra runtime
omScope'thread' | 'resource'Auto-detectedObservational Memory scope. 'resource' is deprecated
settingsPathstringGlobal settingsPath to a custom settings.json file
initialStatePartial<MastraCodeState>Default stateInitial state overrides (yolo, thinkingLevel, etc.)
resolveDefaultThinkingLevel(ctx) => ThinkingLevelSetting | Promise<ThinkingLevelSetting>Settings defaultsHost-owned thinking default applied when a request has no level
createInitialThreadbooleantrueCreate a thread during local boot when no existing thread matches
hostInstructionsstring | ((ctx) => string | undefined | Promise<string | undefined>)—Trusted host instructions resolved outside mutable session state
coAuthor{ name?: string; email?: string }Core defaultsCommit co-author identity used in coding-agent commit guidance
idGenerator() => stringDefaultOverride id generation for threads/messages (useful for deterministic tests)
intervalHandlersIntervalHandler[]gateway-syncOverride interval (background task) handlers
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
disableEnvFilebooleanfalseSkip loading cwd/.env into the process environment
disablePluginsbooleanfalseDisable plugin discovery and loading
disableGithubSignalsbooleanfalseDisable the polling GitHub signal provider even when enabled in global settings
disableSettingsOmSeedbooleanfalseSkip seeding observational memory settings from settings.json
pluginManagerPluginManagerBuilt-in managerOverride the plugin manager
memoryMemory | MemoryFactory | falseBuilt-in gatewayOverride the memory instance or factory
browserBrowserProvider—Browser provider; when set the agent gains browser tools
pubsubPubSub—PubSub 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)
agentConnectionsAgentConnectionsSignalProviderOptions—Agent connection state and discovery options
crossAgentSignalsbooleanGlobal setting (off)Enable experimental cross-agent communication
scheduleToolsbooleanGlobal setting (off)Enable the experimental schedule tools
prepareWakeRequestContext(args) => void | Promise<void>—Prepare request context before a wake runs on an idle thread
resumeWakeSession(args) => Promise<void>—Bring the session that owns a resource online for a deferred notification

AgentControllerMode​

Each mode defines a display configuration and optional tool and instruction overrides. All modes share the backing agent.

PropertyTypeRequiredDescription
idstringYesUnique identifier (e.g., "build", "plan")
namestringNoDisplay name shown in the TUI
defaultModelIdstringNoModel for sessions that start in this mode and fallback for subagents. Mode switches do not apply it
descriptionstringNoDescription shown in mode pickers and Studio
instructionsstringNoInstructions layered above the backing agent's instructions
availableToolsstring[]NoTool allowlist for this mode. undefined allows all tools; [] hides all tools
transitionsTostringNoMode to switch to when a submitted plan is approved
metadataRecord<string, unknown>NoUser-defined metadata. metadata.color sets the TUI indicator color and metadata.default: true marks the startup mode
agentAgentNoDeprecated. Use the shared backing agent

AgentControllerSubagent​

Subagent definitions for spawning focused child agents.

PropertyTypeRequiredDescription
idstringYesUnique identifier (e.g., "explore")
namestringYesDisplay name in tool output
descriptionstringYesWhat this subagent does
instructionsDynamicArgument<AgentInstructions>YesSystem prompt for the subagent. Accepts a string, array of strings, system message object, array of system messages, or a function that returns any of these (or a promise of one)
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 unless stopWhen is set
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. OMModel accepts "auto" or a concrete model ID.

FieldTypeDefaultDescription
yolobooleantrueAuto-approve all tool calls. A saved preference overrides this default
thinkingLevel"off" | "low" | "medium" | "high" | "xhigh" | "max""off"Extended thinking depth
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—Legacy concrete model for the observational memory observer
reflectorModelIdstring—Legacy concrete model for the observational memory reflector
observerModelSelectionOMModel"auto"Automatic or explicit observer model selection
reflectorModelSelectionOMModel"auto"Automatic or explicit reflector model selection
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() => void | Promise<void>YesSync or 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, session, mcpManager, hookManager, authStorage } = await createMastraCode()

const tui = new MastraTUI({
  controller,
  session,
  hookManager,
  authStorage,
  mcpManager,
  appName: 'My Agent',
  version: '1.0.0',
})

tui.run()

MastraTUIOptions​

OptionTypeRequiredDescription
controllerAgentControllerYesThe controller instance
sessionSessionYesThe session created from the controller
hookManagerHookManagerNoHook manager from createMastraCode()
authStorageAuthStorageNoAuth storage from createMastraCode()
mcpManagerMCPManagerNoMCP 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' && event.event.type === 'text-delta') {
    process.stdout.write(event.event.delta)
  }
})

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