服务器适配器
🌐 Server Adapters
服务器适配器让你可以使用自己的 HTTP 服务器运行 Mastra,而不是 mastra build 生成的 Hono 服务器。它们提供了对服务器设置的更多控制,包括自定义中间件顺序、认证、日志记录和部署配置。你仍然可以将 Mastra 集成到任何 Node.js 应用中,而无需改变代理或工作流的执行方式。
🌐 Server adapters let you run Mastra with your own HTTP server instead of the Hono server generated by mastra build. They provide more control over the server setup, including custom middleware ordering, authentication, logging, and deployment configuration. You can still integrate Mastra into any Node.js application without changing how agents or workflows execute.
何时使用服务器适配器Direct link to 何时使用服务器适配器
🌐 When to use server adapters
- 你希望将 Mastra 的端点自动添加到现有应用中
- 你需要直接访问服务器实例以进行自定义配置
- 你们团队更倾向于使用其他服务器框架,而不是
mastra build创建的 Hono 服务器。
对于没有自定义服务器需求的部署,请改用 mastra build。它会配置服务器设置、注册中间件,并根据你的项目配置应用部署设置。请参阅 服务器配置。
🌐 For deployments without custom server requirements, use mastra build instead. It configures server setup, registers middleware, and applies deployment settings based on your project configuration. See Server Configuration.
如果你想将 Studio 与你的服务器适配器一起使用,请使用 mastra studio 仅启动 Studio 界面。
🌐 If you want to use Studio with your server adapter, use mastra studio to only launch the Studio UI.
可用适配器Direct link to 可用适配器
🌐 Available adapters
Mastra 目前提供以下官方服务器适配器:
🌐 Mastra currently provides these official server adapters:
你可以自己构建适配器,详情请参阅自定义适配器。
🌐 You can build your own adapter, read custom adapters for details.
安装Direct link to 安装
🌐 Installation
为你选择的框架安装适配器。
🌐 Install the adapter for the framework of your choice.
- Express
- Hono
- Fastify
- Koa
- 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
配置Direct link to 配置
🌐 Configuration
像平常一样初始化你的应用,然后通过传入 app 和你的主 mastra 实例(来自 src/mastra/index.ts)来创建一个 MastraServer。调用 init() 会自动注册 Mastra 中间件和所有可用的端点。你可以像往常一样继续添加自己的路由,无论是在 init() 之前还是之后,它们都会与 Mastra 的端点一起运行。
🌐 Initialize your app as usual, then create a MastraServer by passing in the app and your main mastra instance from src/mastra/index.ts. Calling init() automatically registers Mastra middleware and all available endpoints. You can continue adding your own routes as normal, either before or after init(), and they’ll run alongside Mastra’s endpoints.
- Express
- Hono
- Fastify
- Koa
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 文档以获取完整的配置选项。
🌐 See the Express Adapter documentation for full configuration options.
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 文档以获取完整的配置选项。
🌐 See the Hono Adapter documentation for full configuration options.
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 适配器 文档以获取完整的配置选项。
🌐 See the Fastify Adapter documentation for full configuration options.
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 适配器文档以了解完整的配置选项。
🌐 See the Koa Adapter documentation for full configuration options.
初始化流程Direct link to 初始化流程
🌐 Initialization flow
调用 init() 会按顺序执行三个步骤。了解这个流程有助于在需要在特定点插入自己的中间件时使用。
🌐 Calling init() runs three steps in order. Understanding this flow helps when you need to insert your own middleware at specific points.
registerContextMiddleware():将 Mastra 实例、请求上下文、工具和中止信号附加到每个请求。这使得 Mastra 可用于所有后续的中间件和路由处理程序。registerAuthMiddleware():添加身份验证和授权中间件,但仅在你的 Mastra 实例中配置了server.auth时才会添加。如果未配置任何身份验证,则完全跳过。registerRoutes():注册所有针对代理、工作流及其他功能的 Mastra API 路由。如果配置了 MCP 服务器,也会注册 MCP 路由。
手动初始化Direct link to 手动初始化
🌐 Manual initialization
对于自定义中间件顺序,请分别调用每个方法,而不是 init()。当你需要在 Mastra 的上下文设置之前运行的中间件,或需要在初始化步骤之间插入逻辑时,这非常有用。
🌐 For custom middleware ordering, call each method separately instead of init(). This is useful when you need middleware that runs before Mastra's context is set up, or when you need to insert logic between the initialization steps.
const server = new MastraServer({ app, mastra });
// Your middleware first
app.use(loggingMiddleware);
server.registerContextMiddleware();
// Middleware that needs Mastra context
app.use(customMiddleware);
server.registerAuthMiddleware();
await server.registerRoutes();
// Routes after Mastra
app.get('/health', ...);
当你需要在 Mastra 的上下文可用之前运行中间件,或者需要在上下文和身份验证步骤之间插入中间件时,请使用手动初始化。
🌐 Use manual initialization when you need middleware that runs before Mastra's context is available, or when you need to insert middleware between the context and auth steps.
添加自定义路由Direct link to 添加自定义路由
🌐 Adding custom routes
你可以在应用中添加自己的路由,同时使用Mastra的路由。
🌐 You can add your own routes to the app alongside Mastra's routes.
- 在
init()之前添加的路由将无法使用 Mastra 上下文。 - 在
init()之后添加的路由可以访问 Mastra 上下文(Mastra 实例、请求上下文、已认证的用户等)。
路由前缀Direct link to 路由前缀
🌐 Route prefixes
默认情况下,Mastra 路由会注册在 /api/agents、/api/workflows 等位置。使用 prefix 选项可以更改此设置。这对于 API 版本控制或在与已有应用集成且其自身拥有 /api 路由时非常有用。
🌐 By default, Mastra routes are registered at /api/agents, /api/workflows, etc. Use the prefix option to change this. This is useful for API versioning or when integrating with an existing app that has its own /api routes.
const server = new MastraServer({
app,
mastra,
prefix: '/api/v2',
});
使用此前缀后,Mastra 路由将变为 /api/v2/agents、/api/v2/workflows 等。你直接添加到应用的自定义路由不受此前缀影响。
🌐 With this prefix, Mastra routes become /api/v2/agents, /api/v2/workflows, etc. Custom routes you add directly to the app are not affected by this prefix.
OpenAPI 规范Direct link to OpenAPI 规范
🌐 OpenAPI spec
Mastra 可以为所有已注册的路由生成 OpenAPI 规范。这对于文档、客户端生成或与 API 工具的集成非常有用。通过设置 openapiPath 选项来启用它:
🌐 Mastra can generate an OpenAPI specification for all registered routes. This is useful for documentation, client generation, or integration with API tools. Enable it by setting the openapiPath option:
const server = new MastraServer({
app,
mastra,
openapiPath: '/openapi.json',
});
规范是从每个路由上定义的 Zod 模式生成的,并在指定路径提供。它包括所有 Mastra 路由以及使用 createRoute() 创建的任何自定义路由。
🌐 The spec is generated from the Zod schemas defined on each route and served at the specified path. It includes all Mastra routes as well as any custom routes created with createRoute().
流数据脱敏Direct link to 流数据脱敏
🌐 Stream data redaction
在通过 HTTP 流式传输代理响应时,HTTP 流式传输层会在将流块发送给客户端之前删除敏感信息。这可以防止意外泄露以下内容:
🌐 When streaming agent responses over HTTP, the HTTP streaming layer redacts sensitive information from stream chunks before sending them to clients. This prevents accidental exposure of:
- 系统提示和代理指令
- 工具定义及其参数
- 请求体中的 API 密钥和其他凭证
- 内部配置数据
这种编辑发生在 HTTP 边界,因此像 onStepFinish 这样的内部回调仍然可以访问完整的请求数据,以用于调试和可观测性目的。
🌐 This redaction happens at the HTTP boundary, so internal callbacks like onStepFinish still have access to the full request data for debugging and observability purposes.
默认情况下,已启用编辑功能。通过 streamOptions 配置此行为。仅在需要在流响应中访问完整请求数据的内部服务或调试场景下设置 redact: false。
🌐 By default, redaction is enabled. Configure this behavior via streamOptions. Set redact: false only for internal services or debugging scenarios where you need access to the full request data in stream responses.
const server = new MastraServer({
app,
mastra,
streamOptions: {
redact: true, // Default
},
});
有关完整的配置选项,请参见 MastraServer。
🌐 See MastraServer for full configuration options.
每路由身份验证覆盖Direct link to 每路由身份验证覆盖
🌐 Per-route auth overrides
当在你的 Mastra 实例上配置了身份验证时,默认情况下所有路由都需要身份验证。有时你需要例外:公共健康检查端点、Webhook 接收器或需要更严格控制的管理路由。
🌐 When authentication is configured on your Mastra instance, all routes require authentication by default. Sometimes you need exceptions: public health check endpoints, webhook receivers, or admin routes that need stricter controls.
使用 customRouteAuthConfig 来覆盖特定路由的认证行为。密钥遵循 METHOD:PATH 格式,其中方法是 GET、POST、PUT、DELETE 或 ALL。路径支持通配符(*)以匹配多个路由。将值设置为 false 会使该路由公开,而 true 则需要认证。
🌐 Use customRouteAuthConfig to override authentication behavior for specific routes. Keys follow the format METHOD:PATH where method is GET, POST, PUT, DELETE, or ALL. Paths support wildcards (*) for matching multiple routes. Setting a value to false makes the route public, while true requires authentication.
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。
🌐 See MastraServer for full configuration options.
访问应用Direct link to 访问应用
🌐 Accessing the app
创建适配器后,你可能仍需要访问底层框架应用。这在将其传递给平台的 serve 函数或从其他模块添加路由时非常有用。
🌐 After creating the adapter, you may still need access to the underlying framework app. This is useful when passing it to a platform’s serve function or when adding routes from another module.
// Via the MastraServer instance
const app = server.getApp();
// Via the Mastra instance (available after adapter construction)
const app = mastra.getServerApp();
这两种方法都会返回相同的应用实例。根据当前的作用域,使用最方便的方法即可。
🌐 Both methods return the same app instance. Use whichever is more convenient based on what's in scope.
服务器配置与适配器选项Direct link to 服务器配置与适配器选项
🌐 Server config vs adapter options
在使用服务器适配器时,配置来自两个地方:Mastra server 配置(传递给 Mastra 构造函数)和适配器构造函数选项。了解哪些选项来自哪里有助于在设置似乎未生效时避免混淆。
🌐 When using server adapters, configuration comes from two places: the Mastra server config (passed to the Mastra constructor) and the adapter constructor options. Understanding which options come from where helps avoid confusion when settings don't seem to take effect.
由适配器使用Direct link to 由适配器使用
🌐 Used by adapters
适配器从 mastra.getServer() 读取这些设置:
🌐 The adapter reads these settings from mastra.getServer():
| 选项 | 描述 |
|---|---|
auth | 认证配置,由 registerAuthMiddleware() 使用。 |
bodySizeLimit | 默认的正文大小限制(以字节为单位)。可以通过 bodyLimitOptions 在每个适配器上覆盖。 |
仅适用于适配器构造函数Direct link to 仅适用于适配器构造函数
🌐 Adapter constructor only
这些选项会直接传递给适配器构造函数,而不会从 Mastra 配置中读取:
🌐 These options are passed directly to the adapter constructor and are not read from the Mastra config:
| 选项 | 描述 |
|---|---|
prefix | 路由路径前缀 |
openapiPath | OpenAPI 规范端点 |
bodyLimitOptions | 带自定义错误处理的请求体大小限制 |
streamOptions | 流量脱敏设置 |
customRouteAuthConfig | 每条路由的身份验证覆盖 |
mcpOptions | MCP 传输选项(例如,针对无状态环境的 serverless: true) |
不被适配器使用Direct link to 不被适配器使用
🌐 Not used by adapters
这些 server 配置选项仅被 mastra build 使用,直接使用适配器时不会生效:
🌐 These server config options are only used by mastra build and have no effect when using adapters directly:
| 选项 | 使用者 |
|---|---|
port、host | mastra dev、mastra build |
cors | mastra build 添加 CORS 中间件 |
timeout | mastra build |
apiRoutes | registerApiRoute() 用于 mastra build |
middleware | mastra build 的中间件配置 |
在使用适配器时,请直接通过你的框架配置这些功能。例如,使用 Hono 或 Express 提供的内置 CORS 包添加 CORS 中间件,并在调用框架的 listen 函数时设置端口。
🌐 When using adapters, configure these features directly with your framework. For example, add CORS middleware using Hono's or Express's built-in CORS packages, and set the port when calling your framework's listen function.
MCP 支持Direct link to MCP 支持
🌐 MCP support
当在你的 Mastra 实例中配置了 MCP 服务器时,服务器适配器会在 registerRoutes() 期间注册 MCP(模型上下文协议)路由。MCP 允许外部工具和服务连接到你的 Mastra 服务器,并与你的代理进行交互。
🌐 Server adapters register MCP (Model Context Protocol) routes during registerRoutes() when MCP servers are configured in your Mastra instance. MCP allows external tools and services to connect to your Mastra server and interact with your agents.
该适配器为 HTTP 和 SSE(服务器发送事件)传输注册路由,从而支持不同的客户端连接模式。
🌐 The adapter registers routes for both HTTP and SSE (Server-Sent Events) transports, enabling different client connection patterns.
无服务器模式Direct link to 无服务器模式
🌐 Serverless mode
对于像 Cloudflare Workers 或 Vercel Edge 这样的无服务器环境,通过 mcpOptions 启用无状态模式:
🌐 For serverless environments like Cloudflare Workers or Vercel Edge, enable stateless mode via mcpOptions:
const server = new MastraServer({
app,
mastra,
mcpOptions: {
serverless: true,
},
});
当 serverless: true 时,MCP HTTP 请求在没有会话管理的情况下运行,使其与无状态执行环境兼容。
🌐 When serverless: true, MCP HTTP requests run without session management, making them compatible with stateless execution environments.
有关配置详情及如何设置 MCP 服务器,请参阅 MCP 。
🌐 See MCP for configuration details and how to set up MCP servers.
相关Direct link to 相关
🌐 Related
- Hono 适配器 - Hono 专用设置
- Express 适配器 - Express 专用设置
- 自定义适配器 - 为其他框架构建适配器
- 服务器配置 - 改用
mastra build - 身份验证 - 配置服务器认证
- MastraServer 参考 - 完整 API 参考
- createRoute() 参考 - 创建类型安全的自定义路由