Skip to content

Chapter 1 · Mastra Overview and Environment Setup ​

Chapter goals: Understand Mastra's position in the TypeScript AI ecosystem, create and run a scaffold project, and build a panoramic view of the core capability modules.

1.1 What Is Mastra ​

Mastra is a full-stack AI application and agent framework for the TypeScript ecosystem, incubated by Y Combinator W25. It packages the common capabilities needed to build AI products into a unified development experience:

CapabilityDescriptionAnalogy
Model RoutingOne interface to接入 40+ model providersORM in the database world
AgentsAutonomous agents that make decisions and call tools to solve open-ended tasksLangChain Agent
WorkflowsGraphical multi-step orchestration engineAirflow / Temporal
MemoryConversation history and observational memorySession state management
RAGRetrieve data from APIs, databases, and files to enhance responsesVector search pipeline
Evals & ObservabilityEvaluation and observabilityTesting + monitoring

Why choose Mastra

If you're a TypeScript developer, Mastra lets you avoid switching to Python while obtaining abstraction capabilities on par with LangChain/LlamaIndex, and integrate seamlessly with React, Next.js, and Node.js projects — or deploy as a standalone service.

1.2 Environment Requirements and Installation ​

Mastra recommends Node.js 20 or above (Node 22.18+ can run TypeScript files directly):

bash
# Check Node version
node -v
# v22.x.x

# Create project with official scaffold (recommended)
npm create mastra@latest my-mastra-app

The scaffold interactively asks for project name and model provider:

text
Project name? my-mastra-app
Provider? openai   # Options: openai / anthropic / google / xai

You can also specify all parameters at once:

bash
# Skip interactive prompts by specifying name and provider directly
npm create mastra@latest my-app -- --llm openai
cd my-app && npm install

1.3 Starting the Dev Server and Studio ​

After entering the project directory, start the dev server:

bash
npm run dev

Open your browser to http://localhost:4111 to see Mastra Studio — Mastra's built-in visual工作台 for testing Agents, debugging Workflows, and viewing Traces. You'll use it frequently in subsequent chapters.

typescript
// Key scripts in package.json (auto-generated by scaffold)
// "dev":   "mastra dev"     —— start dev server and Studio
// "build": "mastra build"   —— build production artifacts

1.4 Core Capabilities Overview ​

Before diving into each module, preview Mastra's overall shape with this minimal complete example — a "weather assistant with tools":

typescript
// src/mastra/agents/weather-agent.ts
import { Agent } from '@mastra/core/agent';
import { weatherTool } from '../tools/weather-tool';

export const weatherAgent = new Agent({
  id: 'weather-agent',
  name: 'Weather Agent',
  // instructions is the agent's system prompt: defines role and behavioral rules
  instructions: `
    You are a helpful weather assistant.
    Use the weatherTool to fetch current weather data.
    Keep responses concise but informative.`,
  // model must be a provider/model string format
  model: 'openai/gpt-5-mini',
  tools: { weatherTool },
});
typescript
// src/mastra/index.ts —— Mastra entry point, registers all resources
import { Mastra } from '@mastra/core';
import { weatherAgent } from './agents/weather-agent';

export const mastra = new Mastra({
  agents: { weatherAgent },
});
typescript
// Invocation: retrieve agent by id from the mastra instance and generate a response
import { mastra } from './mastra';

const agent = mastra.getAgent('weatherAgent');
const response = await agent.generate('What\'s the weather like in Beijing today?');
console.log(response.text); // The LLM may call weatherTool then compose an answer

The three code blocks correspond to the standard chain: define Agent → register on instance → invoke execution — also the basic skeleton for all subsequent chapters.

1.5 Learning Roadmap ​

The 21-chapter learning path for this course:

text
Getting Started (01-06): Environment → Studio → Model Routing → Agent → Tools → Integration
Intermediate (07-13): Workflow sequential/branch/parallel → Suspend/Resume → Memory → RAG → Storage
Advanced (14-17): MCP Server → Evals → Observability → Frontend integration
Production (18-20): Standalone deployment → Best practices → Capstone projects

Each chapter includes runnable TypeScript code, quizzes, and hands-on exercises. Study along with the Studio to verify results interactively.

1.6 Chapter Summary ​

  • Mastra is a full-stack TypeScript AI framework covering six core capabilities: model routing, Agent, Workflow, Memory, RAG, and evaluation;
  • Create a project with npm create mastra@latest, start with npm run dev, and access Studio at localhost:4111;
  • Standard chain: define Agent → register in new Mastra({ agents }) → agent.generate();
  • model must be written as a provider/model string (e.g., openai/gpt-5-mini).

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What is Mastra's officially recommended way to create a new project?

2. At which address does Mastra Studio run by default?

3. When configuring a model for an Agent in Mastra, what is the correct format for the model field?

4. Which of the following is NOT a built-in core capability of Mastra?

🛠️ Hands-On Exercises ​

  1. Create two projects using the scaffold with openai and anthropic providers respectively; compare the generated src/mastra/ directory differences.
  2. Run the weather assistant from Section 1.4; send a message to it in Studio's Agents tab and observe the tool invocation process.
  3. Inspect package.json, list all @mastra/* dependencies with their versions, and record them in your notes.

Next: Chapter 2 · Project Structure and Mastra Studio