mastra-ai/mastra · 上手攻略

  • 仓库:mastra-ai/mastra
  • 链接:https://github.com/mastra-ai/mastra
  • 分类:skill
  • 作者:Tom
  • 更新:2026-07-09

是什么

Mastra 是一个面向 AI 驱动应用与 Agents 的现代 TypeScript 框架,定位类似 Next.js之于 Web 开发——让 AI 应用的构建从草稿到生产都有一套统一、类型安全、可扩展的基础设施。

核心定位是一站式 AI 应用框架:不只是一个 Agent 库,而是一套包含 Agent、Workflow、Memory、RAG、MCP Server、Evals、Observability 的完整技术栈,全部用 TypeScript 写成,与 React/Next.js/Node 生态深度集成。

许可方面,核心框架采用 Apache 2.0,EE 目录(主要是 Auth 相关)采用 Mastra Enterprise License(可免费开发测试,生产使用需商业授权)。


解决什么问题

构建 AI 应用时,开发者通常面临以下碎片化困境:

  • 框架选择混乱:LangChain、LlamaIndex、Hassan 等各有一套抽象,互不兼容
  • 模型接入繁琐:每换一家 provider(OpenAI → Anthropic → Gemini)都要改代码
  • Workflow 与 Agent 二选一难:有的场景需要确定性流程(workflow),有的需要自主决策(agent),但在大多数框架里只能选一个
  • 生产级能力缺失:没有内置 eval、observability、human-in-the-loop,项目上线后无法迭代优化

Mastra 试图提供一个opinionated的答案:统一的 TypeScript 接口、标准化的项目结构、内置生产要素,让团队不再花时间在框架选型和胶水代码上。


快速安装

方式一:脚手架(推荐新手)

# 需要 Node.js 18+(推荐 22+)
npm create mastra@latest my-mastra-app

# 非交互式快速初始化(指定模型)
npm create mastra@latest my-mastra-app -- --default --llm openai

初始化向导会询问: - 项目名称(默认 my-mastra-app) - LLM Provider(默认 openai,可选 anthropic/groq/google/cerebras/mistral) - 是否启用 Observability

向导结束后自动生成项目结构:

my-mastra-app/
├── src/
│   ├── mastra/
│   │   ├── index.ts          # 入口,注册 agents/workflows
│   │   ├── agents/
│   │   │   └── weather-agent.ts
│   │   ├── tools/
│   │   │   └── weather-tool.ts
│   │   └── workflows/
│   │       └── weather-workflow.ts
│   └── index.ts
├── package.json
└── tsconfig.json

启动开发服务器:

npx bgproc start -n -w -- npm run dev
# 打开 http://localhost:4111 访问 Mastra Studio

方式二:手动安装(现有项目)

mkdir my-project && cd my-project
npm init -y
npm install @mastra/core@latest mastra@latest zod typescript @types/node

必须配置 package.json 添加 "type": "module",并创建 tsconfig.json(详见官方文档)。


核心用法

1. 创建 Agent

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

export const weatherAgent = new Agent({
  id: 'weather-agent',
  name: 'Weather Agent',
  instructions: `
    You are a helpful weather assistant. Use the weatherTool to fetch data.
    Include humidity, wind, and precipitation in responses.
  `,
  // 使用 provider/model 格式(Mastra 模型路由)
  model: 'openai/gpt-5.5',
  tools: { weatherTool },
})

⚠️ 注意:model 格式必须是 openai/<model>,不要用 openai:<model> 或传入 provider 对象。

2. 创建 Tool(必须用 createTool)

// src/mastra/tools/weather-tool.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

export const weatherTool = createTool({
  id: 'get-weather',
  description: 'Get current weather for a location',
  inputSchema: z.object({
    location: z.string().describe('City name'),
  }),
  outputSchema: z.object({
    output: z.string(),
  }),
  execute: async ({ location }) => {
    // 实际项目中调用天气 API
    return { output: `The weather in ${location} is sunny` }
  },
})

⚠️ 注意:Tool 必须通过 createTool() 创建,直接传 plain object 不会报错但工具不会被执行。

3. 注册到 Mastra 实例

// src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { weatherAgent } from './agents/weather-agent'

export const mastra = new Mastra({
  agents: { weatherAgent },
})

4. 调用 Agent

// run.mjs(Node 22.18+ 可直接运行 .ts)
import { mastra } from './src/mastra/index.ts'

const agent = mastra.getAgentById('weather-agent')
const response = await agent.generate('Weather in San Francisco')
console.log(response.text)

流式输出:

const stream = await agent.stream('Weather in San Francisco')
for await (const chunk of stream.textStream) {
  process.stdout.write(chunk)
}

5. Workflow(显式流程编排)

当任务需要确定性步骤而非自主 Agent 决策时,用 Workflow:

import { Workflow } from '@mastra/core/workflows'

const myWorkflow = new Workflow({
  name: 'order-processing',
  trigger: {},
})
  .then(stepA)    // 顺序执行
  .branch({       // 条件分支
    if: (ctx) => ctx.outputs.stepA.status === 'approved',
    then: stepB,
    else: stepC,
  })
  .parallel([stepD, stepE])  // 并行执行

6. Human-in-the-loop

Mastra 支持暂停 Workflow/Agent 并等待人工审批后再继续,利用 Storage 保持执行状态,适合需要人工审核的 AI 流程。


典型适用场景

场景 适用原因
企业 AI 应用(Next.js 全栈) 与 React/Next.js 深度集成,TypeScript-first
多模型产品 一次接入 40+ provider,轻易切换路由
需要 Human-in-the-loop 内置暂停/恢复机制,开箱即用
多 Agent 协作系统 Workflow 支持 Agent 组合,结构清晰
生产级 AI 产品 内置 Evals + Observability,无需自己搭建
快速原型验证 npm create mastra@latest 5 分钟出可运行 demo

坑与注意

  1. 模型格式是 provider/model 不是 provider:model:文档明确指出要用斜杠格式(如 openai/gpt-5.5),传 provider 对象或用冒号格式均无效。

  2. Tool 必须用 createTool():plain object 定义会被静默忽略,是最常见的"工具不工作"原因。

  3. Node.js 版本要求:官方推荐 Node 22.18+(可直接运行 TS),部分场景用 bunx 而非 npm 体验更好。

  4. EE 目录有企业授权:Auth、SSO 等功能在 ee/ 目录下,使用这些功能需要商业许可,评估时注意区分。

  5. Observability 平台是付费的:免费版有基础指标,生产级 tracing 需要 Mastra Cloud 订阅。

  6. Mastra Studio 依赖本地服务:启动开发服务器后才能用 http://localhost:4111,不是浏览器插件或在线工具。

  7. 包名 @mastra/core vs mastra:新项目装 mastra,纯库使用装 @mastra/core


与同类对比

Mastra LangChain / LangGraph LlamaIndex AutoGen
语言 TypeScript Python/JS Python Python
类型安全 ✅ 原生 TS ⚠️ JS SDK 较弱 ❌ Python dynamic
Workflow + Agent ✅ 统一 ⚠️ LangGraph 才行 ⚠️
Model Router ✅ 40+ provider ⚠️ 需自行封装
Human-in-the-loop ✅ 内置 ⚠️ 需自行实现 ⚠️
Evals 内置 ⚠️ LangSmith 付费
上手难度
生产成熟度 ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐

一句话总结:如果你用 TypeScript/Node.js 构建 AI 应用,Mastra 是目前最顺畅的"全栈 AI 框架";如果你用 Python 或需要极度灵活的自定义能力,LangChain 生态更成熟。


一句话推荐结论

Mastra 是 TypeScript 生态里最接近"AI 应用的 Next.js"的框架——如果你在 Node.js 侧构建生产级 AI 产品,它能让你少走 80% 的框架整合弯路。