System Architecture Overview
Relevant source files
The following files were used as context for generating this wiki page:- CLAUDE.md
- DEVELOPMENT.md
- README.md
- e2e-tests/kitchen-sink/README.md
- packages/agent-builder/src/defaults.ts
- packages/agent-builder/src/workflows/template-builder/template-builder.ts
- packages/agent-builder/src/workflows/workflow-builder/prompts.ts
- packages/mcp-docs-server/src/tools/docs.ts
- templates/README.md
- templates/template-ad-copy-from-content/README.md
- templates/template-coding-agent/src/mastra/agents/coding-agent.ts
- templates/template-csv-to-questions/README.md
- templates/template-docs-chatbot/README.md
- templates/template-google-sheets/src/mastra/agents/financial-modeling-agent.ts
Mastra is a modular AI framework for building, tuning, and scaling AI-powered applications and agents using TypeScript. The architecture is designed around a central orchestration hub with pluggable components, enabling developers to create complex AI systems that can be integrated into existing applications or deployed as standalone services. Key architectural patterns include dependency injection, a plugin architecture for components like storage and memory, and a unified message handling abstraction.
The framework provides high-level abstractions for common AI patterns, including autonomous agents that reason and use tools, graph-based workflows for orchestrating multi-step processes, and sophisticated context management through various memory systems. This overview details the monorepo structure, core components, and common application patterns found within the Mastra ecosystem.
Sources: README.md, CLAUDE.md:28-34
Monorepo Structure
Mastra is organized as a pnpm-managed monorepo. This structure separates the core framework, integrations, and examples into distinct packages, facilitating modular development and maintenance.
Sources: DEVELOPMENT.md:10-11, CLAUDE.md:37-46
The diagram below illustrates the high-level organization of the repository.
Sources: CLAUDE.md:37-46, DEVELOPMENT.md:13-33
The key directories are summarized in the table below:
| Directory | Description |
|---|---|
packages/ | Contains the core packages that constitute the Mastra framework. |
packages/core | The foundational package with essential components like the Agent system, Workflows, and Tools infrastructure. |
packages/agent-builder | Provides tools and workflows for building and scaffolding AI agents and applications. |
packages/cli | The command-line interface for managing Mastra projects. |
packages/deployer | Server infrastructure and build tools for deploying Mastra applications. |
packages/mcp | Implementation of the Model Context Protocol (MCP) for standardized communication with AI models and tools. |
stores/ | Storage adapters for various vector and key-value databases (e.g., PostgreSQL, Chroma, Pinecone). |
deployers/ | Platform-specific deployment adapters for services like Vercel and Netlify. |
client-sdks/ | Client libraries for interacting with Mastra services from different platforms. |
integrations/ | Third-party API integrations. |
examples/ | Example applications demonstrating various Mastra features. |
templates/ | Boilerplate projects for common use cases like documentation chatbots and coding agents. |
Sources: DEVELOPMENT.md:13-40, CLAUDE.md:37-46, templates/README.md
Core Components
Mastra's architecture is built upon a set of interconnected, pluggable components that register with a central Mastra instance. This promotes modularity and extensibility.
Sources: CLAUDE.md:28-34
This diagram shows the relationship between the main components.
Sources: CLAUDE.md:30-34
Agents
Agents are the primary abstraction for AI interaction. They are autonomous entities that use LLMs, tools, and memory to reason about and solve open-ended tasks.
An Agent is configured with:
- Instructions: A prompt defining the agent's role, capabilities, and constraints.
- Model: The language model the agent will use for reasoning (e.g.,
openai/gpt-4.1). - Tools: A set of functions the agent can execute to interact with the outside world.
- Memory: A system for persisting conversation history and context.
Sources: README.md:21-22, CLAUDE.md:30, templates/template-coding-agent/src/mastra/agents/coding-agent.ts:7-11
The following is an example of a codingAgent definition.
// templates/template-coding-agent/src/mastra/agents/coding-agent.ts:7-40
export const codingAgent = new Agent({
id: 'coding-agent',
name: 'Coding Agent',
instructions: `...`,
model: process.env.MODEL || 'openai/gpt-4.1',
tools: {
createSandbox,
runCode,
readFile,
writeFile,
// ... more tools
},
memory: new Memory({
storage: new LibSQLStore({ id: 'coding-agent-storage', url: 'file:../../mastra.db' }),
options: {
generateTitle: true,
semanticRecall: true,
workingMemory: { enabled: true },
},
embedder: fastembed,
vector: new LibSQLVector({ id: 'coding-agent-vector', connectionUrl: 'file:../../mastra.db' }),
}),
defaultOptions: { maxSteps: 20 },
});
Tools System
The tools system allows agents to perform actions. Tools are dynamically composed from various sources and are defined using createTool, which includes a Zod schema for input and output validation. Agents are provided with a rich set of default tools for file operations, command execution, project management, and web search.
Sources: CLAUDE.md:31, packages/agent-builder/src/defaults.ts:402-418
This diagram shows how an agent uses a tool.
The AgentBuilder provides a default set of tools for common development tasks.
| Tool ID | Description |
|---|---|
read-file | Read contents of a file with optional line range selection. |
write-file | Write content to a file, with options for creating directories. |
list-directory | List contents of a directory with filtering and metadata options. |
execute-command | Execute shell commands with proper error handling and output capture. |
validate-code | Validates code using a fast hybrid approach: syntax → semantic → lint. |
manage-project | Handles project management including creating structures and managing dependencies. |
manage-server | Manages the Mastra server (start, stop, restart, status). |
http-request | Makes HTTP requests to the Mastra server or external APIs. |
web-search | Search the web for current information. |
Sources: packages/agent-builder/src/defaults.ts:402-802
Workflows
Workflows provide explicit control over execution for orchestrating complex, multi-step processes. They are defined as a graph of steps using an intuitive chaining syntax (.then(), .parallel(), .branch()). Each step is created with createStep and has its own defined input and output schemas.
A key feature is the ability to suspend a workflow to await external input, such as human approval, and then resume it. This is managed through a persistent storage layer.
Sources: README.md:24-27, CLAUDE.md:32, packages/agent-builder/src/workflows/workflow-builder/prompts.ts:11-23, 70-85
The agentBuilderTemplateWorkflow is a complex example that demonstrates cloning a template, analyzing it, merging dependencies, installing packages, and validating the code.
This diagram shows a simplified flow of the agentBuilderTemplateWorkflow.
Memory and Storage
The memory system provides agents with context through several mechanisms:
- Conversation History: Persists the history of interactions.
- Semantic Recall: Retrieves relevant past interactions using vector search.
- Working Memory: Maintains short-term context within a session.
This system relies on a pluggable storage layer, which uses adapters for different backends like LibSQLStore for a local database. This layer is also used by workflows to persist their state, enabling features like suspend and resume.
Sources: README.md:29-32, CLAUDE.md:32, 50-52, templates/template-coding-agent/src/mastra/agents/coding-agent.ts:31-38
Application & Deployment Patterns
Mastra applications can be structured in different ways depending on the use case.
Standalone vs. Integrated
A Mastra application can be:
- Integrated into an existing backend or frontend framework like Next.js, React, or a standard Node.js app.
- Deployed as a standalone server, exposing agents and workflows via API endpoints.
Sources: README.md:14, 34-35
Modular MCP Architecture
A common pattern, demonstrated in the template-docs-chatbot, is to separate concerns by creating a dedicated Model Context Protocol (MCP) Server.
- MCP Server: A standalone server that exposes tools (e.g., for documentation lookup) over HTTP/SSE.
- Agent Server: A separate Mastra agent application that consumes the tools from the MCP server to perform its tasks.
- Frontend: A web application that interacts with the Agent Server.
This modularity allows the tool-providing service to be developed, deployed, and scaled independently of the agent that uses it.
Sources: templates/template-docs-chatbot/README.md:6-12, 106-111, README.md:37-39
The diagram below illustrates this separated architecture.
Development and Testing Pipeline
The project uses pnpm for monorepo management and turborepo to manage build dependencies. The end-to-end testing process provides insight into the build and release architecture:
- A local NPM instance (
Verdaccio) is spawned. - All Mastra packages are built and published to the local Verdaccio instance.
- A test application (e.g., from the
templatedirectory) is instantiated with itspackage.jsonmodified to use the locally published packages. - Playwright E2E tests are run against this application.
This complex setup ensures that tests are run against the compiled packages as a user would consume them from NPM, validating the entire user journey from installation to execution.
Sources: DEVELOPMENT.md:46-50, e2e-tests/kitchen-sink/README.md:58-71
Conclusion
The Mastra system architecture is designed for modularity, extensibility, and production-readiness. Its agent-centric model, combined with powerful workflow orchestration and a pluggable component system, provides a robust foundation for building sophisticated AI applications. The separation of concerns, evident in both the monorepo structure and recommended application patterns like the MCP server architecture, allows for scalable and maintainable development of complex AI systems.