The Mastra Class
The Mastra
class is the central orchestrator in any Mastra application, managing agents, workflows, storage, logging, telemetry, and more. Typically, you create a single instance of Mastra
to coordinate your application.
Think of Mastra
as a top-level registry:
- Registering integrations makes them accessible to agents, workflows, and tools alike.
- tools aren’t registered on
Mastra
directly but are associated with agents and discovered automatically.
Importing
import { Mastra } from "@mastra/core";
Constructor
Creates a new Mastra
instance with the specified configuration.
constructor(config?: Config);
Initialization
The Mastra class is typically initialized in your src/mastra/index.ts
file:
src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { LibSQLStore } from "@mastra/libsql";
import { weatherAgent } from "./agents/weather-agent";
export const mastra = new Mastra({
agents: { weatherAgent },
storage: new LibSQLStore({
url: ":memory:",
}),
});
Configuration Object
The constructor accepts an optional Config
object to customize its behavior and integrate various Mastra components. All properties on the Config
object are optional.
Properties
agents?:
Agent[]
= []
Array of Agent instances to register
tools?:
Record<string, ToolApi>
= {}
Custom tools to register. Structured as a key-value pair, with keys being the tool name and values being the tool function.
storage?:
MastraStorage
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()
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, MastraTTS>
An object for registering Text-To-Speech services.
telemetry?:
OtelConfig
Configuration for OpenTelemetry integration.
deployer?:
MastraDeployer
An instance of a MastraDeployer for managing deployments.
server?:
ServerConfig
= { port: 4111, host: localhost, cors: { origin: '*', allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization', 'x-mastra-client-type'], exposeHeaders: ['Content-Length', 'X-Requested-With'], credentials: false } }
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 unique server identifiers and values are instances of MCPServer or classes extending MCPServerBase. This allows Mastra to be aware of and potentially manage these MCP servers.
bundler:
BundlerConfig
Configuration for the asset bundler.
Usage
Any of the below methods can be used with the Mastra class, for example:
example.ts
import { mastra } from "./mastra";
const agent = mastra.getAgent("weatherAgent");
const result = await agent.generate("What's the weather like in London?");
Methods
getAgent(name):
Agent
Returns an agent instance by id. Throws if agent not found.
getAgents():
Record<string, Agent>
Returns all registered agents as a key-value object.
getWorkflow(id, { serialized }):
Workflow
Returns a workflow instance by id. The serialized option (default: false) returns a simplified representation with just the name.
getWorkflows({ serialized }):
Record<string, Workflow>
Returns all registered workflows. The serialized option (default: false) returns simplified representations.
getVector(name):
MastraVector
Returns a vector store instance by name. Throws if not found.
getVectors():
Record<string, MastraVector>
Returns all registered vector stores as a key-value object.
getDeployer():
MastraDeployer | undefined
Returns the configured deployer instance, if any.
getStorage():
MastraStorage | undefined
Returns the configured storage instance.
getMemory():
MastraMemory | undefined
Returns the configured memory instance. Note: This is deprecated, memory should be added to agents directly.
getServer():
ServerConfig | undefined
Returns the server configuration including port, timeout, API routes, middleware, CORS settings, and build options.
setStorage(storage):
void
Sets the storage instance for the Mastra instance.
setLogger({ logger }):
void
Sets the logger for all components (agents, workflows, etc.).
setTelemetry(telemetry):
void
Sets the telemetry configuration for all components.
getLogger():
Logger
Gets the configured logger instance.
getTelemetry():
Telemetry | undefined
Gets the configured telemetry instance.
getLogsByRunId({ runId, transportId }):
Promise<any>
Retrieves logs for a specific run ID and transport ID.
getLogs(transportId):
Promise<any>
Retrieves all logs for a specific transport ID.
getMCPServers():
Record<string, MCPServerBase> | undefined
Retrieves all registered MCP server instances.
Error Handling
The Mastra class methods throw typed errors that can be caught:
example.ts
import { mastra } from "./mastra";
try {
const agent = mastra.getAgent("weatherAgent");
const result = await agent.generate("What's the weather like in London?");
} catch (error) {
if (error instanceof Error) {
console.log(error.message);
}
}