Server 介面卡
Server 介面卡可讓你使用自己的 HTTP 伺服器執行 Mastra,而不使用 mastra build 產生的 Hono 伺服器。你可以更完整地控制伺服器設定,包括自訂中介軟體順序、驗證、記錄記錄及部署設定。你仍可將 Mastra 整合至任何 Node.js 應用程式,且不必變更 Agent 或 Workflow 的執行方式。
Server 介面卡會使用你傳入的 mastra 執行個體,且不會執行檔案式探索。請在程式碼中將 Agent 註冊至該執行個體。若要使用檔案式 Agent,請透過 mastra dev 或 mastra build 將 Mastra 作為獨立伺服器執行。
何時使用 Server 介面卡「何時使用 Server 介面卡」的直接連結
- 你想要自動將 Mastra 的端點新增至現有應用程式
- 你需要直接存取伺服器執行個體以進行自訂設定
- 你的團隊偏好使用其他伺服器框架,而非
mastra build建立的 Hono 伺服器。
若部署沒有自訂伺服器需求,請改用 mastra build。它會設定伺服器並註冊中介軟體,也會依據專案設定套用部署設定。請參閱 Server 設定。
若要搭配 Server 介面卡使用 Studio,請使用 mastra studio,僅啟動 Studio UI。
可用的介面卡「可用的介面卡」的直接連結
Mastra 目前提供下列官方 Server 介面卡:
你也可以建置自己的介面卡,詳情請閱讀自訂介面卡。
安裝「安裝」的直接連結
請安裝所選框架的介面卡。
- Express
- Hono
- Fastify
- Koa
- NestJS
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/express@latest
pnpm add @mastra/express@latest
yarn add @mastra/express@latest
bun add @mastra/express@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/hono@latest
pnpm add @mastra/hono@latest
yarn add @mastra/hono@latest
bun add @mastra/hono@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/fastify@latest
pnpm add @mastra/fastify@latest
yarn add @mastra/fastify@latest
bun add @mastra/fastify@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/koa@latest
pnpm add @mastra/koa@latest
yarn add @mastra/koa@latest
bun add @mastra/koa@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/nestjs@latest
pnpm add @mastra/nestjs@latest
yarn add @mastra/nestjs@latest
bun add @mastra/nestjs@latest
設定「設定」的直接連結
如常初始化應用程式,接著傳入 app 以及來自 src/mastra/index.ts 的主要 mastra 執行個體,以建立 MastraServer。呼叫 init() 會自動註冊 Mastra 中介軟體及所有可用端點。你可以在 init() 之前或之後照常加入自己的路由,它們會與 Mastra 的端點並行運作。
- Express
- Hono
- Fastify
- Koa
- NestJS
import express from 'express'
import { 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.listen(4111, () => {
console.log('Server running on port 4111')
})
如需完整設定選項,請參閱 Express 介面卡文件。
import { Hono } from 'hono'
import { serve } from '@hono/node-server'
import { HonoBindings, HonoVariables, MastraServer } from '@mastra/hono'
import { mastra } from './mastra'
const app = new Hono<{ Bindings: HonoBindings; Variables: HonoVariables }>()
const server = new MastraServer({ app, mastra })
await server.init()
serve({ fetch: app.fetch, port: 4111 }, () => {
console.log('Server running on port 4111')
})
如需完整設定選項,請參閱 Hono 介面卡文件。
import Fastify from 'fastify'
import { MastraServer } from '@mastra/fastify'
import { mastra } from './mastra'
const app = Fastify()
const server = new MastraServer({ app, mastra })
await server.init()
app.get('/health', async request => {
const mastraInstance = request.mastra
const agents = Object.keys(mastraInstance.listAgents())
return { status: 'ok', agents }
})
const port = 4111
app.listen({ port }, () => {
console.log(`Server running on http://localhost:${port}`)
console.log(`Try: curl http://localhost:${port}/api/agents`)
})
如需完整設定選項,請參閱 Fastify 介面卡文件。
import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import { MastraServer } from '@mastra/koa'
import { mastra } from './mastra'
const app = new Koa()
app.use(bodyParser()) // Required for body parsing
const server = new MastraServer({ app, mastra })
await server.init()
app.use(async (ctx, next) => {
if (ctx.path === '/health' && ctx.method === 'GET') {
const mastraInstance = ctx.state.mastra
const agents = Object.keys(mastraInstance.listAgents())
ctx.body = { status: 'ok', agents }
return
}
await next()
})
const port = 4111
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
console.log(`Try: curl http://localhost:${port}/api/agents`)
})
如需完整設定選項,請參閱 Koa 介面卡文件。
import { Module } from '@nestjs/common'
import { MastraModule } from '@mastra/nestjs'
import { mastra } from './mastra'
@Module({
imports: [
MastraModule.register({
mastra,
}),
],
})
export class AppModule {}
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
await app.listen(3000)
}
bootstrap()
如需完整設定選項,請參閱 NestJS 介面卡文件。
初始化流程「初始化流程」的直接連結
呼叫 init() 會依序執行三個步驟。瞭解此流程有助於在特定位置插入自己的中介軟體。
registerContextMiddleware():將 Mastra 執行個體、請求內容、Tool 及中止訊號附加至每個請求。如此一來,後續所有中介軟體與路由處理常式皆可使用 Mastra。registerAuthMiddleware():初始化期間執行介面卡的驗證掛鉤。Mastra 註冊內建路由及registerApiRoute()路由時,官方介面卡會在路由內強制驗證;因此,原始框架路由需要 Mastra 驗證時,應使用介面卡匯出的createAuthMiddleware()輔助函式。registerRoutes():註冊 Agent、Workflow 及其他功能的所有 Mastra API 路由。若已設定 MCP 伺服器,也會註冊 MCP 路由。
手動初始化「手動初始化」的直接連結
若要自訂中介軟體順序,請分別呼叫各方法,而不要呼叫 init()。當中介軟體需要在 Mastra 內容設定前執行,或需要在初始化步驟之間插入邏輯時,這種方式相當實用。
const server = new MastraServer({ app, mastra });
// Your middleware first
app.use(loggingMiddleware);
server.registerContextMiddleware();
// Middleware that needs Mastra context
app.use(customMiddleware);
await server.registerRoutes();
// Routes after Mastra
app.get('/health', ...);
當中介軟體需要在 Mastra 內容可用前執行,或需要在內容與驗證步驟之間插入中介軟體時,請使用手動初始化。
新增自訂路由「新增自訂路由」的直接連結
你可以將自己的路由與 Mastra 路由一同加入應用程式。
- 在
init()之前新增的路由無法使用 Mastra 內容。 - 在
init()之後新增的路由可以存取 Mastra 內容(Mastra 執行個體、請求內容、已驗證使用者等)。 - 若要使用 Mastra 管理的驗證及
requiresAuth等路由中繼資料,請優先使用registerApiRoute()。 - 直接將路由掛載至框架應用程式時,若這些路由需要 Mastra 驗證,請使用介面卡匯出的
createAuthMiddleware()輔助函式。
如需更多資訊,請參閱 Express 與 Hono 的「新增自訂路由」章節:Express及 Hono。
路由前置詞「路由前置詞」的直接連結
Mastra 路由預設會註冊於 /api/agents、/api/workflows 等路徑。使用 prefix 選項可加以變更。這對 API 版本控制,或與已有自身 /api 路由的現有應用程式整合很有幫助。
const server = new MastraServer({
app,
mastra,
prefix: '/api/v2',
})
套用此前置詞後,Mastra 路由會變成 /api/v2/agents、/api/v2/workflows 等。直接加入應用程式的自訂路由不受此前置詞影響。
OpenAPI 規格「OpenAPI 規格」的直接連結
Mastra 可為所有已註冊路由產生 OpenAPI 規格,適用於文件、用戶端產生或與 API 工具整合。設定 openapiPath 選項即可啟用:
const server = new MastraServer({
app,
mastra,
openapiPath: '/openapi.json',
})
此規格會依據各路由定義的 Zod schema 產生,並於指定路徑提供。規格包含所有 Mastra 路由,以及任何以 createRoute() 建立的自訂路由。
串流資料遮蔽「串流資料遮蔽」的直接連結
透過 HTTP 串流傳送 Agent 回應時,HTTP 串流層會先遮蔽串流區塊中的敏感資訊,再將其傳送至用戶端。這可避免意外洩露:
- 系統提示詞與 Agent 指示
- Tool 定義及其參數
- 請求本文中的 API 金鑰及其他認證資訊
- 內部設定資料
遮蔽會在 HTTP 邊界進行,因此 onStepFinish 等內部回呼仍可存取完整請求資料,以供偵錯與可觀測性用途使用。
遮蔽預設為啟用。請透過 streamOptions 設定此行為。只有內部服務或偵錯情境需要存取串流回應中的完整請求資料時,才應設定 redact: false。
const server = new MastraServer({
app,
mastra,
streamOptions: {
redact: true, // Default
},
})
如需完整設定選項,請參閱 MastraServer。
各路由的驗證覆寫「各路由的驗證覆寫」的直接連結
在 Mastra 執行個體上設定驗證後,所有路由預設皆須通過驗證。有時你會需要例外,例如公開的健康狀態檢查端點或 webhook 接收器;也可能需要控制更嚴格的管理員路由。
使用 customRouteAuthConfig 覆寫特定路由的驗證行為。鍵採用 METHOD:PATH 格式,其中 method 可為 GET、POST、PUT、DELETE 或 ALL。路徑支援萬用字元(*),可比對多個路由。將值設為 false 會使路由公開;設為 true 則要求驗證。
const server = new MastraServer({
app,
mastra,
customRouteAuthConfig: new Map([
// Public health check
['GET:/api/health', false],
// Public API spec
['GET:/api/openapi.json', false],
// Public webhook endpoints
['POST:/api/webhooks/*', false],
// Require auth even if globally disabled
['POST:/api/admin/reset', true],
// Protect all methods on internal routes
['ALL:/api/internal/*', true],
]),
})
如需完整設定選項,請參閱 MastraServer。
存取應用程式「存取應用程式」的直接連結
建立介面卡後,你可能仍需存取底層框架應用程式。將其傳入平台的 serve 函式,或從其他模組新增路由時,這會很有幫助。
// Via the MastraServer instance
const app = server.getApp()
// Via the Mastra instance (available after adapter construction)
const app = mastra.getServerApp()
兩種方法都會傳回相同的應用程式執行個體。請依目前作用域選用較方便的方法。
Server 設定與介面卡選項「Server 設定與介面卡選項」的直接連結
使用 Server 介面卡時,設定來自兩處:傳給 Mastra 建構函式的 Mastra server 設定,以及介面卡建構函式選項。瞭解各選項的來源,有助於避免設定看似未生效時產生混淆。
介面卡會使用的設定「介面卡會使用的設定」的直接連結
介面卡會從 mastra.getServer() 讀取下列設定:
| 選項 | 說明 |
|---|---|
auth | 驗證設定,由 registerAuthMiddleware() 使用。 |
bodySizeLimit | 預設本文大小上限(位元組)。可透過 bodyLimitOptions 針對各介面卡覆寫。 |
onError | 路由處理常式發生未處理錯誤時呼叫的自訂錯誤處理常式。請參閱 server.onError。 |
僅限介面卡建構函式「僅限介面卡建構函式」的直接連結
這些選項會直接傳給介面卡建構函式,不會從 Mastra 設定中讀取:
| 選項 | 說明 |
|---|---|
prefix | 路由路徑前置詞 |
openapiPath | OpenAPI 規格端點 |
bodyLimitOptions | 含自訂錯誤處理常式的本文大小上限 |
streamOptions | 串流遮蔽設定 |
customRouteAuthConfig | 各路由的驗證覆寫 |
mcpOptions | MCP 傳輸選項(例如無狀態環境的 serverless: true) |
介面卡不會使用的設定「介面卡不會使用的設定」的直接連結
這些 server 設定選項僅供 mastra build 使用,直接使用介面卡時不會生效:
| 選項 | 使用者 |
|---|---|
port, host | mastra dev, mastra build |
cors | mastra build 會新增 CORS 中介軟體 |
timeout | mastra build |
apiRoutes | mastra build 的 registerApiRoute() |
middleware | mastra build 的中介軟體設定 |
使用介面卡時,請直接透過框架設定這些功能。例如,使用 Hono 或 Express 的內建 CORS 套件新增 CORS 中介軟體,並在呼叫框架的 listen 函式時設定連接埠。
MCP 支援「MCP 支援」的直接連結
若 Mastra 執行個體已設定 MCP 伺服器,Server 介面卡會在 registerRoutes() 期間註冊 MCP(Model Context Protocol)路由。MCP 可讓外部工具與服務連線至 Mastra 伺服器,並與 Agent 互動。
介面卡會同時為 HTTP 與 SSE(Server-Sent Events)傳輸註冊路由,支援不同的用戶端連線模式。
Serverless 模式「Serverless 模式」的直接連結
對於 Cloudflare Workers 或 Vercel Edge 等 Serverless 環境,請透過 mcpOptions 啟用無狀態模式。
使用 Mastra 部署程式(標準 mastra dev/mastra build 路徑)時,請在 Server 設定中設定 mcpOptions:
const mastra = new Mastra({
server: {
mcpOptions: {
serverless: true,
},
},
})
手動建立 Server 介面卡時,請直接傳入 mcpOptions:
const server = new MastraServer({
app,
mastra,
mcpOptions: {
serverless: true,
},
})
當 serverless: true 時,MCP HTTP 請求不使用工作階段管理,因此可與無狀態執行環境相容。
如需設定詳細資料及 MCP 伺服器設定方式,請參閱 MCP。
相關內容「相關內容」的直接連結
- Hono 介面卡 - Hono 專用設定
- Express 介面卡 - Express 專用設定
- NestJS 介面卡 - NestJS 專用設定
- 自訂介面卡 - 為其他框架建置介面卡
- Server 設定 - 改用
mastra build - 驗證 - 設定伺服器驗證
- MastraServer 參考資料 - 完整 API 參考資料
- createRoute() 參考資料 - 建立型別安全的自訂路由