跳至主要內容

Fastify adapter

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

安裝
安裝 的直接連結

安裝 Fastify adapter 及 Fastify framework:

npm install @mastra/fastify@latest fastify

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

server.ts
import Fastify from 'fastify'
import { MastraServer } from '@mastra/fastify'
import { mastra } from './mastra'

const app = Fastify({ logger: true })
const server = new MastraServer({ app, mastra })

await server.init()

app.listen({ port: 3000 }, (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server running on ${address}`)
})

Constructor 參數
Constructor 參數 的直接連結

app:

FastifyInstance
Fastify app instance

mastra:

Mastra
Mastra instance

prefix?:

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

openapiPath?:

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

bodyLimitOptions?:

BodyLimitOptions
Request body 大小限制

streamOptions?:

StreamOptions
= { redact: true }
Stream 遮蔽設定。設為 true(預設值)時,會先從 stream chunk 遮蔽敏感資料(system prompt、Tool 定義、API key),才傳送至 client。

customRouteAuthConfig?:

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

tools?:

ToolsInput
Server 可用的 Tool

taskStore?:

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

mcpOptions?:

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

保護原始 route
保護原始 route 的直接連結

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

server.ts
import Fastify from 'fastify'
import { createAuthMiddleware, MastraServer } from '@mastra/fastify'
import { mastra } from './mastra'

const app = Fastify()
const server = new MastraServer({ app, mastra })

await server.init()

app.get('/custom/protected', { preHandler: createAuthMiddleware({ mastra }) }, async request => {
const user = request.requestContext.get('user')
return { user }
})

app.get(
'/custom/public',
{ preHandler: createAuthMiddleware({ mastra, requiresAuth: false }) },
async () => {
return { ok: true }
},
)

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

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

範例
範例 的直接連結