Skip to main content

Mastra class

The Mastra class is the central orchestrator in any Mastra application, managing agents, workflows, storage, logging, observability, and more. Typically, you create a single instance of Mastra to coordinate your application.

Think of Mastra as a top-level registry where you register agents, workflows, tools, and other components that need to be accessible throughout your application.

Usage example
Direct link to Usage example

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { PinoLogger } from '@mastra/loggers'
import { LibSQLStore } from '@mastra/libsql'
import { weatherWorkflow } from './workflows/weather-workflow'
import { weatherAgent } from './agents/weather-agent'

export const mastra = new Mastra({
workflows: { weatherWorkflow },
agents: { weatherAgent },
storage: new LibSQLStore({
id: 'mastra-storage',
url: ':memory:',
}),
logger: new PinoLogger({
name: 'Mastra',
level: 'info',
}),
})

Enable scheduled notification dispatch when deferred notification records and notification summaries should be delivered automatically through the workflow scheduler:

src/mastra/index.ts
export const mastra = new Mastra({
agents: { supportAgent },
storage,
notifications: {
dispatch: {
enabled: true,
cron: '*/1 * * * *',
batchSize: 100,
},
},
})

notifications.dispatch.enabled allows an internal dispatcher workflow to run with the default cron */1 * * * *. The dispatcher reads due notification records from storage, groups summaries by agentId, resourceId, and threadId, and emits signals through the agent thread runtime. It isn't a user-facing entrypoint. The dispatch schedule (and the workflow scheduler backing it) activates lazily on the first deferred or summarized notification, so apps that never defer notifications don't run a scheduler at all.

Constructor parameters
Direct link to Constructor parameters

Visit the Configuration reference for detailed documentation on all available configuration options.

agents?:

Record<string, Agent>
= {}
Agent instances to register, keyed by name

tools?:

Record<string, ToolApi>
= {}
Tool instances to register. Keys are registration keys used by `getTool()`, and values are tool instances. Use `getToolById()` for intrinsic ID lookup and `listTools()` to read the registry.

storage?:

MastraCompositeStore
Storage engine instance for persisting data

vectors?:

Record<string, MastraVector>
Vector store instance, used for semantic search and vector-based tools (eg Pinecone, PgVector or Qdrant)

logger?:

Logger
= Console logger with INFO level
Logger instance created with new PinoLogger()

idGenerator?:

(context?: IdGeneratorContext) => string
Custom ID generator function. Used by agents, workflows, memory, and other components to generate unique identifiers. Receives optional context such as idType, source, entityId, and threadId to support context-aware ID formats.

workflows?:

Record<string, Workflow>
= {}
Workflows to register. Structured as a key-value pair, with keys being the workflow name and values being the workflow instance.

tts?:

Record<string, MastraVoice>
Text-to-speech providers for voice synthesis

observability?:

ObservabilityEntrypoint
Observability configuration for tracing and monitoring

environment?:

string
Deployment environment name (e.g. production, staging, development). When set, automatically attached to all observability signals so they can be filtered by environment without passing tracingOptions.metadata.environment on each call. Falls back to process.env.NODE_ENV when unset; left undefined if neither is set. Per-call tracingOptions.metadata.environment always takes precedence.

deployer?:

MastraDeployer
An instance of a MastraDeployer for managing deployments.

server?:

ServerConfig
Server configuration including port, host, timeout, API routes, middleware, CORS settings, and build options for Swagger UI, API request logging, and OpenAPI docs.

mcpServers?:

Record<string, MCPServerBase>
An object where keys are registry keys (used for getMCPServer()) and values are instances of MCPServer or classes extending MCPServerBase. Each MCPServer must have an id property. Servers can be retrieved by registry key using getMCPServer() or by their intrinsic id using getMCPServerById().

bundler?:

BundlerConfig
= { externals: [], sourcemap: false, transpilePackages: [], dynamicPackages: [] }
Configuration for the asset bundler with options for externals, sourcemap, transpilePackages, and dynamicPackages.

scorers?:

Record<string, Scorer>
= {}
Scorers for evaluating agent responses and workflow outputs

processors?:

Record<string, Processor>
= {}
Input/output processors for transforming agent inputs and outputs

gateways?:

Record<string, MastraModelGateway>
= {}
Custom model gateways to register for accessing AI models through alternative providers or private deployments. Structured as a key-value pair, with keys being the registry key (used for getGateway()) and values being gateway instances.

memory?:

Record<string, MastraMemory>
= {}
Memory instances to register. These can be referenced by stored agents and resolved at runtime. Structured as a key-value pair, with keys being the registry key and values being memory instances.

notifications?:

object
Runtime configuration for notification signal dispatch.
object

dispatch?:

NotificationDispatchConfig
Scheduled dispatch configuration for deferred notifications and notification summaries. Dispatch is enabled by default.
object

enabled?:

boolean
Set to false to opt out of automatic scheduled notification dispatch.

cron?:

string
Cron schedule used by the internal notification dispatcher workflow.

batchSize?:

number
Maximum number of due notification records to process per dispatch run.

versions?:

VersionOverrides
Global version overrides for sub-agent delegation. When a supervisor agent delegates to a sub-agent, these overrides determine which stored version of that sub-agent to use instead of the code-defined default. Requires the editor package to be configured. See Editor versioning for details.
VersionOverrides

agents?:

Record<string, VersionSelector>
A map of agent IDs to their version selectors. Each selector can target a specific version by ID or by publication status.
VersionSelector

versionId?:

string
The ID of a specific version to use.

status?:

'draft' | 'published'
Select the latest version with this publication status.

workers?:

MastraWorker[] | false
Configure which workers run in this Mastra instance. When omitted, Mastra auto-creates default workers based on your PubSub and config. Pass false to disable all event processing (useful when running standalone workers separately). Pass a MastraWorker[] to add custom workers — they are merged with the auto-created defaults, and a custom worker with the same name as a default replaces it.

backgroundTasks?:

BackgroundTaskManagerConfig
Configure background task execution for agents. See background tasks configuration reference for all options.
BackgroundTaskManagerConfig

enabled?:

boolean
Enable background task dispatch.

globalConcurrency?:

number
Max concurrent tasks across all agents.

perAgentConcurrency?:

number
Max concurrent tasks per agent.

backpressure?:

'queue' | 'reject' | 'fallback-sync'
Behavior when concurrency limit is reached.

defaultTimeoutMs?:

number
Default task timeout in milliseconds.

defaultRetries?:

RetryConfig
Default retry configuration.

scheduler?:

object
Configure the scheduler worker for cron-driven workflow triggers. Auto-enables when any workflow declares a schedule. See Scheduled workflows.
object

enabled?:

boolean
Explicitly enable or disable the scheduler.

recovery?:

MastraRecoveryConfig
= { durableAgents: 'off' }
Boot-time recovery behavior for orphaned agent and workflow runs. See Crash recovery.
object

durableAgents?:

'auto' | 'off'
Set to 'auto' to automatically re-drive orphaned RUNNING durable agent runs on server boot. Recovery re-issues LLM calls and re-executes tool calls, so tools must be idempotent. See Crash recovery.

Methods
Direct link to Methods

recoverAllDurableAgents()
Direct link to recoveralldurableagents

Re-drives every orphaned running durable-agent run across all registered durable agents. Called automatically on boot when recovery.durableAgents is 'auto'. You can also call it directly for manual recovery or from a scheduled task.

Requires persistent storage. With an in-memory store, there's nothing to recover after a process restart.

const result = await mastra.recoverAllDurableAgents()
// { agents: 2, recovered: 3, succeeded: 3, failed: 0 }

Returns:

agents:

number
Number of durable agents scanned.

recovered:

number
Total number of runs that were re-driven.

succeeded:

number
Runs that restarted successfully.

failed:

number
Runs whose restart threw an error.
On this page