用 Mastra 搭 TypeScript 全栈 AI Agent(workflows + 评测 + 可观测一条龙)
如果你团队本来就用 TypeScript 写前后端,最别扭的事就是:为了跑 Agent,被迫再起一套 Python 栈。Mastra 是 2026 年最火的 TypeScript 优先 Agent 框架——它把 agents、workflows、evaluations、observability 打包进同一个框架,专为生产级 JS/TS 应用而生。本教程带你在熟悉的 Node 栈里,从零跑通一个带持久化状态、能挂可观测面板的 Agent。
先搞懂:Mastra 解决什么问题?
用一句话理解:Mastra 像是「Agent 领域的 Next.js」——约定优于配置,把原型阶段之后才冒出来的麻烦事(工作流编排、评测、可观测、断点续跑)做成开箱即用的内建能力。
| 能力 | 说明 | 对你意味着什么 |
|---|---|---|
| Agents | 带指令与工具的 LLM 封装 | 一个文件定义一个人设 |
| Workflows | 多步骤有向编排 | 复杂流程可控、可重试 |
| Evals | 内置评测集 | 上线前先量质量 |
| Observability | 追踪 + 调试面板 | 生产出问题能定位 |
Mastra 较新,生态仍在长。若团队已深度绑定 Python,Pydantic AI 或 LangGraph 可能更顺手。Mastra 的最佳场景是:TS 团队要的是「batteries-included」一条龙,不想自己拼监控和评测。
Step 1:初始化项目
确认本地 Node 18+,用官方脚手架创建(会问你模型提供方,选 OpenAI 或 Anthropic 均可):
# 创建项目(交互式选模型)
npx create-mastra@latest my-agent
cd my-agent
# 安装依赖
npm install
# 启动开发面板(自带 Playground + 可观测 UI)
npm run dev
Step 2:定义一个 Agent
在 `src/mastra/agents/` 下新建一个 Agent,写清指令、模型和工具:
// src/mastra/agents/support.ts
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
export const supportAgent = new Agent({
name: "售后小助手",
instructions: "你是电商售后客服,只回答退款、物流、换货问题,语气亲切。",
model: openai("gpt-5.6"),
});
模型路由上百种。Mastra 通过 Vercel AI SDK 对接数百个模型,换个模型只是改 `openai("...")` 这一行,业务代码不动。
Step 3:给 Agent 接工具
Agent 不会凭空知道订单状态,给它一个查询工具:
// src/mastra/tools/order.ts
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const queryOrder = createTool({
id: "query-order",
description: "按订单号查物流状态",
inputSchema: z.object({ orderId: z.string() }),
execute: async ({ orderId }) => {
const res = await fetch(`https://api.shop.com/orders/${orderId}`);
return res.json();
},
});
// 把工具挂到 Agent:tools: { queryOrder }
Step 4:用 Workflow 串多步骤
单 Agent 不够时,用 Workflow 把「理解意图 → 查订单 → 生成回复 → 人工确认」编排成有向步骤:
// src/mastra/workflows/refund.ts
import { Workflow } from "@mastra/core/workflows";
import { step1, step2 } from "./steps";
export const refundFlow = new Workflow({
name: "退款流程",
triggerSchema: z.object({ msg: z.string() }),
})
.step(step1) // 意图理解
.step(step2) // 查订单 + 生成回复
.commit();
// 支持挂起/恢复(suspend-and-resume):敏感步骤可等人确认再继续
Workflow 的价值在「可恢复」。长流程跑到一半崩了,能从断点续跑,而不是从头再来——这是生产级 Agent 和 demo 的分水岭。
Step 5:加 Evals 在上线前量质量
// src/mastra/evals/tone.ts
import { ToneConsistencyMetric } from "@mastra/evals/llm";
const metric = new ToneConsistencyMetric();
const result = await metric.measure(
"请查下订单 A123 的物流",
"您的订单 A123 已发货,预计明天到达~"
);
console.log(result.score); // 0~1,越接近 1 越符合人设
Step 6:挂可观测面板
Mastra 内置 tracing,把每次 Agent 调用的步骤、token、耗时都记录下来:
// mastra.config.ts
export default {
telemetry: {
serviceName: "my-agent",
export: { type: "console" }, // 也可接 Otel 后端
},
};
// 运行后在 Playground 的 Traces 页看完整调用链
Step 7:部署并对外提供服务
# 构建并部署到 Mastra Cloud(或自带 Node 服务)
npm run build
npx mastra deploy
# 部署后会拿到一个可调用端点,前端直接 fetch 即可
const res = await fetch("https://your-agent.mastra.ai/api/agents/support", {
method: "POST",
body: JSON.stringify({ messages: [{ role: "user", content: "查物流" }] }),
});
常见问题速查
| 你遇到的现象 | 大概率原因 & 解决 |
|---|---|
| Playground 打不开 | `npm run dev` 没起,或端口被占用 |
| Agent 不调工具 | 工具没在 Agent 的 tools 里注册,或 description 太模糊 |
| Eval 分数忽高忽低 | 模型本身有随机性,固定 temperature 再对比 |
| 想换 Python 生态 | Mastra 是 TS 优先,重模型逻辑可迁 Pydantic AI |