Documentation Index Fetch the complete documentation index at: https://mintlify.com/mastra-ai/mastra/llms.txt
Use this file to discover all available pages before exploring further.
The Mastra class is the main entry point and orchestrator for all components in a Mastra application. It provides a centralized configuration hub with dependency injection, managing agents, workflows, storage, logging, and more.
Core Concept
Mastra follows a dependency injection pattern where components register with the central Mastra instance to access shared resources:
Centralized Configuration : All components configured in one place
Dependency Injection : Components automatically receive access to storage, logging, observability
Plugin Architecture : Swap implementations without changing application code
Type Safety : Full TypeScript support with generic type parameters
Basic Example
import { Mastra } from '@mastra/core' ;
import { Agent } from '@mastra/core/agent' ;
import { PostgresStore } from '@mastra/postgres' ;
import { PinoLogger } from '@mastra/pino' ;
const mastra = new Mastra ({
agents: {
assistant: new Agent ({
id: 'assistant' ,
name: 'Assistant' ,
instructions: 'You are a helpful assistant' ,
model: 'openai/gpt-5'
})
},
storage: new PostgresStore ({
connectionString: process . env . DATABASE_URL
}),
logger: new PinoLogger ({ name: 'MyApp' })
});
Configuration Interface
The Config interface defines all optional components that can be registered:
interface Config < TAgents , TWorkflows , TVectors , ...> {
// Core Components
agents ?: Record < string , Agent >; // AI agents with tools & memory
workflows ?: Record < string , AnyWorkflow >; // Step-based execution flows
storage ?: MastraCompositeStore ; // Persistence backend
// AI Infrastructure
vectors ?: Record < string , MastraVector >; // Vector stores for RAG
memory ?: Record < string , MastraMemory >; // Memory instances
gateways ?: Record < string , MastraModelGateway >; // Custom LLM providers
// Tools & Utilities
tools ?: Record < string , ToolAction >; // Reusable tools
processors ?: Record < string , Processor >; // Input/output transformers
scorers ?: Record < string , MastraScorer >; // Quality assessment
// Infrastructure
logger ?: IMastraLogger | false ; // Logging implementation
observability ?: ObservabilityEntrypoint ; // Tracing & metrics
pubsub ?: PubSub ; // Event system
// Advanced
mcpServers ?: Record < string , MCPServerBase >; // MCP tool providers
workspace ?: AnyWorkspace ; // Global workspace
deployer ?: MastraDeployer ; // Cloud deployment
server ?: ServerConfig ; // HTTP server config
idGenerator ?: MastraIdGenerator ; // Custom ID generation
}
Dependency Injection Flow
When components are registered with Mastra, they automatically gain access to shared resources:
// 1. Create Mastra instance with storage
const mastra = new Mastra ({
storage: new PostgresStore ({ url: process . env . DATABASE_URL }),
logger: new PinoLogger ({ name: 'app' })
});
// 2. Agents registered later receive storage & logger automatically
mastra . addAgent ( new Agent ({
id: 'chat-agent' ,
name: 'Chat Agent' ,
model: 'openai/gpt-5' ,
memory: new Memory () // Memory will inherit Mastra's storage
}));
// 3. The agent's memory now has access to storage
const agent = mastra . getAgent ( 'chat-agent' );
const memory = await agent . getMemory ();
// memory.storage === mastra.getStorage() ✓
Component Registry Methods
Agents
Agents are autonomous systems that can make decisions and take actions:
// Add agents
mastra . addAgent ( weatherAgent , 'weather' );
// Retrieve by name
const agent = mastra . getAgent ( 'weather' );
// Retrieve by ID
const sameAgent = mastra . getAgentById ( weatherAgent . id );
// List all agents
const allAgents = mastra . listAgents ();
See Agents for more details.
Workflows
Workflows provide type-safe, composable task execution:
// Register workflow
mastra . addWorkflow ( dataWorkflow , 'processor' );
// Retrieve workflow
const workflow = mastra . getWorkflow ( 'processor' );
// Execute workflow
const run = await workflow . createRun ({
inputData: { input: 'process this' }
});
const result = await run . start ();
See Workflows for more details.
Storage
Storage persists conversation history, workflow state, and application data:
const mastra = new Mastra ({
storage: new PostgresStore ({
connectionString: process . env . DATABASE_URL
})
});
const storage = mastra . getStorage ();
// Storage is automatically injected into agents and memory
const agent = new Agent ({
id: 'assistant' ,
memory: new Memory () // Inherits Mastra's storage
});
Vector Stores
Vector stores enable semantic search and RAG:
const mastra = new Mastra ({
vectors: {
knowledge: new PineconeVector ({
apiKey: process . env . PINECONE_API_KEY ,
indexName: 'knowledge-base'
})
}
});
const vectorStore = mastra . getVector ( 'knowledge' );
const results = await vectorStore . query ({
query: 'How to reset password?' ,
topK: 5
});
Tools extend agent capabilities with reusable functions:
const mastra = new Mastra ({
tools: {
weather: createTool ({
id: 'get-weather' ,
description: 'Get weather for location' ,
execute : async ({ location }) => {
return await fetchWeather ( location );
}
})
}
});
const tool = mastra . getTool ( 'weather' );
See Tools for more details.
Memory
Memory instances manage conversation persistence:
const mastra = new Mastra ({
memory: {
default: new Memory ({
name: 'default' ,
options: { lastMessages: 20 }
})
}
});
const memory = mastra . getMemory ( 'default' );
See Memory for more details.
Logging
Mastra supports pluggable logging implementations:
import { PinoLogger } from '@mastra/pino' ;
import { ConsoleLogger , LogLevel } from '@mastra/core/logger' ;
// Use Pino logger
const mastra = new Mastra ({
logger: new PinoLogger ({ name: 'MyApp' , level: 'info' })
});
// Use console logger
const mastra2 = new Mastra ({
logger: new ConsoleLogger ({ name: 'Dev' , level: LogLevel . DEBUG })
});
// Disable logging
const mastra3 = new Mastra ({
logger: false
});
// Access logger
const logger = mastra . getLogger ();
logger . info ( 'Application started' );
Default behavior:
Development: INFO level
Production: WARN level
Observability
Track LLM interactions and application traces:
import { Observability , DefaultExporter } from '@mastra/observability' ;
const mastra = new Mastra ({
observability: new Observability ({
configs: {
default: {
serviceName: 'mastra' ,
exporters: [ new DefaultExporter ()]
}
}
})
});
Custom ID Generation
Override default UUID generation:
const mastra = new Mastra ({
idGenerator : ( context ) => {
// Deterministic IDs based on context
if ( context ?. threadId ) {
return `msg- ${ context . threadId } - ${ Date . now () } ` ;
}
return `custom- ${ Date . now () } ` ;
}
});
const id = mastra . generateId ();
console . log ( id ); // "custom-1234567890"
const msgId = mastra . generateId ({
idType: 'message' ,
threadId: 'thread-123'
});
console . log ( msgId ); // "msg-thread-123-1234567890"
Event System
Mastra includes a pub/sub system for event-driven communication:
const mastra = new Mastra ({
events: {
'user.created' : async ( event ) => {
console . log ( 'New user:' , event . data );
}
}
});
const pubsub = mastra . pubsub ;
await pubsub . publish ( 'user.created' , { id: 'user-123' });
Working with Stored Agents
Mastra automatically manages stored agents from the database:
// Stored agents are loaded and cached automatically
const storedAgent = await mastra . getAgentById ( 'stored-agent-id' );
// Changes to stored agents are reflected in the cache
mastra . removeAgent ( 'stored-agent-id' ); // Clear cache
Best Practices
Configure storage in the Mastra constructor so all components can access it: const mastra = new Mastra ({
storage: new PostgresStore ({ url: process . env . DATABASE_URL }),
agents: {
assistant: new Agent ({
memory: new Memory () // Inherits storage
})
}
});
Let Mastra inject dependencies instead of passing them manually: // Good: Mastra handles dependency injection
const mastra = new Mastra ({ storage , logger });
mastra . addAgent ( agent );
// Avoid: Manual dependency passing
agent . setStorage ( storage );
agent . setLogger ( logger );
Register components in constructor
Register all components in the Mastra constructor for proper initialization order: const mastra = new Mastra ({
tools , // Register first
processors , // Then processors
memory , // Then memory
agents // Agents last (may use other components)
});
Type Safety
Mastra provides full TypeScript support with generic type parameters:
type MyAgents = {
weather : Agent < 'weather' >;
support : Agent < 'support' >;
};
type MyWorkflows = {
dataProcessor : Workflow <...>;
};
const mastra = new Mastra < MyAgents , MyWorkflows >({
agents: {
weather: weatherAgent ,
support: supportAgent
},
workflows: {
dataProcessor: dataWorkflow
}
});
// Type-safe retrieval
const agent = mastra . getAgent ( 'weather' ); // Type: Agent<'weather'>
Agents - Autonomous AI systems
Workflows - Step-based execution
Memory - Conversation persistence
Tools - Tool composition patterns