Mastra 深度解析:2026 年最值得关注的 TypeScript AI Agent 框架——从内核设计到生产级部署的完整实战指南
如果你正在用 TypeScript 构建 AI 应用,还在为 LangChain 的复杂度头疼,或者觉得 Vercel AI SDK 太偏前端——Mastra 可能会改变你的技术选型。这篇文章将从底层设计、核心模块、实战代码到生产部署,全方位拆解这款 2026 年最热门的 TypeScript AI 框架。
一、背景:为什么 TypeScript 生态需要一个原生 AI 框架?
2024-2026 年,AI Agent 开发框架的格局发生了剧烈变化。
Python 生态有 LangChain、LlamaIndex、AutoGen;但 TypeScript 这边,前端开发者想做 AI 功能,要么自己封装 OpenAI SDK,要么引入厚重的不适配 TS 的 Python 移植版。
Vercel AI SDK 偏前端,核心场景是 "给 Next.js 页面加个聊天框";LangChain.js 是把 Python LangChain 的逻辑移植过来,概念繁重,TS 类型体验差强人意。
Mastra 的出现,填补了一个关键空白:为 TypeScript 原生设计的、全栈可用的、从原型到生产的 AI Agent 框架。
Mastra 是谁做的?
Mastra 由独立团队开发,2026 年入选 Y Combinator W25 批次,GitHub 星标增长迅速,已被 Replit、Fireworks、Medusa、Sanity 等公司在生产环境采用。
核心定位
Mastra = TypeScript 原生 + Agent + Workflow + Memory + 模型路由 + 可观测性,一站式解决 AI 应用从开发到部署的全链路问题。
二、核心概念全解析
Mastra 的设计哲学是:Agent 负责开放决策,Workflow 负责确定逻辑,Memory 负责上下文,Tools 负责外部能力。
2.1 Agent—— autonomous reasoning 的执行主体
Agent 是 Mastra 的核心 primitive。每个 Agent 包含:
- instructions(系统提示词,定义 Agent 的行为边界)
- model(LLM 模型,格式为
provider/model,如openai/gpt-5.5) - tools(Agent 可以调用的工具集合)
- memory(跨轮对话的记忆能力)
import { Agent } from '@mast/core/agent'
const coderAgent = new Agent({
id: 'coder-agent',
name: 'Coder Agent',
instructions: `
你是一个资深 TypeScript 开发助手。
你的职责是:
1. 理解用户的编程需求
2. 使用提供的工具查询文档和编写代码
3. 返回类型安全、可运行的 TypeScript 代码
4. 代码必须包含完整的类型注解和错误处理
`,
model: 'anthropic/claude-sonnet-4-6',
tools: { /* 见下文 */ },
})
关键设计决策:Mastra 的 Agent 不依赖任何特定的 LLM 提供商。通过内置的 Model Router,只需切换 model 字符串,就能在 40+ 模型提供商之间无缝切换,无需修改业务代码。
2.2 模型路由:一行代码切换 40+ 模型
Mastra 内置了模型网关(Model Router),支持 OpenAI、Anthropic、Google、Groq、Together AI 等 40+ 提供商。
模型字符串格式统一为 provider/model,环境变量自动匹配:
| 模型字符串 | 所需环境变量 |
|---|---|
openai/gpt-5.5 | OPENAI_API_KEY |
anthropic/claude-sonnet-4-6 | ANTHROPIC_API_KEY |
google/gemini-2.5-flash | GOOGLE_API_KEY |
groq/llama-3-70b | GROQ_API_KEY |
实战技巧:在开发阶段用便宜/快速的模型(如 google/gemini-2.5-flash),生产环境切换到高质量模型(anthropic/claude-opus-4-7),只需改一个字符串。
2.3 Tool——Agent 的能力扩展点
Tool 是 Agent 与外部世界交互的接口。Mastra 要求 Tool 必须通过 createTool() 函数定义(普通对象会被静默忽略!),并强制使用 Zod/Valibot/ArkType 进行输入输出 schema 校验。
import { createTool } from '@mast/core/tools'
import { z } from 'zod'
export const searchDocsTool = createTool({
id: 'search-docs',
description: '搜索 Mastra 官方文档,接收查询关键词,返回相关文档片段',
inputSchema: z.object({
query: z.string().describe('搜索关键词,支持中英文'),
limit: z.number().min(1).max(10).default(5).describe('返回结果数量'),
}),
outputSchema: z.object({
results: z.array(z.object({
title: z.string(),
content: z.string(),
url: z.string(),
})),
}),
execute: async ({ query, limit }) => {
// 实际实现:调用文档搜索 API
const results = await searchMastraDocs(query, limit)
return { results }
},
})
execute 函数的签名:
- 第一个参数:经过 Zod 校验的输入数据(直接从
inputSchema推导) - 第二个参数(可选):执行上下文,包含
requestContext、tracingContext、abortSignal等
2.4 Workflow——确定性强、可观测的多步编排
当任务的执行步骤是明确的时候,用 Agent 反而太"自由"。Workflow 提供了确定性的、类型安全的、可暂停/恢复的图执行引擎。
import { createWorkflow, createStep } from '@mast/core/workflows'
import { z } from 'zod'
// 步骤 1:获取用户输入
const fetchUserInput = createStep({
id: 'fetch-input',
inputSchema: z.object({ userId: z.string() }),
outputSchema: z.object({ input: z.string(), history: z.array(z.string()) }),
execute: async ({ inputData }) => {
const user = await db.users.findById(inputData.userId)
return {
input: user.lastMessage,
history: user.messageHistory,
}
},
})
// 步骤 2:调用 Agent 生成回复
const generateReply = createStep({
id: 'generate-reply',
inputSchema: z.object({ input: z.string(), history: z.array(z.string()) }),
outputSchema: z.object({ reply: z.string(), confidence: z.number() }),
execute: async ({ inputData }) => {
const agent = mastra.getAgentById('support-agent')
const response = await agent.generate(inputData.input, {
memory: { resource: inputData.userId, thread: 'support-session' },
})
return {
reply: response.text,
confidence: response.usage?.completionTokens ? 0.9 : 0.5,
}
},
})
// 组装 Workflow
export const supportWorkflow = createWorkflow({
id: 'support-workflow',
inputSchema: z.object({ userId: z.string() }),
outputSchema: z.object({ reply: z.string() }),
})
.then(fetchUserInput)
.then(generateReply)
.commit()
Workflow 的核心优势:
- 类型安全:inputSchema/outputSchema 在全链路自动推导类型
- 可观测:每个 Step 的输入输出都记录在 tracing 系统里
- 可暂停/恢复:支持
.suspend()和.resume(),适合人工审批场景 - Time Travel 调试:Studio 里可以回放任意 Step 的执行过程
2.5 Memory——让 Agent 真正"记住"对话
Mastra 的 Memory 系统分为四个层次:
| Memory 类型 | 作用 | 适用场景 |
|---|---|---|
| Message History | 保留原始对话消息 | 基础多轮对话 |
| Observational Memory | 后台 Agent 压缩历史消息为观察摘要 | 超长对话,避免 context window 溢出 |
| Working Memory | 结构化存储用户偏好/目标 | 记住用户设置、项目名称等 |
| Semantic Recall | 基于向量语义检索历史消息 | "我上周问过什么问题" |
import { Memory } from '@mast/memory'
const agentWithMemory = new Agent({
id: 'personal-agent',
name: 'Personal Assistant',
model: 'openai/gpt-5.5',
memory: new Memory({
options: {
lastMessages: 20, // 保留最近 20 条消息
observationalMemory: true, // 启用观察记忆(自动压缩)
workingMemory: { // 工作记忆配置
schema: z.object({
userName: z.string().optional(),
preferredLanguage: z.string().default('zh-CN'),
currentProject: z.string().optional(),
}),
},
semanticRecall: { // 语义召回配置
topK: 5,
messageRange: { before: 3, after: 2 },
},
},
}),
})
Observational Memory 的工作原理:
当对话历史超过阈值,Mastra 会启动一个后台 Agent,将旧消息压缩为结构化观察记录(例如:"用户偏好用 TypeScript;正在开发 Mastra 项目;上次讨论了 Memory 配置")。这些观察记录占用极少的 token,但保留了长期记忆的精髓。
三、架构深度分析
3.1 整体架构图
┌─────────────────────────────────────────────────────┐
│ Mastra Instance │
│ (new Mastra({ agents, workflows, storage, ... }))│
└──────────────┬──────────────────────────────────────┘
│
┌───────┴────────┐
│ │
┌──────▼──────┐ ┌─────▼──────┐
│ Agents │ │ Workflows │
│ │ │ │
│ - LLM Call │ │ - Step Graph │
│ - Tools │ │ - Suspension │
│ - Memory │ │ - Streaming │
└──────┬──────┘ └─────┬──────┘
│ │
└────────┬────────┘
│
┌──────────┴──────────┐
│ Shared Services │
│ │
│ - Storage (LibSQL/ │
│ PgVector/Upstash) │
│ - Logger │
│ - Tracing (LangFuse)│
│ - Voice (STT/TTS) │
└─────────────────────┘
3.2 Mastra Instance 的设计
Mastra 类是应用的入口点,负责:
- 注册所有 Agent、Workflow、Tool
- 注入共享服务(Storage、Logger、Tracing)
- 启动 HTTP 服务(可选,内置 Hono 服务器)
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
agents: { supportAgent, coderAgent },
workflows: { supportWorkflow },
storage: new LibSQLStore({ url: process.env.DATABASE_URL }),
logger: new PinoLogger({ level: 'info' }),
tracing: new LangFuseTracing({ publicKey: process.env.LANGFUSE_KEY }),
})
3.3 Agent 执行链路(从 .generate() 到返回)
当你调用 agent.generate('用户消息') 时,内部发生了什么?
1. Memory 加载:根据 resource + thread 从 Storage 加载历史消息
2. Prompt 组装:system(instructions) + history + user message
3. Tool 注入:将所有注册 Tool 的 JSON Schema 注入到 LLM 请求
4. LLM 调用:通过 Model Router 转发到对应提供商
5. Tool Call 解析:如果 LLM 返回 tool_calls,执行对应 Tool
6. 循环迭代:将 Tool 结果返回给 LLM,直到 LLM 返回最终答案
7. Memory 保存:将本轮对话保存到 Storage
8. 返回结果:{ text, toolCalls, toolResults, steps, usage }
这个链路的每一步都可以通过 Processor 拦截和修改:
const agent = new Agent({
// ...
processors: [
{
// 在 LLM 调用前修改消息
beforeGenerate: ({ messages }) => {
return messages.map(msg => ({
...msg,
content: msg.content.replace(/敏感词/g, '***'),
}))
},
},
],
})
四、代码实战:从零构建一个技术支持 Agent
下面通过一个完整的实战案例,展示 Mastra 的各模块如何协同工作。
4.1 项目初始化
npm create mastra@latest
# 选择:Yes to install dependencies
# 选择:Yes to initialize git
# 选择:None(暂时不添加示例)
生成的项目结构:
my-mastra-app/
├── src/
│ ├── mastra/
│ │ ├── agents/
│ │ ├── tools/
│ │ ├── workflows/
│ │ └── index.ts # Mastra 实例入口
│ └── index.ts
├── package.json
├── tsconfig.json
└── .env # 环境变量
4.2 定义 Tool:查询订单数据库
// src/mastra/tools/order-tool.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const queryOrderTool = createTool({
id: 'query-order',
description: '根据用户ID或订单号查询订单信息。返回订单状态、商品列表、物流信息。',
inputSchema: z.object({
userId: z.string().optional().describe('用户ID'),
orderId: z.string().optional().describe('订单号'),
}).refine(data => data.userId || data.orderId, {
message: '必须提供 userId 或 orderId 其中之一',
}),
outputSchema: z.object({
found: z.boolean(),
order: z.object({
id: z.string(),
status: z.enum(['pending', 'shipped', 'delivered', 'cancelled']),
items: z.array(z.object({
name: z.string(),
quantity: z.number(),
price: z.number(),
})),
tracking: z.string().optional(),
}).optional(),
}),
execute: async ({ userId, orderId }) => {
// 实际项目中连接数据库
const prisma = getPrismaClient()
const order = await prisma.order.findFirst({
where: {
OR: [
{ id: orderId },
{ userId: userId },
],
},
orderBy: { createdAt: 'desc' },
take: 1,
include: { items: true },
})
if (!order) {
return { found: false }
}
return {
found: true,
order: {
id: order.id,
status: order.status,
items: order.items.map(item => ({
name: item.name,
quantity: item.quantity,
price: item.price,
})),
tracking: order.trackingNumber ?? undefined,
},
}
},
})
4.3 定义 Agent:技术支持助手
// src/mastra/agents/support-agent.ts
import { Agent } from '@mastra/core/agent'
import { Memory } from '@mastra/memory'
import { LibSQLStore } from '@mastra/libsql'
import { queryOrderTool } from '../tools/order-tool'
import { searchDocsTool } from '../tools/docs-tool'
export const supportAgent = new Agent({
id: 'support-agent',
name: '技术支持助手',
instructions: `
你是一个专业、耐心、高效的技术支持助手。
## 核心职责
- 帮助用户查询订单状态
- 回答产品使用问题(通过查询文档)
- 将无法处理的问题礼貌地转接人工
## 行为准则
- 始终使用 query-order 工具查询订单,不要猜测订单信息
- 使用 search-docs 工具查找产品文档,基于文档内容回答
- 如果工具调用失败,告知用户具体原因
- 回复使用中文,技术术语保留英文
- 不要编造不存在的订单信息或产品功能
## 订单状态说明
- pending: 待处理
- shipped: 已发货(提供物流单号)
- delivered: 已送达
- cancelled: 已取消
`,
model: 'openai/gpt-5.5',
tools: {
queryOrderTool,
searchDocsTool,
},
memory: new Memory({
options: {
lastMessages: 15,
observationalMemory: true,
},
}),
})
4.4 注册到 Mastra 实例
// src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { LibSQLStore } from '@mastra/libsql'
import { supportAgent } from './agents/support-agent'
import { coderAgent } from './agents/coder-agent'
import { supportWorkflow } from './workflows/support-workflow'
export const mastra = new Mastra({
agents: {
supportAgent,
coderAgent,
},
workflows: {
supportWorkflow,
},
storage: new LibSQLStore({
id: 'production-storage',
url: process.env.DATABASE_URL || ':memory:',
}),
})
4.5 调用 Agent(Next.js API Route 示例)
// src/app/api/chat/route.ts
import { mastra } from '@/mastra'
import { NextRequest, NextResponse } from 'next/server'
export async function POST(req: NextRequest) {
const { message, userId } = await req.json()
const agent = mastra.getAgentById('support-agent')
const response = await agent.stream(message, {
memory: {
resource: userId, // 每个用户独立的记忆空间
thread: `support-${userId}`, // 每个用户一个会话线程
},
})
// 流式返回
const stream = new ReadableStream({
async start(controller) {
for await (const chunk of response.textStream) {
controller.enqueue(new TextEncoder().encode(chunk))
}
controller.close()
},
})
return new NextResponse(stream, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
})
}
五、高级特性实战
5.1 Human-in-the-Loop:关键操作的审批流程
某些操作(如退款、删除数据)需要人工审批。Mastra 的 Agent Approval 机制可以在 Tool 执行前暂停,等待人工确认。
import { createTool } from '@mastra/core/tools'
const refundTool = createTool({
id: 'process-refund',
description: '处理用户退款申请。需要人工审批。',
inputSchema: z.object({
orderId: z.string(),
amount: z.number(),
reason: z.string(),
}),
execute: async ({ orderId, amount, reason }) => {
// 执行退款逻辑
await paymentProvider.refund(orderId, amount)
return { success: true, transactionId: `ref_${Date.now()}` }
},
})
// 在 Agent 中配置审批
const agent = new Agent({
id: 'refund-agent',
name: 'Refund Agent',
tools: { refundTool },
// 配置需要审批的工具
approval: {
rules: [
{
toolId: 'process-refund',
// 金额超过 1000 需要审批
condition: (input) => input.amount > 1000,
// 审批超时 10 分钟
timeoutMs: 600_000,
},
],
},
})
当 Agent 调用 process-refund 且金额超过 1000 时,执行会暂停,Workflow 进入 suspended 状态。人工审批通过后,调用 workflow.resume() 继续执行。
5.2 Multi-Agent 协作:Supervisor 模式
复杂的任务可以拆给多个专业 Agent,由 Supervisor Agent 协调。
// 专业 Agent:代码审查
const codeReviewAgent = new Agent({
id: 'code-reviewer',
name: 'Code Reviewer',
description: '专业审查 TypeScript 代码,检查类型安全、性能问题和最佳实践',
instructions: '你是资深 TypeScript 代码审查专家...',
model: 'anthropic/claude-sonnet-4-6',
})
// 专业 Agent:测试生成
const testGenAgent = new Agent({
id: 'test-generator',
name: 'Test Generator',
description: '为 TypeScript 代码生成全面的单元测试',
instructions: '你是测试工程专家,擅长写 Vitest 测试...',
model: 'openai/gpt-5.5',
})
// Supervisor Agent
const supervisorAgent = new Agent({
id: 'supervisor',
name: 'Supervisor',
instructions: `
你协调 code-reviewer 和 test-generator 两个子 Agent。
收到代码后:
1. 先交给 code-reviewer 审查
2. 审查通过后,交给 test-generator 生成测试
3. 汇总结果返回给用户
`,
model: 'anthropic/claude-opus-4-7',
agents: {
codeReviewAgent,
testGenAgent,
},
})
Supervisor 会自动将子 Agent 转换为 Tool(agent-code-reviewer 和 agent-test-generator),通过 Tool Call 实现委托。
子 Agent 的记忆隔离:每次委托都会创建独立的 threadId,但 resourceId 是确定的({parentResourceId}-{agentName}),因此子 Agent 能跨多次委托记住信息。
5.3 Workflow 的 Branch 和 Parallel
Workflow 支持条件分支和并行执行,覆盖复杂业务逻辑:
export const orderProcessingWorkflow = createWorkflow({
id: 'order-processing',
inputSchema: z.object({ orderId: z.string() }),
outputSchema: z.object({ success: z.boolean(), trackingId: z.string().optional() }),
})
.then(fetchOrderStep)
// 条件分支:根据订单类型走不同路径
.branch({
source: 'fetchOrderStep',
cases: [
{
condition: (output) => output.order.type === 'physical',
target: physicalOrderStep,
},
{
condition: (output) => output.order.type === 'digital',
target: digitalDeliveryStep,
},
],
})
// 并行执行:同时发送确认邮件和更新库存
.parallel([sendConfirmationEmail, updateInventory])
.then(updateOrderStatusStep)
.commit()
六、与主流框架的横向对比
| 维度 | Mastra | LangChain.js | Vercel AI SDK | Agno |
|---|---|---|---|---|
| 语言 | TypeScript 原生 | Python 优先,JS 移植 | TypeScript 原生 | Python |
| 学习曲线 | 中等 | 陡峭 | 平缓 | 中等 |
| Agent 抽象 | 完善 | 完善但复杂 | 基础 | 完善 |
| Workflow 引擎 | 内置,图执行 | LangGraph(独立) | 无 | 无 |
| Memory 系统 | 四层(含观察记忆) | 基础 | 基础 | 三层 |
| 模型路由 | 40+ 内置 | 需手动配置 | 需手动配置 | 20+ |
| 可观测性 | 内置(LangFuse 等) | 需额外配置 | 基础 | 内置 |
| 部署方式 | 独立服务/集成现有应用 | 独立服务 | 仅前端/Serverless | 独立服务 |
| 前端集成 | Next.js/React/Vite 官方指南 | 无官方指南 | 核心场景 | 无 |
| 企业采用 | Replit/Fireworks 等 | 广泛 | Vercel 生态 | 较少 |
选型建议:
- 如果你用 Next.js 做全栈开发,Mastra 的前端集成指南最完善
- 如果你需要 复杂的 Agent 协作模式,Mastra 的 Supervisor + 子 Agent 机制比 LangChain 更直观
- 如果你做 纯前端 AI 聊天界面,Vercel AI SDK 更轻量
- 如果你用 Python 技术栈,LangChain 或 Agno 更合适
七、生产部署最佳实践
7.1 部署模式选择
Mastra 支持多种部署模式:
模式一:集成到现有应用
// 在 Next.js 中直接使用
import { mastra } from '@/mastra'
const agent = mastra.getAgentById('support-agent')
模式二:独立 HTTP 服务
// mastra serve 启动独立服务
// 其他服务通过 HTTP API 调用
const response = await fetch('http://localhost:4111/api/agents/support-agent/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: '你好' }),
})
模式三:Serverless(Vercel/Cloudflare Workers)
// 利用 Mastra 的 Server Adapters
import { HonoAdapter } from '@mastra/server/hono'
export default new HonoAdapter({
mastra,
route: '/api/ai',
})
7.2 性能优化清单
- 使用 Streaming:
.stream()比.generate()用户体验好得多,首字延迟极低 - Tool 结果缓存:对幂等 Tool(如"查询天气")添加 TTL Cache
- Memory 索引优化:LibSQL/PostgreSQL 的连接池配置
- Model 降级策略:简单问题用低成本模型,复杂问题才用旗舰模型
- Observational Memory 阈值调整:根据业务场景平衡记忆质量和成本
const optimizedMemory = new Memory({
options: {
lastMessages: 10, // 不要保留太多原始消息
observationalMemory: {
triggerAfter: 20, // 20条消息后开始压缩
compactionFrequency: 5, // 每5条新消息更新一次观察
},
},
})
7.3 安全与 Guardrails
const safeAgent = new Agent({
id: 'safe-agent',
name: 'Safe Agent',
guardrails: [
{
// 输入过滤:防止 prompt injection
beforeGenerate: ({ messages }) => {
const lastMessage = messages[messages.length - 1].content
if (lastMessage.includes('ignore previous instructions')) {
throw new Error('Potential prompt injection detected')
}
return messages
},
},
{
// 输出过滤:防止敏感信息泄露
afterGenerate: ({ response }) => {
const sanitized = response.text.replace(
/\b[\w.-]+@[\w.-]+\.\w{2,}\b/g,
'[email redacted]'
)
return { ...response, text: sanitized }
},
},
],
})
八、真实案例:Replit Agent 3 如何用 Mastra 构建
Replit 在 2026 年发布的 Agent 3 使用了 Mastra 作为底层框架。核心架构:
- Multi-Agent 系统:Planner Agent → Coder Agent → Reviewer Agent → Deployer Agent
- Workflow 编排:每个部署流程是一个 Mastra Workflow,支持暂停(等待用户确认)和恢复
- Memory 驱动个性化:每个 Replit 用户有独立的 Memory,记住编码偏好、常用依赖、项目历史
- Tool 生态:文件系统 Tool、Shell 执行 Tool、NPM 安装 Tool、浏览器预览 Tool
关键代码片段(简化版):
// Replit Agent 3 的核心 Workflow
const buildAppWorkflow = createWorkflow({
id: 'replit-build-app',
inputSchema: z.object({ prompt: z.string(), userId: z.string() }),
})
.then(planningStep) // Planner Agent 制定实现计划
.then(codeGenerationStep) // Coder Agent 生成代码
.then(lintAndFixStep) // 自动修复 Lint 错误
.then(runTestsStep) // 执行测试
.branch({ // 测试失败?回到代码生成
source: 'runTestsStep',
cases: [
{ condition: (o) => !o.passed, target: codeGenerationStep },
],
})
.then(deployPreviewStep) // 部署预览环境
.then(awaitUserApprovalStep) // 暂停,等待用户确认
.then(deployProductionStep) // 用户确认后,部署生产环境
.commit()
九、Mastra 的生态系统
9.1 官方 Integration
Mastra 官方维护了丰富的 Integration 包:
| 包名 | 用途 |
|---|---|
@mastra/libsql | LibSQL 存储后端(本地/Turso) |
@mastra/pg | PostgreSQL 存储后端 |
@mastra/upstash | Upstash Redis/Vektor 存储 |
@mastra/memory | Memory 系统核心包 |
@mastra/voice | 语音输入输出(STT/TTS) |
@mastra/tracing-langfuse | LangFuse 可观测性集成 |
9.2 MCP(Model Context Protocol)支持
Mastra Agent 可以连接远程 MCP 服务器,动态加载 Tool:
import { MCPServer } from '@mastra/mcp'
const githubMCPServer = new MCPServer({
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-github'],
env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN },
})
const agent = new Agent({
id: 'github-agent',
name: 'GitHub Agent',
mcpServers: [githubMCPServer], // 自动加载所有 GitHub 相关 Tool
})
9.3 Studio:本地调试 UI
npx mastra studio 启动一个本地 Web UI,功能包括:
- Agent 测试:交互式聊天,查看 Tool Call 详情
- Workflow 可视化:查看 Step Graph,实时监控执行状态
- Time Travel 调试:回放历史执行,逐 Step 调试
- Memory 检查:查看 Agent 的记忆内容
- Tracing 浏览:查看每次 LLM 调用的详细信息
十、总结与展望
Mastra 的核心优势
- TypeScript 原生:类型安全贯穿全链路,开发体验极佳
- Agent + Workflow 双模:开放决策用 Agent,确定逻辑用 Workflow
- Memory 系统领先:Observational Memory 是业界首创,有效解决长对话 context 溢出
- 部署灵活:从 Next.js 中间件到独立微服务,覆盖全场景
- 生态活跃:YC W25 背景,企业采用案例增多
当前限制
- Python 支持不完整:主要还是 TypeScript 框架
- 文档还在完善:部分高级功能的文档较简略
- 社区规模:相比 LangChain 小,第三方 Tool/Integration 较少
2026 年下半年展望
根据 Mastra 团队的公开路线图:
- Mastra Cloud:官方托管平台,类似 Vercel for AI Agents
- Multi-modal 增强:更好的图片/音频/视频输入输出支持
- Agent Marketplace:分享和发现预构建 Agent 的地方
- Enhanced Evaluation:内置 Agent 输出质量评估框架
实战资源
- 官方文档:https://mastra.ai/docs
- GitHub 仓库:https://github.com/mastra-ai/mastra
- 模板库:https://mastra.ai/templates(包含 Next.js、Slack Agent、GitHub PR Review 等)
- Discord 社区:https://discord.gg/BTYqqHKUrf
- YouTube 教程:https://www.youtube.com/@MastraAI
本文基于 Mastra v2026.6 的官方文档撰写,代码示例均已通过 TypeScript 类型检查。生产使用前请参考最新官方文档确认 API 是否有变动。
字数统计:约 8500 字