PageSourceSearch

https://mastra.ai/assets/js/ddde1626.eded4d98.js

js mastra.ai collected 2026-10-02 02:43:07 UTC 16,822 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunkmastra_docs=self.webpackChunkmastra_docs||[]).push([["2256"],{88450(e,t,r){r.r(t),r.d(t,{metadata:()=>a,default:()=>p,frontMatter:()=>o,contentTitle:()=>i,toc:()=>l,assets:()=>c});var a=JSON.parse('{"id":"core/mastra-class","title":"Reference: Mastra class | Core","description":"The Mastra class is the central orchestrator in any Mastra application, managing agents, workflows, storage, logging, observability, and more.","source":"@site/src/content/en/reference/core/mastra-class.mdx","sourceDirName":"core","slug":"/core/mastra-class","permalink":"/reference/core/mastra-class","draft":false,"unlisted":false,"editUrl":"https://github.com/mastra-ai/mastra/tree/main/docs/src/content/en/reference/core/mastra-class.mdx","tags":[],"version":"current","frontMatter":{"title":"Reference: Mastra class | Core","description":"The Mastra class is the central orchestrator in any Mastra application, managing agents, workflows, storage, logging, observability, and more.","packages":["@mastra/core","@mastra/libsql","@mastra/loggers"]},"sidebar":"referenceSidebar","previous":{"title":"createCodingAgent()","permalink":"/reference/coding-agent/create-coding-agent"},"next":{"title":"MastraModelGateway","permalink":"/reference/core/mastra-model-gateway"}}'),s=r(74848),n=r(28453);let o={title:"Reference: Mastra class | Core",description:"The Mastra class is the central orchestrator in any Mastra application, managing agents, workflows, storage, logging, observability, and more.",packages:["@mastra/core","@mastra/libsql","@mastra/loggers"]},i="Mastra class",c={},l=[{value:"Usage example",id:"usage-example",level:2},{value:"Constructor parameters",id:"constructor-parameters",level:2},{value:"Methods",id:"methods",level:2},{value:"<code>recoverAllDurableAgents()</code>",id:"recoveralldurableagents",level:3}];function d(e){let t={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",p:"p",pre:"pre",...(0,n.R)(),...e.components},{PropertiesTable:r}=t;return r||function(e,t){throw Error("Expected "+(t?"component":"object")+" `"+e+"` to be defined: you likely forgot to import, pass, or provide it.")}("PropertiesTable",!0),(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(t.header,{children:(0,s.jsx)(t.h1,{id:"mastra-class",children:"Mastra class"})}),"\n",(0,s.jsxs)(t.p,{children:["The ",(0,s.jsx)(t.code,{children:"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 ",(0,s.jsx)(t.code,{children:"Mastra"})," to coordinate your application."]}),"\n",(0,s.jsxs)(t.p,{children:[(0,s.jsx)(t.code,{children:"Mastra"})," is the top-level registry where you register agents, workflows, tools, and other components that need to be accessible throughout your application."]}),"\n",(0,s.jsx)(t.h2,{id:"usage-example",children:"Usage example"}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-typescript",metastring:'title="src/mastra/index.ts"',children:"import { Mastra } from '@mastra/core'\nimport { PinoLogger } from '@mastra/loggers'\nimport { LibSQLStore } from '@mastra/libsql'\nimport { weatherWorkflow } from './workflows/weather-workflow'\nimport { weatherAgent } from './agents/weather-agent'\n\nexport const mastra = new Mastra({\n  workflows: { weatherWorkflow },\n  agents: { weatherAgent },\n  storage: new LibSQLStore({\n    id: 'mastra-storage',\n    url: ':memory:',\n  }),\n  logger: new PinoLogger({\n    name: 'Mastra',\n    level: 'info',\n  }),\n})\n"})}),"\n",(0,s.jsx)(t.p,{children:"Enable scheduled notification dispatch when deferred notification records and notification summaries should be delivered automatically through the workflow scheduler:"}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-typescript",metastring:'title="src/mastra/index.ts"',children:"export const mastra = new Mastra({\n  agents: { supportAgent },\n  storage,\n  notifications: {\n    dispatch: {\n      enabled: true,\n      cron: '*/1 * * * *',\n      batchSize: 100,\n    },\n  },\n})\n"})}),"\n",(0,s.jsxs)(t.p,{children:[(0,s.jsx)(t.code,{children:"notifications.dispatch.enabled"})," allows an internal dispatcher workflow to run with the default cron ",(0,s.jsx)(t.code,{children:"*/1 * * * *"}),". The dispatcher reads due notification records from storage, groups summaries by ",(0,s.jsx)(t.code,{children:"agentId"}),", ",(0,s.jsx)(t.code,{children:"resourceId"}),", and ",(0,s.jsx)(t.code,{children:"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."]}),"\n",(0,s.jsx)(t.h2,{id:"constructor-parameters",children:"Constructor parameters"}),"\n",(0,s.jsxs)(t.p,{children:["Visit the ",(0,s.jsx)(t.a,{href:"/reference/configuration",children:"Configuration reference"})," for detailed documentation on all available configuration options."]}),"\n",(0,s.jsx)(r,{content:[{name:"agents",type:"Record<string, Agent>",description:"Agent instances to register, keyed by name",isOptional:!0,defaultValue:"{}"},{name:"tools",type:"Record<string, ToolApi>",description:"Tool instances to register. Keys are registration keys used by [`getTool()`](/reference/core/getTool), and values are tool instances. Use [`getToolById()`](/reference/core/getToolById) for intrinsic ID lookup and [`listTools()`](/reference/core/listTools) to read the registry.",isOptional:!0,defaultValue:"{}"},{name:"storage",type:"MastraCompositeStore",description:"Storage engine instance for persisting data",isOptional:!0},{name:"vectors",type:"Record<string, MastraVector>
1",description:"Vector store instance, used for semantic search and vector-based tools (eg Pinecone, PgVector or Qdrant)",isOptional:!0},{name:"logger",type:"Logger",description:"Logger instance created with new PinoLogger()",isOptional:!0,defaultValue:"Console logger with INFO level"},{name:"loggerOptions",type:"{ correlation?: boolean; export?: boolean }",description:"Controls logger observability behavior. `correlation` injects trace_id/span_id into native log output during traced operations; `export` forwards log records to observability storage.",isOptional:!0,defaultValue:"{ correlation: true, export: true }"},{name:"idGenerator",type:"(context?: IdGeneratorContext) => string",description:"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.",isOptional:!0},{name:"workflows",type:"Record<string, Workflow>",description:"Workflows to register. Structured as a key-value pair, with keys being the workflow name and values being the workflow instance.",isOptional:!0,defaultValue:"{}"},{name:"tts",type:"Record<string, MastraVoice>",isOptional:!0,description:"Text-to-speech providers for voice synthesis"},{name:"observability",type:"ObservabilityEntrypoint",isOptional:!0,description:"Observability configuration for tracing and monitoring"},{name:"environment",type:"string",isOptional:!0,description:"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. When unset, resolves to `development` for `mastra dev` runs, then falls back to `process.env.NODE_ENV`; left undefined if none are set. Per-call `tracingOptions.metadata.environment` always takes precedence."},{name:"deployer",type:"MastraDeployer",isOptional:!0,description:"An instance of a MastraDeployer for managing deployments."},{name:"server",type:"ServerConfig",description:"Server configuration including port, host, timeout, API routes, middleware, CORS settings, and build options for Swagger UI, API request logging, and OpenAPI docs.",isOptional:!0},{name:"mcpServers",type:"Record<string, MCPServerBase>",isOptional:!0,description:"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()."},{name:"bundler",type:"BundlerConfig",description:"Configuration for the asset bundler with options for externals, sourcemap, transpilePackages, and dynamicPackages.",isOptional:!0,defaultValue:"{ externals: [], sourcemap: false, transpilePackages: [], dynamicPackages: [] }"},{name:"scorers",type:"Record<string, Scorer>",description:"Scorers for evaluating agent responses and workflow outputs. Registration also makes a scorer resolvable by ID, which is required to persist its scores. See [Score persistence](/docs/evals/overview#score-persistence)",isOptional:!0,defaultValue:"{}"},{name:"classifiers",type:"Record<string, Classifier>",description:"Classifiers for typed fixed-option evaluation. Registered classifiers can be retrieved by key or ID. See [Classifier](/reference/classifier/classifier)",isOptional:!0,defaultValue:"{}"},{name:"processors",type:"Record<string, Processor>",description:"Input/output processors for transforming agent inputs and outputs",isOptional:!0,defaultValue:"{}"},{name:"gateways",type:"Record<string, MastraModelGateway>",description:"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.",isOptional:!0,defaultValue:"{}"},{name:"memory",type:"Record<string, MastraMemory>
1",description:"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.",isOptional:!0,defaultValue:"{}"},{name:"notifications",type:"object",description:"Runtime configuration for notification signal dispatch.",isOptional:!0,properties:[{type:"object",parameters:[{name:"dispatch",type:"NotificationDispatchConfig",isOptional:!0,description:"Scheduled dispatch configuration for deferred notifications and notification summaries. Dispatch is enabled by default.",properties:[{type:"object",parameters:[{name:"enabled",type:"boolean",isOptional:!0,defaultValue:"true",description:"Set to `false` to opt out of automatic scheduled notification dispatch."},{name:"cron",type:"string",isOptional:!0,defaultValue:"`*/1 * * * *`",description:"Cron schedule used by the internal notification dispatcher workflow."},{name:"batchSize",type:"number",isOptional:!0,defaultValue:"100",description:"Maximum number of due notification records to process per dispatch run."}]}]}]}]},{name:"versions",type:"VersionOverrides",description:"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](/docs/studio/editor#versioning) for details.",isOptional:!0,properties:[{type:"VersionOverrides",parameters:[{name:"agents",type:"Record<string, VersionSelector>",isOptional:!0,description:"A map of agent IDs to their version selectors. Each selector can target a specific version by ID or by publication status.",properties:[{type:"VersionSelector",parameters:[{name:"versionId",type:"string",isOptional:!0,description:"The ID of a specific version to use."}]},{parameters:[{name:"status",type:"'draft' | 'published'",isOptional:!0,description:"Select the latest version with this publication status."}]}]}]}]},{name:"workers",type:"MastraWorker[] | false",description:"Configure which [workers](/docs/deployment/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 \u2014 they are merged with the auto-created defaults, and a custom worker with the same `name` as a default replaces it.",isOptional:!0},{name:"backgroundTasks",type:"BackgroundTaskManagerConfig",description:"Configure [background task](/docs/harness/background-tasks) execution for agents. See [background tasks configuration reference](/reference/configuration#backgroundtasks) for all options.",isOptional:!0,properties:[{type:"BackgroundTaskManagerConfig",parameters:[{name:"enabled",type:"boolean",isOptional:!0,defaultValue:"false",description:"Enable background task dispatch."},{name:"globalConcurrency",type:"number",isOptional:!0,defaultValue:"10",description:"Max concurrent tasks across all agents."},{name:"perAgentConcurrency",type:"number",isOptional:!0,defaultValue:"5",description:"Max concurrent tasks per agent."},{name:"backpressure",type:"'queue' | 'reject' | 'fallback-sync'",isOptional:!0,defaultValue:"'queue'",description:"Behavior when concurrency limit is reached."},{name:"defaultTimeoutMs",type:"number",isOptional:!0,defaultValue:"300000",description:"Default task timeout in milliseconds."},{name:"defaultRetries",type:"RetryConfig",isOptional:!0,description:"Default retry configuration."}]}]},{name:"scheduler",type:"object",description:"Configure the [scheduler worker](/docs/deployment/workers#scheduler-worker) for cron-driven workflow triggers. Auto-enables when any workflow declares a `schedule`, when schedule rows already exist in storage, or when a schedule is created at runtime. Apps that never schedule anything run one `listSchedules()` check at boot and never poll after that. See [Scheduled workflows](/docs/workflows/scheduled-workflows).",isOptional:!0,properties:[{type:"object",parameters:[{name:"enabled",type:"boolean",isOptional:!0,description:"Explicitly enable or disable the scheduler."}]}]},{name:"recovery",type:"MastraRecoveryConfig",description:"Boot-time recovery behavior for orphaned agent and workflow runs. See [Crash recovery](/docs/harness/durable-agents#crash-recovery).",isOptional:!0,defaultValue:"{ durableAgents: 'off' }",properties:[{type:"object",parameters:[{name:"durableAgents",type:"'auto' | 'off'",isOptional:!0,defaultValue:"'off'",description:"Set to `'auto'` to automatically re-drive orphaned RUNNING durable agent runs on server boot. This also controls the default snapshot-persistence policy for durable agents: `running` checkpoints are only written when set to `'auto'` (
1or when an agent sets a custom `shouldPersistSnapshot` that includes `running`). Recovery re-issues LLM calls and re-executes tool calls, so tools must be idempotent. See [Crash recovery](/docs/harness/durable-agents#crash-recovery)."}]}]}]}),"\n",(0,s.jsx)(t.h2,{id:"methods",children:"Methods"}),"\n",(0,s.jsx)(t.h3,{id:"recoveralldurableagents",children:(0,s.jsx)(t.code,{children:"recoverAllDurableAgents()"})}),"\n",(0,s.jsxs)(t.p,{children:["Re-drives every orphaned ",(0,s.jsx)(t.code,{children:"running"})," durable-agent run across all registered durable agents. Called automatically on boot when ",(0,s.jsx)(t.code,{children:"recovery.durableAgents"})," is ",(0,s.jsx)(t.code,{children:"'auto'"}),". You can also call it directly for manual recovery or from a scheduled task."]}),"\n",(0,s.jsx)(t.p,{children:"Requires persistent storage. With an in-memory store, there's nothing to recover after a process restart."}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-typescript",children:"const result = await mastra.recoverAllDurableAgents()\n// { agents: 2, recovered: 3, succeeded: 3, failed: 0 }\n"})}),"\n",(0,s.jsx)(t.p,{children:"Returns:"}),"\n",(0,s.jsx)(r,{content:[{name:"agents",type:"number",description:"Number of durable agents scanned."},{name:"recovered",type:"number",description:"Total number of runs that were re-driven."},{name:"succeeded",type:"number",description:"Runs that restarted successfully."},{name:"failed",type:"number",description:"Runs whose restart threw an error."}]})]})}function p(e={}){let{wrapper:t}={...(0,n.R)(),...e.components};return t?(0,s.jsx)(t,{...e,children:(0,s.jsx)(d,{...e})}):d(e)}},28453(e,t,r){r.d(t,{R:()=>o,x:()=>i});var a=r(96540);let s={},n=a.createContext(s);function o(e){let t=a.useContext(n);return a.useMemo(function(){return"function"==typeof e?e(t):{...t,...e}},[t,e])}function i(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:o(e.components),a.createElement(n.Provider,{value:t},e.children)}}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.