> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Hono 适配器 `@mastra/hono` 包提供了一个服务器适配器,用于通过 [Hono](https://hono.dev) 运行 Mastra。有关通用适配器概念(构造函数选项、初始化流程等),请参阅 [Server 适配器](https://mastra.zisheng.pro/docs/server/server-adapters)。 ## 安装 安装 Hono 适配器和 Hono 框架: **npm**: ```bash npm install @mastra/hono@latest hono ``` **pnpm**: ```bash pnpm add @mastra/hono@latest hono ``` **Yarn**: ```bash yarn add @mastra/hono@latest hono ``` **Bun**: ```bash bun add @mastra/hono@latest hono ``` ## 使用示例 ```typescript import { Hono } from 'hono' import { HonoBindings, HonoVariables, MastraServer } from '@mastra/hono' import { mastra } from './mastra' const app = new Hono<{ Bindings: HonoBindings; Variables: HonoVariables }>() const server = new MastraServer({ app, mastra }) await server.init() export default app ``` ## 构造函数参数 **app** (`Hono`): Hono 应用实例 **mastra** (`Mastra`): Mastra 实例 **prefix** (`string`): 路由路径前缀(例如:/api/v2) (Default: `''`) **openapiPath** (`string`): 提供 OpenAPI 规范的路径(例如:/openapi.json) (Default: `''`) **bodyLimitOptions** (`{ maxSize: number, onError: (err) => unknown }`): 请求正文大小限制 **streamOptions** (`{ redact?: boolean }`): 流脱敏配置。设为 true 时,会从流中移除敏感数据。 (Default: `{ redact: true }`) **customRouteAuthConfig** (`Map`): 按路由覆盖认证配置。键为 METHOD:PATH(例如:GET:/api/health)。值为 false 时路由公开;为 true 时需要认证。 **tools** (`Record`): 服务器可用的 Tool **taskStore** (`InMemoryTaskStore`): 用于 A2A(Agent-to-Agent)操作的任务存储 **mcpOptions** (`MCPOptions`): MCP 传输选项。对于 Cloudflare Workers 或 Vercel Edge 等无状态环境,请设置 serverless: true。 ## 添加自定义路由 直接向 Hono 应用添加路由: ```typescript import { Hono } from 'hono' import { HonoBindings, HonoVariables, MastraServer } from '@mastra/hono' const app = new Hono<{ Bindings: HonoBindings; Variables: HonoVariables }>() const server = new MastraServer({ app, mastra }) // Before init - runs before Mastra middleware app.get('/early-health', c => c.json({ status: 'ok' })) await server.init() // After init - has access to Mastra context app.get('/custom', c => { const mastraInstance = c.get('mastra') return c.json({ agents: Object.keys(mastraInstance.listAgents()) }) }) ``` > **提示:** 在 `init()` 前添加的路由会在没有 Mastra 上下文的情况下运行。请在 `init()` 后添加路由,以访问 Mastra 实例和请求上下文。 如需使用由 Mastra 管理的认证和 `requiresAuth` 等路由元数据,请优先使用 [`registerApiRoute()`](https://mastra.zisheng.pro/reference/server/register-api-route)。对于直接挂载到 `app` 上的原始 Hono 路由,请使用 `createAuthMiddleware()`: ```typescript import { Hono } from 'hono' import { createAuthMiddleware, HonoBindings, HonoVariables, MastraServer } from '@mastra/hono' import { mastra } from './mastra' const app = new Hono<{ Bindings: HonoBindings; Variables: HonoVariables }>() const server = new MastraServer({ app, mastra }) await server.init() app.get('/custom/protected', createAuthMiddleware({ mastra }), c => { const user = c.get('requestContext').get('user') return c.json({ user }) }) app.get('/custom/public', createAuthMiddleware({ mastra, requiresAuth: false }), c => { return c.json({ ok: true }) }) ``` ## 访问上下文 在 Hono 中间件和路由处理程序中,通过 `c.get()` 访问 Mastra 上下文: ```typescript app.get('/custom', async c => { const mastra = c.get('mastra') const requestContext = c.get('requestContext') const abortSignal = c.get('abortSignal') const agent = mastra.getAgent('myAgent') return c.json({ agent: agent.name }) }) ``` 可用的上下文键: | 键 | 说明 | | ----------------------- | --------------- | | `mastra` | Mastra 实例 | | `requestContext` | 请求上下文映射 | | `abortSignal` | 请求取消信号 | | `tools` | 可用的 Tool | | `taskStore` | 用于 A2A 操作的任务存储 | | `customRouteAuthConfig` | 按路由覆盖认证配置 | | `user` | 已认证的用户(如果已配置认证) | ## 添加中间件 在 `init()` 前或后添加 Hono 中间件: ```typescript import { Hono } from 'hono' import { HonoBindings, HonoVariables, MastraServer } from '@mastra/hono' const app = new Hono<{ Bindings: HonoBindings; Variables: HonoVariables }>() // Middleware before init app.use('*', async (c, next) => { console.log(`${c.req.method} ${c.req.url}`) await next() }) const server = new MastraServer({ app, mastra }) await server.init() // Middleware after init has access to Mastra context app.use('*', async (c, next) => { const mastra = c.get('mastra') await next() }) ``` ## 手动初始化 如需自定义中间件顺序,请分别调用各个方法,而非调用 `init()`。详情请参阅[手动初始化](https://mastra.zisheng.pro/docs/server/server-adapters)。 ## 示例 - [Hono 适配器](https://github.com/mastra-ai/mastra/tree/main/examples/server-hono-adapter):基础 Hono 服务器设置 ## 相关内容 - [Server 适配器](https://mastra.zisheng.pro/docs/server/server-adapters):共享的适配器概念 - [MastraServer 参考](https://mastra.zisheng.pro/reference/server/mastra-server):完整 API 参考 - [createRoute() 参考](https://mastra.zisheng.pro/reference/server/create-route):创建类型安全的自定义路由