본문으로 건너뛰기

호노 어댑터

그만큼@mastra/hono패키지는 Mastra를 실행하기 위한 서버 어댑터를 제공합니다.호노. 일반적인 어댑터 개념(생성자 옵션, 초기화 흐름 등)은 다음을 참조하세요.서버 어댑터.

설치
설치에 대한 직접 링크

Hono 어댑터 및 Hono 프레임워크를 설치합니다.

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

생성자 매개변수
생성자 매개변수에 대한 직접 링크

app:

Hono
Hono 앱 인스턴스

mastra:

Mastra
Mastra 인스턴스

prefix?:

string
= ''
경로 경로 접두사(예: /api/v2)

openapiPath?:

string
= ''
OpenAPI 명세를 제공할 경로(예: /openapi.json)

bodyLimitOptions?:

{ maxSize: number, onError: (err) => unknown }
요청 본문 크기 제한

streamOptions?:

{ redact?: boolean }
= { redact: true }
스트림 마스킹 구성입니다. true이면 스트림에서 민감한 데이터를 마스킹합니다.

customRouteAuthConfig?:

Map<string, boolean>
경로별 인증 재정의입니다. 키는 METHOD:PATH 형식입니다(예: GET:/api/health). 값이 false이면 경로가 공개되고, true이면 인증이 필요합니다.

tools?:

Record<string, Tool>
서버에서 사용할 수 있는 Tool

taskStore?:

InMemoryTaskStore
A2A(Agent-to-Agent) 작업을 위한 작업 저장소

mcpOptions?:

MCPOptions
MCP 전송 옵션입니다. Cloudflare Workers 또는 Vercel Edge 같은 상태 비저장 환경에서는 serverless: true로 설정하세요.

커스텀 경로 추가
커스텀 경로 추가에 대한 직접 링크

Hono 앱에 직접 경로를 추가하세요.

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() 전에 추가된 경로는 Mastra 컨텍스트 없이 실행됩니다. Mastra 인스턴스와 요청 컨텍스트에 접근하려면 init() 후에 경로를 추가하세요.

requiresAuth 같은 Mastra 관리 인증 및 경로 메타데이터가 필요하다면 registerApiRoute()를 사용하는 것이 좋습니다. app에 직접 마운트된 원시 Hono 경로에는 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 })
})

컨텍스트에 액세스
컨텍스트에 액세스에 대한 직접 링크

Hono 미들웨어 및 경로 핸들러에서 다음을 통해 Mastra 컨텍스트에 액세스합니다.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 })
})

사용 가능한 컨텍스트 키:

설명
mastraMastra 인스턴스
requestContext요청 컨텍스트 맵
abortSignal요청 취소 신호
tools사용 가능한 Tool
taskStoreA2A 작업용 작업 저장소
customRouteAuthConfig경로별 인증 재정의
user인증된 사용자(인증이 구성된 경우)

미들웨어 추가
미들웨어 추가에 대한 직접 링크

이전 또는 이후에 Hono 미들웨어 추가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()
})

수동 초기화
수동 초기화에 대한 직접 링크

사용자 정의 미들웨어 순서가 필요하다면 init() 대신 각 메서드를 개별적으로 호출하세요. 자세한 내용은 수동 초기화를 참조하세요.

예에 대한 직접 링크