> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # MastraServer `MastraServer` abstract class 是所有 server adapter 的基礎。擴充此 class 可為 Hono 或 Express 以外的 framework 建立 adapter。 ## 匯入 ```typescript import { MastraServer } from '@mastra/server/server-adapter' ``` ## Type 參數 ```typescript MastraServer ``` | 參數 | 說明 | | ----------- | ----------------------------------------- | | `TApp` | Framework app 類型(例如 `Hono`、`Application`) | | `TRequest` | Framework request 類型 | | `TResponse` | Framework response/context 類型 | ## Constructor ```typescript constructor(options: MastraServerOptions) ``` ### 選項 **app** (`TApp`): Framework app instance **mastra** (`Mastra`): Mastra instance **prefix** (`string`): Route 路徑前綴(例如 /api/v2) (Default: `''`) **openapiPath** (`string`): 提供 OpenAPI 規格的路徑 (Default: `''`) **bodyLimitOptions** (`BodyLimitOptions`): Request body 大小限制 **streamOptions** (`StreamOptions`): Stream 遮蔽設定 (Default: `{ redact: true }`) **customRouteAuthConfig** (`Map`): 各 route 的 auth 覆寫設定 **tools** (`Record`): Server 可用的 Tool **taskStore** (`InMemoryTaskStore`): A2A(Agent-to-Agent)操作的 task store **mcpOptions** (`MCPOptions`): Serverless 環境的 MCP transport 選項 ## Abstract method Adapter 必須實作以下 method: ### `registerContextMiddleware()` 將 Mastra context 附加至每個 request。 ```typescript abstract registerContextMiddleware(): void ``` **要附加的 context:** - `mastra` - Mastra instance - `requestContext` - Request scope context - `tools` - 可用的 Tool - `abortSignal` - Request 取消訊號 ### `registerAuthMiddleware()` 在初始化期間運行 adapter auth hook。當 auth 按 route 強制執行時,官方 adapter 可將其實作為 no-op。 ```typescript abstract registerAuthMiddleware(): void ``` ### `registerRoute()` 向 framework 註冊單一 route。 ```typescript abstract registerRoute( app: TApp, route: ServerRoute, options: { prefix?: string } ): Promise ``` ### `getParams()` 從 request 擷取參數。 ```typescript abstract getParams( route: ServerRoute, request: TRequest ): Promise<{ urlParams: Record; queryParams: Record; body: unknown; }> ``` ### `sendResponse()` 根據 route 類型傳送 response。 ```typescript abstract sendResponse( route: ServerRoute, response: TResponse, result: unknown ): Promise ``` ### `stream()` 處理 streaming response。 ```typescript abstract stream( route: ServerRoute, response: TResponse, result: unknown ): Promise ``` ## Instance method ### `init()` 透過註冊所有 middleware 及 route 初始化 server。 ```typescript async init(): Promise ``` 按以下順序呼叫: 1. `registerContextMiddleware()` 2. `registerAuthMiddleware()` 3. `registerRoutes()` ### `registerRoutes()` 註冊所有 Mastra route。 ```typescript async registerRoutes(): Promise ``` ### `getApp()` 取得 framework app instance。 ```typescript getApp(): T ``` ### `parsePathParams()` 使用 route 的 Zod schema 驗證路徑參數。 ```typescript async parsePathParams( route: ServerRoute, params: Record ): Promise> ``` ### `parseQueryParams()` 使用 route 的 Zod schema 驗證 query 參數。 ```typescript async parseQueryParams( route: ServerRoute, params: Record ): Promise> ``` ### `parseBody()` 使用 route 的 Zod schema 驗證 request body。 ```typescript async parseBody( route: ServerRoute, body: unknown ): Promise ``` ### `registerOpenAPIRoute()` 註冊提供 OpenAPI 規格的 endpoint。 ```typescript async registerOpenAPIRoute( app: TApp, config: OpenAPIConfig, options: { prefix?: string } ): Promise ``` ## Protected method ### `mergeRequestContext()` 合併來自多個來源(query 參數及 body)的 request context。 ```typescript protected mergeRequestContext(options: { paramsRequestContext?: Record; bodyRequestContext?: Record; }): RequestContext ``` ## 類型 ### `BodyLimitOptions` ```typescript interface BodyLimitOptions { maxSize: number onError: (error: unknown) => unknown } ``` ### `StreamOptions` ```typescript interface StreamOptions { redact?: boolean } ``` ### MCPOptions ```typescript interface MCPOptions { serverless?: boolean sessionIdGenerator?: () => string } ``` | Property | 說明 | | -------------------- | ---------------------------------------------------------------------------------------------- | | `serverless` | 設為 `true` 時,MCP 會以無狀態模式運行,不使用 session 管理。適用於 Cloudflare Workers 或 Vercel Edge 等 serverless 環境。 | | `sessionIdGenerator` | 用於產生 session ID 的自訂 function。 | ## 範例 ```typescript import { MastraServer, ServerRoute } from '@mastra/server/server-adapter' import type { Mastra } from '@mastra/core' export class MyServer extends MastraServer { registerContextMiddleware(): void { this.app.use('*', (req, res, next) => { res.locals.mastra = this.mastra next() }) } registerAuthMiddleware(): void { const auth = this.mastra.getServer()?.auth if (!auth) return // Register global auth middleware, or leave this empty and // enforce auth when routes are registered. } async registerRoute(app, route, { prefix }) { // Implement route registration } async getParams(route, request) { return { urlParams: request.params, queryParams: request.query, body: request.body, } } async sendResponse(route, response, result) { return response.json(result) } async stream(route, response, result) { // Implement streaming } } ``` ## 相關內容 - [Server adapter](https://mastra.zisheng.pro/zh-HK/docs/server/server-adapters):使用 adapter - [自訂 adapter](https://mastra.zisheng.pro/zh-HK/docs/server/custom-adapters):建立自訂 adapter - [createRoute()](https://mastra.zisheng.pro/zh-HK/reference/server/create-route):建立自訂 route