跳到主要内容

Fastify 适配器

@mastra/fastify 包提供了一个 Server 适配器,用于通过 Fastify 运行 Mastra。有关通用适配器概念(构造函数选项、初始化流程等),请参阅 Server Adapters

安装
安装的直接链接

安装 Fastify 适配器和 Fastify 框架:

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

构造函数参数
构造函数参数的直接链接

app:

FastifyInstance
Fastify app 实例

mastra:

Mastra
Mastra 实例

prefix?:

string
= ''
路由路径前缀(例如,/api/v2

openapiPath?:

string
= ''
提供 OpenAPI 规范的路径(例如,/openapi.json

bodyLimitOptions?:

BodyLimitOptions
请求正文大小限制

streamOptions?:

StreamOptions
= { redact: true }
流脱敏配置。为 true(默认值)时,会在将流块发送给客户端之前,从中删除敏感数据(系统提示词、Tool 定义、API 密钥)。

customRouteAuthConfig?:

Map<string, boolean>
按路由覆盖身份验证。键为 METHOD:PATH(例如,GET:/api/health)。值为 false 时路由公开,值为 true 时需要身份验证。

tools?:

ToolsInput
Server 可用的 Tool

taskStore?:

InMemoryTaskStore
用于 A2A(Agent-to-Agent)操作的任务存储

mcpOptions?:

MCPOptions
MCP 传输选项。对于 Cloudflare Workers 或 Vercel Edge 等无状态环境,请设置 serverless: true

保护原始路由
保护原始路由的直接链接

若要使用 Mastra 管理的身份验证和 requiresAuth 等路由元数据,请优先使用 registerApiRoute()。对于直接挂载在 app 上的原始 Fastify 路由,请使用 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 }
},
)

手动初始化
手动初始化的直接链接

如需自定义中间件顺序,请分别调用每个方法,而不是调用 init()。详见手动初始化

示例
示例的直接链接