跳至主要內容

Express 轉接器

@mastra/express 套件提供了一個伺服器轉接器,用於透過 Express 執行 Mastra。有關通用轉接器概念(建構函式選項、初始化流程等),請參閱 Server 轉接器

安裝
「安裝」的直接連結

安裝 Express 轉接器和 Express 框架:

npm install @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() middleware 來解析 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 的差異」的直接連結

方面ExpressHono
請求主體解析需要 express.json()由框架處理
情境儲存res.localsc.get() / c.set()
middleware 簽名(req, res, next)(c, next)
串流傳輸res.write() / res.end()stream() 助手函式
AbortSignalreq.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 middleware 和路由中,透過 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 上可用的屬性:

說明
mastraMastra 執行個體
requestContext請求情境對應
abortSignal請求取消訊號
tools可用的 Tool
taskStore用於 A2A 操作的任務儲存
customRouteAuthConfig依路由覆寫認證設定
user已認證的使用者(如果已設定認證)

新增 middleware
「新增 middleware」的直接連結

init() 前或後新增 Express middleware:

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

手動初始化
「手動初始化」的直接連結

如需自訂 middleware 順序,請分別呼叫各個方法,而非呼叫 init()。詳情請參閱手動初始化

範例
「範例」的直接連結