> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Fastify 适配器 `@mastra/fastify` 包提供了一个 Server 适配器,用于通过 [Fastify](https://fastify.dev) 运行 Mastra。有关通用适配器概念(构造函数选项、初始化流程等),请参阅 [Server Adapters](https://mastra.zisheng.pro/docs/server/server-adapters)。 ## 安装 安装 Fastify 适配器和 Fastify 框架: **npm**: ```bash npm install @mastra/fastify@latest fastify ``` **pnpm**: ```bash pnpm add @mastra/fastify@latest fastify ``` **Yarn**: ```bash yarn add @mastra/fastify@latest fastify ``` **Bun**: ```bash bun add @mastra/fastify@latest fastify ``` ## 使用示例 ```typescript 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) (Default: `''`) **openapiPath** (`string`): 提供 OpenAPI 规范的路径(例如,/openapi.json) (Default: `''`) **bodyLimitOptions** (`BodyLimitOptions`): 请求正文大小限制 **streamOptions** (`StreamOptions`): 流脱敏配置。为 true(默认值)时,会在将流块发送给客户端之前,从中删除敏感数据(系统提示词、Tool 定义、API 密钥)。 (Default: `{ redact: true }`) **customRouteAuthConfig** (`Map`): 按路由覆盖身份验证。键为 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()`](https://mastra.zisheng.pro/reference/server/register-api-route)。对于直接挂载在 app 上的原始 Fastify 路由,请使用 `createAuthMiddleware()`: ```typescript 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()`。详见[手动初始化](https://mastra.zisheng.pro/docs/server/server-adapters)。 ## 示例 - [Fastify Adapter](https://github.com/mastra-ai/mastra/tree/main/examples/server-fastify-adapter):基本 Fastify Server 设置 ## 相关内容 - [Server Adapters](https://mastra.zisheng.pro/docs/server/server-adapters):共享的适配器概念 - [MastraServer Reference](https://mastra.zisheng.pro/reference/server/mastra-server):完整 API 参考 - [createRoute() Reference](https://mastra.zisheng.pro/reference/server/create-route):创建类型安全的自定义路由