Express 适配器
🌐 Express Adapter
@mastra/express 包提供了一个用于在 Express 上运行 Mastra 的服务器适配器。
🌐 The @mastra/express package provides a server adapter for running Mastra with Express.
有关一般适配器概念(构造函数选项、初始化流程等),请参见 服务器适配器。
🌐 For general adapter concepts (constructor options, initialization flow, etc.), see Server Adapters.
安装Direct link to 安装
🌐 Installation
安装 Express 适配器和 Express 框架:
🌐 Install the Express adapter and Express framework:
- 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
使用示例Direct link to 使用示例
🌐 Usage example
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 之前添加它。
🌐 Express requires express.json() middleware for JSON body parsing. Add it before creating the MastraServer.
构造函数参数Direct link to 构造函数参数
🌐 Constructor parameters
app:
mastra:
prefix?:
openapiPath?:
bodyLimitOptions?:
streamOptions?:
customRouteAuthConfig?:
tools?:
taskStore?:
mcpOptions?:
与Hono的区别Direct link to 与Hono的区别
🌐 Differences from 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 |
添加自定义路由Direct link to 添加自定义路由
🌐 Adding custom routes
直接向 Express 应用添加路由:
🌐 Add routes directly to the Express app:
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 实例和请求上下文。
🌐 Routes added before init() run without Mastra context. Add routes after init() to access the Mastra instance and request context.
访问上下文Direct link to 访问上下文
🌐 Accessing context
在 Express 中间件和路由中,通过 res.locals 访问 Mastra 上下文:
🌐 In Express middleware and routes, access Mastra context via res.locals:
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 上可用的属性:
🌐 Available properties on res.locals:
| 键 | 描述 |
|---|---|
mastra | Mastra 实例 |
requestContext | 请求上下文映射 |
abortSignal | 请求取消信号 |
tools | 可用工具 |
taskStore | A2A 操作的任务存储 |
customRouteAuthConfig | 每条路由的认证覆盖 |
user | 已认证用户(如果已配置认证) |
添加中间件Direct link to 添加中间件
🌐 Adding middleware
在 init() 之前或之后添加 Express 中间件:
🌐 Add Express middleware before or after init():
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();
});
手动初始化Direct link to 手动初始化
🌐 Manual initialization
对于自定义中间件顺序,请分别调用每个方法,而不是使用 init()。详情请参阅手动初始化。
🌐 For custom middleware ordering, call each method separately instead of init(). See manual initialization for details.
示例Direct link to 示例
🌐 Examples
- Express 适配器 - 基本 Express 服务器设置
相关Direct link to 相关
🌐 Related
- 服务器适配器 - 共享适配器概念
- MastraServer 参考 - 完整 API 参考
- createRoute() 参考 - 创建类型安全的自定义路由