跳至主要內容

Hono adapter

@mastra/hono 套件提供 server adapter,讓 Mastra 可配合 Hono 運行。有關一般 adapter 概念(constructor 選項、初始化流程等),請參閱 Server adapter

安裝
安裝 的直接連結

安裝 Hono adapter 及 Hono framework:

npm install @mastra/hono@latest hono

使用範例
使用範例 的直接連結

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

Constructor 參數
Constructor 參數 的直接連結

app:

Hono
Hono app instance

mastra:

Mastra
Mastra instance

prefix?:

string
= ''
Route 路徑前綴(例如 /api/v2

openapiPath?:

string
= ''
提供 OpenAPI 規格的路徑(例如 /openapi.json

bodyLimitOptions?:

{ maxSize: number, onError: (err) => unknown }
Request body 大小限制

streamOptions?:

{ redact?: boolean }
= { redact: true }
Stream 遮蔽設定。設為 true 時,會從 stream 遮蔽敏感資料。

customRouteAuthConfig?:

Map<string, boolean>
各 route 的 auth 覆寫設定。Key 為 METHOD:PATH(例如 GET:/api/health)。值為 false 時 route 會公開,true 則需要 auth。

tools?:

Record<string, Tool>
Server 可用的 Tool

taskStore?:

InMemoryTaskStore
A2A(Agent-to-Agent)操作的 task store

mcpOptions?:

MCPOptions
MCP transport 選項。對 Cloudflare Workers 或 Vercel Edge 等無狀態環境,請設定 serverless: true

新增自訂 route
新增自訂 route 的直接連結

直接將 route 新增至 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()) })
})
提示

init() 前新增的 route 會在沒有 Mastra context 的情況下運行。如要存取 Mastra instance 及 request context,請在 init() 後新增 route。

如需 Mastra 管理的 auth,以及 requiresAuth 等 route metadata,建議使用 registerApiRoute()。對於直接掛載到 app 的原始 Hono route,請使用 createAuthMiddleware()

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

存取 context
存取 context 的直接連結

在 Hono middleware 及 route handler 中,透過 c.get() 存取 Mastra context:

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

可用的 context key:

Key說明
mastraMastra instance
requestContextRequest context map
abortSignalRequest 取消訊號
tools可用的 Tool
taskStoreA2A 操作的 task store
customRouteAuthConfig各 route 的 auth 覆寫設定
user已驗證的使用者(如已設定 auth)

新增 middleware
新增 middleware 的直接連結

init() 前或後新增 Hono middleware:

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

手動初始化
手動初始化 的直接連結

如要自訂 middleware 順序,請分別呼叫各個 method,而非使用 init()。詳情請參閱手動初始化

範例
範例 的直接連結