Skip to main content

Express 适配器

🌐 Express Adapter

@mastra/express 包提供了一个用于在 Express 上运行 Mastra 的服务器适配器。

🌐 The @mastra/express package provides a server adapter for running Mastra with Express.

info

有关一般适配器概念(构造函数选项、初始化流程等),请参见 服务器适配器

🌐 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 install @mastra/express@latest express

使用示例
Direct link to 使用示例

🌐 Usage example

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');
});
note

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:

Application
Express app instance

mastra:

Mastra
Mastra instance

prefix?:

string
= ''
Route path prefix (e.g., `/api/v2`)

openapiPath?:

string
= ''
Path to serve OpenAPI spec (e.g., `/openapi.json`)

bodyLimitOptions?:

{ maxSize: number, onError: (err) => unknown }
Request body size limits

streamOptions?:

{ redact?: boolean }
= { redact: true }
Stream redaction config. When true, redacts sensitive data from streams.

customRouteAuthConfig?:

Map<string, boolean>
Per-route auth overrides. Keys are `METHOD:PATH` (e.g., `GET:/api/health`). Value `false` makes route public, `true` requires auth.

tools?:

Record<string, Tool>
Available tools for the server

taskStore?:

InMemoryTaskStore
Task store for A2A (Agent-to-Agent) operations

mcpOptions?:

MCPOptions
MCP transport options. Set `serverless: true` for stateless environments like Cloudflare Workers or Vercel Edge.

与Hono的区别
Direct link to 与Hono的区别

🌐 Differences from Hono

方面ExpressHono
请求体解析需要 express.json()由框架处理
上下文存储res.localsc.get() / c.set()
中间件签名(req, res, next)(c, next)
流处理res.write() / res.end()stream() 辅助
AbortSignalreq.on('close') 创建c.req.raw.signal

添加自定义路由
Direct link to 添加自定义路由

🌐 Adding custom routes

直接向 Express 应用添加路由:

🌐 Add routes directly to the Express app:

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);
tip

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:

描述
mastraMastra 实例
requestContext请求上下文映射
abortSignal请求取消信号
tools可用工具
taskStoreA2A 操作的任务存储
customRouteAuthConfig每条路由的认证覆盖
user已认证用户(如果已配置认证)

添加中间件
Direct link to 添加中间件

🌐 Adding middleware

init() 之前或之后添加 Express 中间件:

🌐 Add Express middleware before or after init():

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();
});

手动初始化
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

🌐 Related