关于 mastra-hono
mastra-hono 是面向 Mastra v1 Beta 与 Hono 的开发技能,指导开发者构建 Agent、工具、工作流及 API 服务,并提供脚手架和模式参考。
主要功能
- 01定义 Mastra Agent 与工具
- 02构建多步骤工作流
- 03通过 Hono 提供 API 服务
- 04配置多 Agent 网络
- 05参考 MCP 服务实现模式
- 06提供脚手架与校验脚本
适用场景
- 01创建带工具和记忆的 Agent
- 02为工作流配置步骤与数据流
- 03搭建 Mastra 与 Hono API
- 04为 MCP 客户端编写 MCP 服务
MCP 相关
提供通过 Mastra 暴露 Agent 和工具的 MCP 服务编写指导;所生成的 MCP 服务面向兼容 MCP 的客户端。
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jwynia/ agent-skills --skill mastra-hono安装后在 Claude Code 中输入/mastra-hono确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/agent-template.tshono-server-template.tstool-template.tsvitest-setup-template.tsworkflow-template.tsreferences/agent-networks.mdagent-patterns.mdcommon-mistakes.mdcontext-network-memory.mdhono-server-patterns.mdmcp-server-patterns.mdrag-memory-patterns.mdtesting-patterns.mdtool-patterns.mdworkflow-data-flow.mdscripts/check-version-patterns.tsscaffold-agent.tsscaffold-project.tsscaffold-tool.tsscaffold-workflow.tsvalidate-workflow-schemas.ts详细介绍
Mastra + Hono 开发
使用 Mastra v1 Beta 和 Hono API 服务,构建可用于生产环境的 AI Agent、工具和工作流。本技能涵盖从 Agent 定义到部署的完整技术栈。
目标版本:Mastra v1 Beta(预计于 2026 年 1 月发布稳定版本)
何时使用本技能
适用于:
- 创建带有工具和记忆功能的 Mastra Agent
- 使用 Zod 输入/输出架构定义工具
- 构建具有多步骤数据流的工作流
- 使用 Mastra 适配器设置 Hono API 服务
- 实现多 Agent 协作的 Agent 网络
- 编写用于公开 Agent/工具的 MCP 服务
- 集成 RAG 和对话记忆
不适用于:
- 使用 Mastra 稳定版(0.24.x)——模式存在显著差异
- 构建非 AI Web API(直接使用 Hono)
- 不涉及 Agent/工具的简单 LLM 调用
前置条件
- Node.js 22.13.0+(v1 Beta 必需)
- 包管理器:npm、pnpm 或 bun
- API 密钥:OpenAI、Anthropic 或其他受支持的提供商
# Install v1 Beta packages
npm install @mastra/core@beta @mastra/hono@beta
npm install @ai-sdk/openai # or other provider
npm install zod hono @hono/node-server
快速开始
最小化 Agent + 工具 + Hono 服务
// src/mastra/tools/weather-tool.ts
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const weatherTool = createTool({
id: "get-weather",
description: "Fetches current weather for a location",
inputSchema: z.object({
location: z.string().describe("City name, e.g., 'Seattle'"),
}),
outputSchema: z.object({
temperature: z.number(),
conditions: z.string(),
}),
// v1 Beta signature: (inputData, context)
execute: async (inputData, context) => {
const { location } = inputData;
const { abortSignal } = context;
if (abortSignal?.aborted) throw new Error("Aborted");
// Fetch weather data...
return { temperature: 72, conditions: "sunny" };
},
});
// src/mastra/agents/weather-agent.ts
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { weatherTool } from "../tools/weather-tool.js";
export const weatherAgent = new Agent({
name: "weather-agent",
instructions: "You are a helpful weather assistant.",
model: openai("gpt-4o-mini"),
tools: { weatherTool }, // Object, not array
});
// src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra";
import { weatherAgent } from "./agents/weather-agent.js";
export const mastra = new Mastra({
agents: { weatherAgent },
});
// src/index.ts
import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { MastraServer } from "@mastra/hono";
import { mastra } from "./mastra/index.js";
const app = new Hono();
const server = new MastraServer({ app, mastra });
await server.init();
app.get("/", (c) => c.text("Mastra + Hono Server"));
serve({ fetch: app.fetch, port: 3000 });
console.log("Server running at http://localhost:3000");
// Agent endpoint: POST /api/agents/weather-agent/generate
核心模式
Agent 定义
import { Agent } from "@mastra/core/agent";
const agent = new Agent({
name: "my-agent", // Required: unique identifier
instructions: "You are a helpful assistant.", // Required: system prompt
model: openai("gpt-4o-mini"), // Required: LLM model
tools: { weatherTool, searchTool }, // Optional: object with named tools
});
// Model routing (1113+ models from 53 providers)
model: "openai/gpt-4o-mini"
model: "anthropic/claude-3-5-sonnet"
model: "google/gemini-2.5-flash"
// Model fallbacks for resilience
model: [
{ model: "anthropic/claude-3-opus", maxRetries: 3 },
{ model: "openai/gpt-4o", maxRetries: 2 },
{ model: "google/gemini-pro", maxRetries: 1 },
]
// Agent execution with memory
const response = await agent.generate("Remember my name is Alex", {
memory: {
thread: "conversation-123", // Isolates conversation
resource: "user-456", // Associates with user
},
});
工具签名(v1 Beta - 至关重要)
// v1 Beta: execute(inputData, context)
execute: async (inputData, context) => {
const { location } = inputData; // First parameter: parsed input
const { mastra, runtimeContext, abortSignal } = context; // Second: context
// Access nested agents via mastra
const helper = mastra?.getAgent("helperAgent");
// Always check abort signal for long operations
if (abortSignal?.aborted) throw new Error("Aborted");
return { temperature: 72, conditions: "sunny" };
}
// WRONG for v1 Beta:
execute: async ({ context }) => { ... } // This is stable 0.24.x signature
工作流数据流(至关重要)
大多数错误都发生在这里。完整模式请参阅 references/workflow-data-flow.md。
import { createWorkflow, createStep } from "@mastra/core/workflows";
const step1 = createStep({
id: "step-1",
inputSchema: z.object({ message: z.string() }),
outputSchema: z.object({ formatted: z.string() }),
execute: async ({ inputData }) => {
// inputData = workflow input (for first step)
return { formatted: inputData.message.toUpperCase() };
},
});
const step2 = createStep({
id: "step-2",
inputSchema: z.object({ formatted: z.string() }), // MUST match step1 output
outputSchema: z.object({ emphasized: z.string() }),
execute: async ({ inputData }) => {
// inputData = step1's return value directly
return { emphasized: `${inputData.formatted}!!!` };
},
});
const workflow = createWorkflow({
id: "my-workflow",
inputSchema: z.object({ message: z.string() }), // MUST match step1 input
outputSchema: z.object({ emphasized: z.string() }), // MUST match final output
})
.then(step1)
.then(step2)
.commit();
架构匹配规则:
| 规则 | 说明 |
|---|---|
| 工作流输入 → 步骤 1 输入 | 必须完全匹配 |
| 步骤 N 输出 → 步骤 N+1 输入 | 必须完全匹配 |
| 最后一步输出 → 工作流输出 | 必须完全匹配 |
步骤中的数据访问:
execute: async ({
inputData, // Previous step's output (or workflow input for step 1)
getStepResult, // Access ANY step's output by ID
getInitData, // Get original workflow input
mastra, // Access agents, tools, storage
}) => {
const step1Result = getStepResult("step-1");
const originalInput = getInitData();
return { result: inputData.formatted };
}
Hono 服务设置
import { MastraServer } from "@mastra/hono";
const app = new Hono();
const server = new MastraServer({ app, mastra });
await server.init();
// Endpoints auto-registered:
// POST /api/agents/{agent-name}/generate
// POST /api/agents/{agent-name}/stream
// POST /api/workflows/{workflow-id}/start
自定义路由前缀:
const server = new MastraServer({
app,
mastra,
prefix: "/v1/ai" // Routes at /v1/ai/agents/...
});
自定义 API 路由:
import { registerApiRoute } from "@mastra/core/server";
registerApiRoute("/my-custom-route", {
method: "POST",
handler: async (c) => {
const mastra = c.get("mastra");
const agent = mastra.getAgent("my-agent");
const result = await agent.generate("Hello");
return c.json({ response: result.text });
},
});
常见错误速查
| 主题 | 错误写法 | 正确写法 |
|---|---|---|
| 导入 | import { Agent } from "@mastra/core" | import { Agent } from "@mastra/core/agent" |
| 工具数组 | tools: [tool1, tool2] | tools: { tool1, tool2 } |
| 记忆上下文 | { threadId: "123" } | { memory: { thread: "123", resource: "user" } } |
| 工作流数据 | context.steps.step1.output | inputData 或 getStepResult("step-1") |
| 并行之后 | inputData.result | inputData["step-id"].result |
| 分支之后 | inputData.result | inputData["step-id"]?.result(可选) |
| 嵌套 Agent | import agent; agent.generate() | mastra.getAgent("name").generate() |
| 状态变更 | state.counter++ | setState({ ...state, counter: state.counter + 1 }) |
| v1 工具执行 | execute: async ({ context }) | execute: async (inputData, context) |
脚本参考
| 脚本 | 用途 | 用法 |
|---|---|---|
scaffold-project.ts | 创建新的 Mastra+Hono 项目 | deno run --allow-all scripts/scaffold-project.ts --name my-project |
scaffold-agent.ts | 创建带有工具的 Agent | deno run --allow-all scripts/scaffold-agent.ts --name weather |
scaffold-workflow.ts | 创建包含多个步骤的工作流 | deno run --allow-all scripts/scaffold-workflow.ts --name process-data |
scaffold-tool.ts | 创建带有架构的工具 | deno run --allow-all scripts/scaffold-tool.ts --name fetch-weather |
validate-workflow-schemas.ts | 验证步骤架构是否匹配 | deno run --allow-read scripts/validate-workflow-schemas.ts ./src/mastra/workflows/ |
check-version-patterns.ts | 检测 v1/稳定版模式混用 | deno run --allow-read scripts/check-version-patterns.ts ./src/mastra/ |
其他资源
参考文件
references/workflow-data-flow.md- 完整的数据流模式(重要)references/common-mistakes.md- 更多反模式及修正方法references/agent-patterns.md- 深入解析 Agent 定义references/tool-patterns.md- 工具签名、包装器references/hono-server-patterns.md- 服务设置、路由、中间件references/testing-patterns.md- Vitest 设置、模拟大模型references/mcp-server-patterns.md- Model Context Protocol 编写references/agent-networks.md- 多 Agent 协作、A2Areferences/rag-memory-patterns.md- 向量存储、嵌入、记忆references/context-network-memory.md- 用于 Agent 记忆的上下文网络
资源模板
assets/agent-template.ts- Agent 样板代码assets/tool-template.ts- 工具样板代码(v1 签名)assets/workflow-template.ts- 工作流样板代码assets/hono-server-template.ts- Hono+Mastra 服务设置assets/vitest-setup-template.ts- 测试配置
外部文档
限制
- 仅针对 v1 Beta;稳定版(0.24.x)的模式存在显著差异
- 脚本需要在具备相应权限的 Deno 运行时中运行
- MCP 服务模式需要兼容 MCP 的客户端
- Agent 网络要求所有参与的 Agent 都注册在同一个 Mastra 实例中
相关技能
- research-workflow - 深入研究 AI Agent 设计
- web-search - 为 Agent 实时检索信息
评论
支持 Markdown