服务器 Adapter
服务器 Adapter 允许你使用自己的 HTTP 服务器运行 Mastra,而不是使用 mastra build 生成的 Hono 服务器。它们让你更细致地控制服务器设置,包括自定义中间件顺序、身份验证、日志记录和部署配置。仍可将 Mastra 集成到任何 Node.js 应用,而无需改变 Agent 或 Workflow 的执行方式。
服务器 Adapter 使用传入的 mastra 实例,不会运行基于文件的发现。请在代码中向该实例注册 Agent。要使用基于文件的 Agent,请通过 mastra dev 或 mastra build 将 Mastra 作为独立服务器运行。
何时使用服务器 Adapter何时使用服务器 Adapter的直接链接
- 希望将 Mastra 端点自动添加到现有应用
- 需要直接访问服务器实例以进行自定义配置
- 团队更喜欢使用其他服务器框架,而不是
mastra build创建的 Hono 服务器。
对于没有自定义服务器要求的部署,请改用 mastra build。它会配置服务器设置并注册中间件,还会根据项目配置应用部署设置。请参阅服务器配置。
如果要将 Studio 与服务器 Adapter 配合使用,请使用 mastra studio 仅启动 Studio UI。
可用的 Adapter可用的 Adapter的直接链接
Mastra 目前提供以下官方服务器 Adapter:
也可以构建自己的 Adapter,详情请阅读自定义 Adapter。
安装安装的直接链接
安装所选框架的 Adapter。
- Express
- Hono
- Fastify
- Koa
- NestJS
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/express@latest
pnpm add @mastra/express@latest
yarn add @mastra/express@latest
bun add @mastra/express@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/hono@latest
pnpm add @mastra/hono@latest
yarn add @mastra/hono@latest
bun add @mastra/hono@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/fastify@latest
pnpm add @mastra/fastify@latest
yarn add @mastra/fastify@latest
bun add @mastra/fastify@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/koa@latest
pnpm add @mastra/koa@latest
yarn add @mastra/koa@latest
bun add @mastra/koa@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/nestjs@latest
pnpm add @mastra/nestjs@latest
yarn add @mastra/nestjs@latest
bun add @mastra/nestjs@latest
配置配置的直接链接
照常初始化应用,然后传入 app 和来自 src/mastra/index.ts 的主 mastra 实例来创建 MastraServer。调用 init() 会自动注册 Mastra 中间件和所有可用端点。可以像往常一样在 init() 前后继续添加自己的路由,它们会与 Mastra 端点一起运行。
- Express
- Hono
- Fastify
- Koa
- NestJS
import express from 'express'
import { MastraServer } from '@mastra/express'
import { mastra } from './mastra'
const app = express()
app.use(express.json())
const server = new MastraServer({ app, mastra })
await server.init()
app.listen(4111, () => {
console.log('Server running on port 4111')
})
有关完整配置选项,请参阅 Express Adapter 文档。
import { Hono } from 'hono'
import { serve } from '@hono/node-server'
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()
serve({ fetch: app.fetch, port: 4111 }, () => {
console.log('Server running on port 4111')
})
有关完整配置选项,请参阅 Hono Adapter 文档。
import Fastify from 'fastify'
import { MastraServer } from '@mastra/fastify'
import { mastra } from './mastra'
const app = Fastify()
const server = new MastraServer({ app, mastra })
await server.init()
app.get('/health', async request => {
const mastraInstance = request.mastra
const agents = Object.keys(mastraInstance.listAgents())
return { status: 'ok', agents }
})
const port = 4111
app.listen({ port }, () => {
console.log(`Server running on http://localhost:${port}`)
console.log(`Try: curl http://localhost:${port}/api/agents`)
})
有关完整配置选项,请参阅 Fastify Adapter 文档。
import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import { MastraServer } from '@mastra/koa'
import { mastra } from './mastra'
const app = new Koa()
app.use(bodyParser()) // Required for body parsing
const server = new MastraServer({ app, mastra })
await server.init()
app.use(async (ctx, next) => {
if (ctx.path === '/health' && ctx.method === 'GET') {
const mastraInstance = ctx.state.mastra
const agents = Object.keys(mastraInstance.listAgents())
ctx.body = { status: 'ok', agents }
return
}
await next()
})
const port = 4111
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
console.log(`Try: curl http://localhost:${port}/api/agents`)
})
有关完整配置选项,请参阅 Koa Adapter 文档。
import { Module } from '@nestjs/common'
import { MastraModule } from '@mastra/nestjs'
import { mastra } from './mastra'
@Module({
imports: [
MastraModule.register({
mastra,
}),
],
})
export class AppModule {}
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
await app.listen(3000)
}
bootstrap()
有关完整配置选项,请参阅 NestJS Adapter 文档。
初始化流程初始化流程的直接链接
调用 init() 会按顺序运行三个步骤。了解此流程有助于在特定位置插入自己的中间件。
registerContextMiddleware():将 Mastra 实例、请求上下文、Tool 和中止信号附加到每个请求,使后续所有中间件和路由 handler 都能使用 Mastra。registerAuthMiddleware():初始化期间运行 Adapter 身份验证 hook。Mastra 注册内置路由和registerApiRoute()路由时,官方 Adapter 会内联实施身份验证;因此,原始框架路由需要 Mastra 身份验证时,应使用 Adapter 导出的createAuthMiddleware()辅助函数。registerRoutes():注册 Agent、Workflow 和其他功能的所有 Mastra API 路由。如果配置了 MCP 服务器,也会注册 MCP 路由。
手动初始化手动初始化的直接链接
要自定义中间件顺序,请分别调用各个方法,而不是调用 init()。当需要在设置 Mastra 上下文之前运行中间件,或需要在初始化步骤之间插入逻辑时,此方式很有用。
const server = new MastraServer({ app, mastra });
// Your middleware first
app.use(loggingMiddleware);
server.registerContextMiddleware();
// Middleware that needs Mastra context
app.use(customMiddleware);
await server.registerRoutes();
// Routes after Mastra
app.get('/health', ...);
当需要在 Mastra 上下文可用之前运行中间件,或需要在上下文和身份验证步骤之间插入中间件时,请使用手动初始化。
添加自定义路由添加自定义路由的直接链接
可以将自己的路由与 Mastra 路由一同添加到应用中。
- 在
init()之前添加的路由无法使用 Mastra 上下文。 - 在
init()之后添加的路由可以访问 Mastra 上下文(Mastra 实例、请求上下文、已认证用户等)。 - 需要由 Mastra 管理的身份验证和
requiresAuth等路由元数据时,请优先使用registerApiRoute()。 - 直接在框架应用上挂载路由时,如果这些路由需要 Mastra 身份验证,请使用 Adapter 导出的
createAuthMiddleware()辅助函数。
有关更多信息,请参阅 Express 和 Hono 文档中的“添加自定义路由”部分:Express、Hono。
路由前缀路由前缀的直接链接
默认情况下,Mastra 路由注册在 /api/agents、/api/workflows 等路径。使用 prefix 选项可进行更改。这适用于 API 版本控制,或与已有自身 /api 路由的现有应用集成。
const server = new MastraServer({
app,
mastra,
prefix: '/api/v2',
})
使用此前缀后,Mastra 路由会变为 /api/v2/agents、/api/v2/workflows 等。直接添加到应用的自定义路由不受此前缀影响。
OpenAPI 规范OpenAPI 规范的直接链接
Mastra 可以为所有已注册路由生成 OpenAPI 规范。这适用于文档、客户端生成或与 API Tool 集成。设置 openapiPath 选项即可启用:
const server = new MastraServer({
app,
mastra,
openapiPath: '/openapi.json',
})
该规范根据每个路由上定义的 Zod schema 生成,并在指定路径提供。它包括所有 Mastra 路由以及使用 createRoute() 创建的所有自定义路由。
流数据删减流数据删减的直接链接
通过 HTTP 流式传输 Agent 响应时,HTTP 流式传输层会在将数据块发送给客户端之前删减敏感信息,从而防止意外暴露:
- 系统提示和 Agent 指令
- Tool 定义及其参数
- 请求正文中的 API 密钥和其他凭据
- 内部配置数据
删减发生在 HTTP 边界,因此 onStepFinish 等内部回调仍可访问完整请求数据,用于调试和可观测性。
删减默认启用。通过 streamOptions 配置此行为。仅当内部服务或调试场景需要访问流式响应中的完整请求数据时,才设置 redact: false。
const server = new MastraServer({
app,
mastra,
streamOptions: {
redact: true, // Default
},
})
有关完整配置选项,请参阅 MastraServer。
单路由身份验证覆盖单路由身份验证覆盖的直接链接
在 Mastra 实例上配置身份验证后,所有路由默认都需要身份验证。有时需要例外,例如公开的健康检查端点或 webhook 接收器,或者需要更严格控制的管理员路由。
使用 customRouteAuthConfig 覆盖特定路由的身份验证行为。键遵循 METHOD:PATH 格式,其中方法为 GET、POST、PUT、DELETE 或 ALL。路径支持通配符(*)以匹配多个路由。将值设置为 false 会使路由公开,设置为 true 则要求身份验证。
const server = new MastraServer({
app,
mastra,
customRouteAuthConfig: new Map([
// Public health check
['GET:/api/health', false],
// Public API spec
['GET:/api/openapi.json', false],
// Public webhook endpoints
['POST:/api/webhooks/*', false],
// Require auth even if globally disabled
['POST:/api/admin/reset', true],
// Protect all methods on internal routes
['ALL:/api/internal/*', true],
]),
})
有关完整配置选项,请参阅 MastraServer。
访问应用访问应用的直接链接
创建 Adapter 后,可能仍需访问底层框架应用。这适用于将其传递给平台的 serve 函数,或从其他模块添加路由。
// Via the MastraServer instance
const app = server.getApp()
// Via the Mastra instance (available after adapter construction)
const app = mastra.getServerApp()
两种方法返回相同的应用实例。请根据当前作用域选择更方便的方法。
服务器配置与 Adapter 选项服务器配置与 Adapter 选项的直接链接
使用服务器 Adapter 时,配置来自两个位置:Mastra server 配置(传递给 Mastra 构造函数)和 Adapter 构造函数选项。了解各选项的来源,有助于在设置似乎未生效时避免困惑。
Adapter 使用的选项Adapter 使用的选项的直接链接
Adapter 从 mastra.getServer() 读取以下设置:
| 选项 | 描述 |
|---|---|
auth | 身份验证配置,由 registerAuthMiddleware() 使用。 |
bodySizeLimit | 默认正文大小限制(字节)。可通过 bodyLimitOptions 为每个 Adapter 覆盖。 |
onError | 路由 handler 中发生未处理错误时调用的自定义错误 handler。请参阅 server.onError。 |
仅用于 Adapter 构造函数仅用于 Adapter 构造函数的直接链接
以下选项直接传递给 Adapter 构造函数,不从 Mastra 配置中读取:
| 选项 | 描述 |
|---|---|
prefix | 路由路径前缀 |
openapiPath | OpenAPI 规范端点 |
bodyLimitOptions | 带自定义错误 handler 的正文大小限制 |
streamOptions | 流删减设置 |
customRouteAuthConfig | 单路由身份验证覆盖 |
mcpOptions | MCP transport 选项(例如无状态环境使用 serverless: true) |
Adapter 不使用的选项Adapter 不使用的选项的直接链接
以下 server 配置选项仅供 mastra build 使用,直接使用 Adapter 时不会生效:
| 选项 | 使用方 |
|---|---|
port, host | mastra dev, mastra build |
cors | mastra build 添加 CORS 中间件 |
timeout | mastra build |
apiRoutes | mastra build 的 registerApiRoute() |
middleware | mastra build 的中间件配置 |
使用 Adapter 时,请直接通过框架配置这些功能。例如,使用 Hono 或 Express 的内置 CORS 包添加 CORS 中间件,并在调用框架的 listen 函数时设置端口。
MCP 支持MCP 支持的直接链接
当 Mastra 实例中配置了 MCP 服务器时,服务器 Adapter 会在 registerRoutes() 期间注册 MCP (Model Context Protocol) 路由。MCP 允许外部 Tool 和服务连接到 Mastra 服务器并与 Agent 交互。
Adapter 会同时为 HTTP 和 SSE (Server-Sent Events) transport 注册路由,从而支持不同的客户端连接模式。
Serverless 模式Serverless 模式的直接链接
对于 Cloudflare Workers 或 Vercel Edge 等 Serverless 环境,请通过 mcpOptions 启用无状态模式。
使用 Mastra deployer(标准 mastra dev / mastra build 路径)时,请在服务器配置中设置 mcpOptions:
const mastra = new Mastra({
server: {
mcpOptions: {
serverless: true,
},
},
})
手动创建服务器 Adapter 时,请直接传递 mcpOptions:
const server = new MastraServer({
app,
mastra,
mcpOptions: {
serverless: true,
},
})
设置 serverless: true 后,MCP HTTP 请求在没有会话管理的情况下运行,因此与无状态执行环境兼容。
有关配置详情和设置 MCP 服务器的方法,请参阅 MCP。
相关内容相关内容的直接链接
- Hono Adapter - Hono 特定设置
- Express Adapter - Express 特定设置
- NestJS Adapter - NestJS 特定设置
- 自定义 Adapter - 为其他框架构建 Adapter
- 服务器配置 - 改用
mastra build - 身份验证 - 配置服务器身份验证
- MastraServer 参考 - 完整 API 参考
- createRoute() 参考 - 创建类型安全的自定义路由