| name | mastra-patterns |
| description | Mastra Agent/Tool/Workflow 定义模式、config-as-data 函数式壳、Concierge/Vertical Agent、注册中心、流式响应、自定义路由。编写 src/mastra/ 下代码前必读。 |
Mastra 二次开发模式
Agent 框架 = Mastra(ADR-0007,无沉没成本 bake-off 后确认)。垂类由声明式 Solution Pack manifest 驱动,非每垂类写死代码。
两类运行时 Agent(ADR-0006)
- Concierge Agent:每 Account 一个,supervisor,承接对话+记忆,委派 Vertical Agent。只服务主动对话链路。
- Vertical Agent:每 Solution Pack 一个,只读专家,挂本包只读 Tool + Vertical Skill + Knowledge。被 Concierge(主动)或 Workflow(被动,直连)调用。
config-as-data:函数式 Agent 壳(ADR-0007)
不要每垂类写死一个 Agent。定义少数 agent 壳,其 instructions/tools/model 是 runtimeContext 的函数,按 Pack Manifest 在运行时解析:
new Agent({
id: "vertical-agent-shell",
model: ({ runtimeContext }) =>
resolveModel(packRegistry.get(runtimeContext.get("packId")).model),
tools: ({ runtimeContext }) =>
packRegistry.get(runtimeContext.get("packId")).tools,
instructions: ({ runtimeContext }) =>
packRegistry.get(runtimeContext.get("packId")).instructions,
});
manifest 加载前 Zod 强校验;只引用白名单工具、不内联代码/密钥(ADR-0014)。
Agent 定义
id kebab-case 全局唯一;instructions 中文,含输入/输出/工具/边界
model 用 resolveModel() 字符串路由——绝不硬编码厂商 SDK(避免硬编码模型字面量,优先 env/manifest)
- Agent 只持只读工具——副作用归 Workflow
Tool 创建
- 文件:
src/mastra/tools/<category>/<tool-id>.ts,zod inputSchema/outputSchema
- 所有外部 HTTP 调用必须 AbortController 超时(10s)
- 租户上下文从
requestContext 取 tenantId+accountId,绝不用客户端传入的(ADR-0014)
- Vertical Skill = 经 MCP 发现 + 委派独立推理端点,按租户上下文解析模型变体(ADR-0008)
Workflow 编排
- 每 Step 独立
inputSchema/outputSchema,output→input 显式衔接
- Workflow 承担一切副作用:写库/推送;下发设备命令需显式 Grant + 审计(ADR-0006/0014)
- LLM 调用走
mastra.getAgent('id').generate(),不裸 API
createRun({ resourceId }) 带三层租户上下文 tenant:{t}:account:{a}:user:{u}
注册中心 (src/mastra/index.ts)
- Agent/Workflow 显式注册,不文件扫描;环境变量一次性读取
- 长连接组件(Tap 连接器/MQTT bridge)通过副作用 import 启动
流式响应
const stream = await agent.stream(message, {
memory: { thread: conversationId, resource: resourceId },
});
return new Response(stream.toDataStreamResponse().body, {
headers: { "Content-Type": "text/event-stream" },
});
自定义路由
registerApiRoute("/webhooks/iot-event", {
method: "POST",
handler: async (c) => {
},
});
Mastra 保留 /api/ 前缀,自定义路由用其他前缀。