> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Express 适配器 `@mastra/express` 包提供了一个服务器适配器,用于通过 [Express](https://expressjs.com) 运行 Mastra。有关通用适配器概念(构造函数选项、初始化流程等),请参阅 [Server 适配器](https://mastra.zisheng.pro/docs/server/server-adapters)。 ## 安装 安装 Express 适配器和 Express 框架: **npm**: ```bash npm install @mastra/express@latest express ``` **pnpm**: ```bash pnpm add @mastra/express@latest express ``` **Yarn**: ```bash yarn add @mastra/express@latest express ``` **Bun**: ```bash bun add @mastra/express@latest express ``` ## 使用示例 ```typescript import express from 'express' import { MastraServer } from '@mastra/express' import { mastra } from './mastra' const app = express() app.use(express.json()) // Required for body parsing const server = new MastraServer({ app, mastra }) await server.init() app.listen(4111, () => { console.log('Server running on port 4111') }) ``` > **备注:** Express 需要使用 `express.json()` 中间件来解析 JSON 请求正文。请在创建 `MastraServer` 前添加它。 ## 构造函数参数 **app** (`Application`): Express 应用实例 **mastra** (`Mastra`): Mastra 实例 **prefix** (`string`): 路由路径前缀(例如:/api/v2) (Default: `''`) **openapiPath** (`string`): 提供 OpenAPI 规范的路径(例如:/openapi.json) (Default: `''`) **bodyLimitOptions** (`{ maxSize: number, onError: (err) => unknown }`): 请求正文大小限制 **streamOptions** (`{ redact?: boolean }`): 流脱敏配置。设为 true 时,会从流中移除敏感数据。 (Default: `{ redact: true }`) **customRouteAuthConfig** (`Map`): 按路由覆盖认证配置。键为 METHOD:PATH(例如:GET:/api/health)。值为 false 时路由公开;为 true 时需要认证。 **tools** (`Record`): 服务器可用的 Tool **taskStore** (`InMemoryTaskStore`): 用于 A2A(Agent-to-Agent)操作的任务存储 **mcpOptions** (`MCPOptions`): MCP 传输选项。对于 Cloudflare Workers 或 Vercel Edge 等无状态环境,请设置 serverless: true。 ## 与 Hono 的差异 | 方面 | Express | Hono | | ----------- | --------------------------- | --------------------- | | 请求正文解析 | 需要 `express.json()` | 由框架处理 | | 上下文存储 | `res.locals` | `c.get()` / `c.set()` | | 中间件签名 | `(req, res, next)` | `(c, next)` | | 流式传输 | `res.write()` / `res.end()` | `stream()` 助手函数 | | AbortSignal | 从 `req.on('close')` 创建 | `c.req.raw.signal` | ## 添加自定义路由 直接向 Express 应用添加路由: ```typescript const app = express() app.use(express.json()) const server = new MastraServer({ app, mastra }) // Before init - runs before Mastra middleware app.get('/early-health', (req, res) => res.json({ status: 'ok' })) await server.init() // After init - has access to Mastra context app.get('/custom', (req, res) => { const mastraInstance = res.locals.mastra res.json({ agents: Object.keys(mastraInstance.listAgents()) }) }) app.listen(4111) ``` > **提示:** 在 `init()` 前添加的路由会在没有 Mastra 上下文的情况下运行。请在 `init()` 后添加路由,以访问 Mastra 实例和请求上下文。 如需使用由 Mastra 管理的认证和 `requiresAuth` 等路由元数据,请优先使用 [`registerApiRoute()`](https://mastra.zisheng.pro/reference/server/register-api-route)。对于直接挂载到 `app` 上的原始 Express 路由,请使用 `createAuthMiddleware()`: ```typescript import express from 'express' import { createAuthMiddleware, 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.get('/custom/protected', createAuthMiddleware({ mastra }), (req, res) => { const user = res.locals.requestContext.get('user') res.json({ user }) }) app.get('/custom/public', createAuthMiddleware({ mastra, requiresAuth: false }), (req, res) => { res.json({ ok: true }) }) ``` ## 访问上下文 在 Express 中间件和路由中,通过 `res.locals` 访问 Mastra 上下文: ```typescript app.get('/custom', (req, res) => { const mastra = res.locals.mastra const requestContext = res.locals.requestContext const abortSignal = res.locals.abortSignal const agent = mastra.getAgent('myAgent') res.json({ agent: agent.name }) }) ``` `res.locals` 上可用的属性: | 键 | 说明 | | ----------------------- | --------------- | | `mastra` | Mastra 实例 | | `requestContext` | 请求上下文映射 | | `abortSignal` | 请求取消信号 | | `tools` | 可用的 Tool | | `taskStore` | 用于 A2A 操作的任务存储 | | `customRouteAuthConfig` | 按路由覆盖认证配置 | | `user` | 已认证的用户(如果已配置认证) | ## 添加中间件 在 `init()` 前或后添加 Express 中间件: ```typescript const app = express() app.use(express.json()) // Middleware before init app.use((req, res, next) => { console.log(`${req.method} ${req.url}`) next() }) const server = new MastraServer({ app, mastra }) await server.init() // Middleware after init has access to Mastra context app.use((req, res, next) => { const mastra = res.locals.mastra next() }) ``` ## 手动初始化 如需自定义中间件顺序,请分别调用各个方法,而非调用 `init()`。详情请参阅[手动初始化](https://mastra.zisheng.pro/docs/server/server-adapters)。 ## 示例 - [Express 适配器](https://github.com/mastra-ai/mastra/tree/main/examples/server-express-adapter):基础 Express 服务器设置 ## 相关内容 - [Server 适配器](https://mastra.zisheng.pro/docs/server/server-adapters):共享的适配器概念 - [MastraServer 参考](https://mastra.zisheng.pro/reference/server/mastra-server):完整 API 参考 - [createRoute() 参考](https://mastra.zisheng.pro/reference/server/create-route):创建类型安全的自定义路由