Overview
The Mastra class serves as the main entry point and registry for all components in a Mastra application. It coordinates the interaction between agents, workflows, storage systems, and other services.
Constructor
Configuration object for initializing a Mastra instance agents
Record<string, Agent | ToolLoopAgent>
Agents are autonomous systems that can make decisions and take actions. Accepts both Mastra Agent instances and AI SDK v6 ToolLoopAgent instances.
Storage provider for persisting data, conversation history, and workflow state. Required for agent memory and workflow persistence.
vectors
Record<string, MastraVector>
Vector stores for semantic search and retrieval-augmented generation (RAG). Used for storing and querying embeddings.
Logger implementation for application logging and debugging. Set to false to disable logging entirely. Defaults to INFO level in development, WARN in production.
Workflows provide type-safe, composable task execution with built-in error handling.
tts
Record<string, MastraTTS>
Text-to-speech providers for voice synthesis capabilities.
Observability entrypoint for tracking model interactions and tracing. Pass an instance of the Observability class from @mastra/observability.
Custom ID generator function for creating unique identifiers. Defaults to crypto.randomUUID().
Deployment provider for publishing applications to cloud platforms.
Server configuration for HTTP endpoints and middleware.
mcpServers
Record<string, MCPServerBase>
MCP servers provide tools and resources that agents can use.
Bundler configuration for packaging and deployment.
Pub/sub system for event-driven communication between components. Defaults to EventEmitterPubSub.
scorers
Record<string, MastraScorer>
Scorers help assess the quality of agent responses and workflow outputs.
tools
Record<string, ToolAction>
Tools are reusable functions that agents can use to interact with external systems.
processors
Record<string, Processor>
Processors transform inputs and outputs for agents and workflows.
memory
Record<string, MastraMemory>
Memory instances that can be referenced by stored agents. Keys are used to look up memory instances when resolving stored agent configurations.
Global workspace for file storage, skills, and code execution. Agents inherit this workspace unless they have their own configured.
gateways
Record<string, MastraModelGateway>
Custom model router gateways for accessing LLM providers. Gateways handle provider-specific authentication, URL construction, and model resolution.
events
Record<string, EventHandler>
Event handlers for custom application events. Maps event topics to handler functions for event-driven architectures.
Editor instance for handling agent instantiation and configuration. The editor handles complex instantiation logic including memory resolution.
Methods
Agent Management
getAgent
getAgent < TAgentName extends keyof TAgents >( name : TAgentName ) : TAgents [ TAgentName ]
Retrieves a registered agent by its name.
The name of the agent to retrieve
The requested agent instance
getAgentById
getAgentById < TAgentName extends keyof TAgents >( id : string ) : TAgents [ TAgentName ]
Retrieves a registered agent by its unique ID.
The unique ID of the agent
The requested agent instance
listAgents
Returns all registered agents as a record keyed by their names.
addAgent
addAgent < A extends Agent | ToolLoopAgentLike > (
agent : A ,
key ?: string ,
options ?: { source? : 'code' | 'stored' }
): void
Adds a new agent to the Mastra instance dynamically.
agent
Agent | ToolLoopAgent
required
The agent instance to add
Optional custom key for the agent. Defaults to agent.id
removeAgent
removeAgent ( keyOrId : string ): boolean
Removes an agent from the Mastra instance by its key or ID.
The agent key or ID to remove
true if an agent was removed, false if no agent was found
Vector Store Management
getVector
getVector < TVectorName extends keyof TVectors >( name : TVectorName ) : TVectors [ TVectorName ]
Retrieves a registered vector store by its name.
The name of the vector store
The requested vector store instance
getVectorById
getVectorById < TVectorName extends keyof TVectors >( id : string ) : TVectors [ TVectorName ]
Retrieves a vector store instance by its ID.
The unique ID of the vector store
The requested vector store instance
listVectors
listVectors (): TVectors | undefined
Returns all registered vector stores.
vectors
Record<string, MastraVector> | undefined
All registered vector stores
addVector
addVector < V extends MastraVector >( vector : V , key ?: string ) : void
Adds a new vector store to the Mastra instance.
The vector store instance to add
Optional custom key for the vector store. Defaults to vector.id
Workflow Management
getWorkflow
getWorkflow < TWorkflowId extends keyof TWorkflows > (
id : TWorkflowId ,
options ?: { serialized? : boolean }
): TWorkflows [ TWorkflowId ]
Retrieves a registered workflow by its ID.
If true, returns a minimal serialized version with just the name
The requested workflow instance
getWorkflowById
getWorkflowById < TWorkflowName extends keyof TWorkflows >( id : string ) : TWorkflows [ TWorkflowName ]
Retrieves a workflow by its unique ID.
The requested workflow instance
listActiveWorkflowRuns
listActiveWorkflowRuns (): Promise < WorkflowRuns >
Returns all currently active workflow runs (running or waiting status).
Object containing runs array and total count
restartAllActiveWorkflowRuns
restartAllActiveWorkflowRuns (): Promise < void >
Restarts all active workflow runs.
Storage
getStorage
getStorage (): MastraCompositeStore | undefined
Returns the configured storage instance.
storage
MastraCompositeStore | undefined
The storage instance, or undefined if not configured
Workspace Management
getWorkspace
getWorkspace (): Workspace | undefined
Gets the global workspace instance.
The global workspace, or undefined if not configured
getWorkspaceById
getWorkspaceById ( id : string ): Workspace
Retrieves a registered workspace by its ID.
The requested workspace instance
listWorkspaces
listWorkspaces (): Record < string , RegisteredWorkspace >
Returns all registered workspaces.
workspaces
Record<string, RegisteredWorkspace>
All registered workspaces keyed by their IDs
addWorkspace
addWorkspace (
workspace : Workspace ,
key ?: string ,
metadata ?: { source? : 'mastra' | 'agent' ; agentId ?: string ; agentName ?: string }
): void
Adds a new workspace to the Mastra instance.
The workspace instance to add
Optional custom key for the workspace. Defaults to workspace.id
Metadata about the workspace source
Scorer Management
listScorers
listScorers (): TScorers | undefined
Returns all registered scorers.
scorers
Record<string, MastraScorer> | undefined
All registered scorers
addScorer
addScorer < S extends MastraScorer > (
scorer : S ,
key ?: string ,
options ?: { source? : 'code' | 'stored' }
): void
Adds a new scorer to the Mastra instance.
The scorer instance to add
Optional custom key for the scorer. Defaults to scorer.id
ID Generation
generateId
generateId ( context ?: IdGeneratorContext ): string
Generates a unique identifier using the configured generator or defaults to crypto.randomUUID().
Optional context information about what type of ID is being generated
setIdGenerator
setIdGenerator ( idGenerator : MastraIdGenerator ): void
Sets a custom ID generator function.
idGenerator
MastraIdGenerator
required
Function that generates unique IDs
getIdGenerator
getIdGenerator (): MastraIdGenerator | undefined
Gets the currently configured ID generator function.
generator
MastraIdGenerator | undefined
The ID generator function, or undefined if using default
Other Getters
getDeployer
getDeployer (): MastraDeployer | undefined
Gets the currently configured deployment provider.
deployer
MastraDeployer | undefined
The deployment provider, or undefined if not configured
getEditor
getEditor (): IMastraEditor | undefined
Gets the currently configured editor instance.
editor
IMastraEditor | undefined
The editor instance, or undefined if not configured
getLogger
Gets the configured logger instance.
Properties
The pub/sub instance for event-driven communication
The datasets manager for handling evaluation datasets
Example
import { Mastra } from '@mastra/core' ;
import { Agent } from '@mastra/core/agent' ;
import { LibSQLStore } from '@mastra/libsql' ;
import { PinoLogger } from '@mastra/pino' ;
import { Observability , DefaultExporter } from '@mastra/observability' ;
const mastra = new Mastra ({
agents: {
weatherAgent: new Agent ({
id: 'weather-agent' ,
name: 'Weather Agent' ,
instructions: 'You provide weather information' ,
model: 'openai/gpt-5' ,
tools: { getWeather }
})
},
storage: new LibSQLStore ({ id: 'mastra-storage' , url: ':memory:' }),
logger: new PinoLogger ({ name: 'MyApp' }),
observability: new Observability ({
configs: {
default: {
serviceName: 'mastra' ,
exporters: [ new DefaultExporter ()]
}
}
})
});
// Get and use an agent
const agent = mastra . getAgent ( 'weatherAgent' );
const response = await agent . generate ( 'What is the weather?' );