Skip to main content

Hono 适配器

🌐 Hono Adapter

@mastra/hono 包提供了一个用于在 Hono 上运行 Mastra 的服务器适配器。

🌐 The @mastra/hono package provides a server adapter for running Mastra with Hono.

info

有关一般适配器概念(构造函数选项、初始化流程等),请参见 服务器适配器

🌐 For general adapter concepts (constructor options, initialization flow, etc.), see Server Adapters.

安装
Direct link to 安装

🌐 Installation

安装 Hono 适配器和 Hono 框架:

🌐 Install the Hono adapter and Hono framework:

npm install @mastra/hono@latest hono

使用示例
Direct link to 使用示例

🌐 Usage example

server.ts
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;

构造函数参数
Direct link to 构造函数参数

🌐 Constructor parameters

app:

Hono
Hono app instance

mastra:

Mastra
Mastra instance

prefix?:

string
= ''
Route path prefix (e.g., `/api/v2`)

openapiPath?:

string
= ''
Path to serve OpenAPI spec (e.g., `/openapi.json`)

bodyLimitOptions?:

{ maxSize: number, onError: (err) => unknown }
Request body size limits

streamOptions?:

{ redact?: boolean }
= { redact: true }
Stream redaction config. When true, redacts sensitive data from streams.

customRouteAuthConfig?:

Map<string, boolean>
Per-route auth overrides. Keys are `METHOD:PATH` (e.g., `GET:/api/health`). Value `false` makes route public, `true` requires auth.

tools?:

Record<string, Tool>
Available tools for the server

taskStore?:

InMemoryTaskStore
Task store for A2A (Agent-to-Agent) operations

mcpOptions?:

MCPOptions
MCP transport options. Set `serverless: true` for stateless environments like Cloudflare Workers or Vercel Edge.

添加自定义路由
Direct link to 添加自定义路由

🌐 Adding custom routes

直接向 Hono 应用添加路由:

🌐 Add routes directly to the Hono app:

server.ts
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()) });
});
tip

init() 之前添加的路由在没有 Mastra 上下文的情况下运行。在 init() 之后添加路由以访问 Mastra 实例和请求上下文。

🌐 Routes added before init() run without Mastra context. Add routes after init() to access the Mastra instance and request context.

访问上下文
Direct link to 访问上下文

🌐 Accessing context

在 Hono 中间件和路由处理程序中,通过 c.get() 访问 Mastra 上下文:

🌐 In Hono middleware and route handlers, access Mastra context via c.get():

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 });
});

可用的上下文键:

🌐 Available context keys:

描述
mastraMastra 实例
requestContext请求上下文映射
abortSignal请求取消信号
tools可用工具
taskStoreA2A 操作的任务存储
customRouteAuthConfig每条路由的认证覆盖
user已认证用户(如果已配置认证)

添加中间件
Direct link to 添加中间件

🌐 Adding middleware

init() 之前或之后添加 Hono 中间件:

🌐 Add Hono middleware before or after init():

server.ts
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();
});

手动初始化
Direct link to 手动初始化

🌐 Manual initialization

对于自定义中间件顺序,请分别调用每个方法,而不是使用 init()。详情请参阅手动初始化

🌐 For custom middleware ordering, call each method separately instead of init(). See manual initialization for details.

示例
Direct link to 示例

🌐 Examples

🌐 Related