Express 适配器
@mastra/express 包提供了一个服务器适配器,用于通过 Express 运行 Mastra。有关通用适配器概念(构造函数选项、初始化流程等),请参阅 Server 适配器。
安装安装的直接链接
安装 Express 适配器和 Express 框架:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/express@latest express
pnpm add @mastra/express@latest express
yarn add @mastra/express@latest express
bun add @mastra/express@latest express
使用示例使用示例的直接链接
server.ts
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)openapiPath?:
string
= ''
提供 OpenAPI 规范的路径(例如:
/openapi.json)bodyLimitOptions?:
{ maxSize: number, onError: (err) => unknown }
请求正文大小限制
streamOptions?:
{ redact?: boolean }
= { redact: true }
流脱敏配置。设为
true 时,会从流中移除敏感数据。customRouteAuthConfig?:
Map<string, boolean>
按路由覆盖认证配置。键为
METHOD:PATH(例如:GET:/api/health)。值为 false 时路由公开;为 true 时需要认证。tools?:
Record<string, Tool>
服务器可用的 Tool
taskStore?:
InMemoryTaskStore
用于 A2A(Agent-to-Agent)操作的任务存储
mcpOptions?:
MCPOptions
MCP 传输选项。对于 Cloudflare Workers 或 Vercel Edge 等无状态环境,请设置
serverless: true。与 Hono 的差异与 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 应用添加路由:
server.ts
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()。对于直接挂载到 app 上的原始 Express 路由,请使用 createAuthMiddleware():
server.ts
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 上下文:
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 中间件:
server.ts
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()。详情请参阅手动初始化。
示例示例的直接链接
- Express 适配器:基础 Express 服务器设置
相关内容相关内容的直接链接
- Server 适配器:共享的适配器概念
- MastraServer 参考:完整 API 参考
- createRoute() 参考:创建类型安全的自定义路由