> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Hono 轉接器 `@mastra/hono` 套件提供了一個伺服器轉接器,用於透過 [Hono](https://hono.dev) 執行 Mastra。有關通用轉接器概念(建構函式選項、初始化流程等),請參閱 [Server 轉接器](https://mastra.zisheng.pro/zh-TW/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/zh-TW/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 middleware 和路由處理常式中,透過 `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` | 已認證的使用者(如果已設定認證) | ## 新增 middleware 在 `init()` 前或後新增 Hono middleware: ```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() }) ``` ## 手動初始化 如需自訂 middleware 順序,請分別呼叫各個方法,而非呼叫 `init()`。詳情請參閱[手動初始化](https://mastra.zisheng.pro/zh-TW/docs/server/server-adapters)。 ## 範例 - [Hono 轉接器](https://github.com/mastra-ai/mastra/tree/main/examples/server-hono-adapter):基礎 Hono 伺服器設定 ## 相關內容 - [Server 轉接器](https://mastra.zisheng.pro/zh-TW/docs/server/server-adapters):共享的轉接器概念 - [MastraServer 參考](https://mastra.zisheng.pro/zh-TW/reference/server/mastra-server):完整 API 參考 - [createRoute() 參考](https://mastra.zisheng.pro/zh-TW/reference/server/create-route):建立類型安全的自訂路由