mastra-hono
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMastra + Hono Development
Mastra + Hono 开发
Build production-ready AI agents, tools, and workflows using Mastra v1 Beta with Hono API servers. This skill covers the complete stack from agent definition to deployment.
Target version: Mastra v1 Beta (stable release expected January 2026)
使用Mastra v1 Beta搭配Hono API服务器构建可投入生产的AI Agent、工具与工作流。本技能涵盖从Agent定义到部署的完整技术栈。
目标版本:Mastra v1 Beta(预计2026年1月发布稳定版)
When to Use This Skill
适用场景
Use when:
- Creating Mastra agents with tools and memory
- Defining tools with Zod input/output schemas
- Building workflows with multi-step data flow
- Setting up Hono API servers with Mastra adapters
- Implementing agent networks for multi-agent collaboration
- Authoring MCP servers to expose agents/tools
- Integrating RAG and conversation memory
Do NOT use when:
- Working with Mastra stable (0.24.x) - patterns differ significantly
- Building non-AI web APIs (use Hono directly)
- Simple LLM calls without agents/tools
适用情况:
- 创建带工具与记忆功能的Mastra Agent
- 使用Zod输入/输出schema定义工具
- 构建多步骤数据流的工作流
- 通过Mastra适配器搭建Hono API服务器
- 实现多Agent协作的Agent网络
- 编写MCP服务器以暴露Agent/工具
- 集成RAG与对话记忆
不适用情况:
- 使用Mastra稳定版(0.24.x)—— 实现模式差异极大
- 构建非AI类Web API(直接使用Hono即可)
- 无需Agent/工具的简单LLM调用
Prerequisites
前置条件
- Node.js 22.13.0+ (required for v1 Beta)
- Package manager: npm, pnpm, or bun
- API keys: OpenAI, Anthropic, or other supported providers
bash
undefined- Node.js 22.13.0+(v1 Beta版本要求)
- 包管理器:npm、pnpm或bun
- API密钥:OpenAI、Anthropic或其他支持的服务商密钥
bash
undefinedInstall v1 Beta packages
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
undefinednpm install @mastra/core@beta @mastra/hono@beta
npm install @ai-sdk/openai # or other provider
npm install zod hono @hono/node-server
undefinedQuick Start
快速开始
Minimal Agent + Tool + Hono Server
最简Agent + 工具 + Hono服务器
typescript
// 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" };
},
});typescript
// 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
});typescript
// src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra";
import { weatherAgent } from "./agents/weather-agent.js";
export const mastra = new Mastra({
agents: { weatherAgent },
});typescript
// 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/generatetypescript
// 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" };
},
});typescript
// 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
});typescript
// src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra";
import { weatherAgent } from "./agents/weather-agent.js";
export const mastra = new Mastra({
agents: { weatherAgent },
});typescript
// 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/generateCore Patterns
核心模式
Agent Definition
Agent定义
typescript
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
},
});typescript
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
},
});Tool Signatures (v1 Beta - CRITICAL)
工具签名(v1 Beta - 重点)
typescript
// 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 signaturetypescript
// 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 signatureWorkflow Data Flow (CRITICAL)
工作流数据流(重点)
This is where most errors occur. See for complete patterns.
references/workflow-data-flow.mdtypescript
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();Schema matching rules:
| Rule | Description |
|---|---|
| Workflow input → Step 1 input | Must match exactly |
| Step N output → Step N+1 input | Must match exactly |
| Final step output → Workflow output | Must match exactly |
Data access in steps:
typescript
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 };
}这是最容易出错的部分。完整模式请参考。
references/workflow-data-flow.mdtypescript
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();Schema匹配规则:
| 规则 | 描述 |
|---|---|
| 工作流输入 → 步骤1输入 | 必须完全匹配 |
| 步骤N输出 → 步骤N+1输入 | 必须完全匹配 |
| 最后一步输出 → 工作流输出 | 必须完全匹配 |
步骤中的数据访问:
typescript
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 Server Setup
Hono服务器搭建
typescript
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}/startCustom route prefix:
typescript
const server = new MastraServer({
app,
mastra,
prefix: "/v1/ai" // Routes at /v1/ai/agents/...
});Custom API routes:
typescript
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 });
},
});typescript
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自定义路由前缀:
typescript
const server = new MastraServer({
app,
mastra,
prefix: "/v1/ai" // Routes at /v1/ai/agents/...
});自定义API路由:
typescript
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 });
},
});Common Mistakes Quick Reference
常见错误速查
| Topic | Wrong | Correct |
|---|---|---|
| Imports | | |
| Tools array | | |
| Memory context | | |
| Workflow data | | |
| After parallel | | |
| After branch | | |
| Nested agents | | |
| State mutation | | |
| v1 tool exec | | |
| 主题 | 错误做法 | 正确做法 |
|---|---|---|
| 导入 | | |
| 工具数组 | | |
| 记忆上下文 | | |
| 工作流数据 | | |
| 并行步骤后 | | |
| 分支步骤后 | | |
| 嵌套Agent | | |
| 状态变更 | | |
| v1工具执行 | | |
Scripts Reference
脚本参考
| Script | Purpose | Usage |
|---|---|---|
| Create new Mastra+Hono project | |
| Create agent with tools | |
| Create workflow with steps | |
| Create tool with schemas | |
| Validate step schema matching | |
| Detect v1/stable pattern mixing | |
| 脚本 | 用途 | 使用方式 |
|---|---|---|
| 创建新的Mastra+Hono项目 | |
| 创建带工具的Agent | |
| 创建带步骤的工作流 | |
| 创建带Schema的工具 | |
| 验证步骤Schema匹配 | |
| 检测v1/稳定版模式混用 | |
Additional Resources
额外资源
Reference Files
参考文件
- - Complete data flow patterns (CRITICAL)
references/workflow-data-flow.md - - Extended anti-patterns and fixes
references/common-mistakes.md - - Agent definition deep-dive
references/agent-patterns.md - - Tool signatures, wrappers
references/tool-patterns.md - - Server setup, routes, middleware
references/hono-server-patterns.md - - Vitest setup, mocking LLMs
references/testing-patterns.md - - Model Context Protocol authoring
references/mcp-server-patterns.md - - Multi-agent collaboration, A2A
references/agent-networks.md - - Vector stores, embeddings, memory
references/rag-memory-patterns.md - - Context networks for agent memory
references/context-network-memory.md
- - 完整数据流模式(重点)
references/workflow-data-flow.md - - 扩展反模式与修复方案
references/common-mistakes.md - - Agent定义深度解析
references/agent-patterns.md - - 工具签名、包装器
references/tool-patterns.md - - 服务器搭建、路由、中间件
references/hono-server-patterns.md - - Vitest配置、LLM模拟
references/testing-patterns.md - - Model Context Protocol编写
references/mcp-server-patterns.md - - 多Agent协作、A2A
references/agent-networks.md - - 向量存储、嵌入、记忆
references/rag-memory-patterns.md - - Agent记忆的上下文网络
references/context-network-memory.md
Asset Templates
资产模板
- - Agent boilerplate
assets/agent-template.ts - - Tool boilerplate (v1 signature)
assets/tool-template.ts - - Workflow boilerplate
assets/workflow-template.ts - - Hono+Mastra server setup
assets/hono-server-template.ts - - Test configuration
assets/vitest-setup-template.ts
- - Agent模板代码
assets/agent-template.ts - - 工具模板代码(v1签名)
assets/tool-template.ts - - 工作流模板代码
assets/workflow-template.ts - - Hono+Mastra服务器搭建模板
assets/hono-server-template.ts - - 测试配置模板
assets/vitest-setup-template.ts
External Documentation
外部文档
Limitations
限制条件
- Targets v1 Beta only; stable (0.24.x) patterns differ significantly
- Scripts require Deno runtime with appropriate permissions
- MCP server patterns require MCP-compatible clients
- Agent networks require all participating agents to be registered in same Mastra instance
- 仅针对v1 Beta版本;稳定版(0.24.x)的实现模式差异极大
- 脚本需要Deno运行时及相应权限
- MCP服务器模式需要兼容MCP的客户端
- Agent网络要求所有参与Agent注册在同一Mastra实例中
Related Skills
相关技能
- research-workflow - Deep dive research for AI agent design
- web-search - Real-time information retrieval for agents
- research-workflow - AI Agent设计的深度调研工作流
- web-search - 为Agent提供实时信息检索