> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # 配置 以下參考資料涵蓋 Mastra 支援的所有選項。你可建立 [`Mastra` 類別](https://mastra.zisheng.pro/zh-HK/reference/core/mastra-class)的實例,以初始化及配置 Mastra。 ```ts import { Mastra } from '@mastra/core' export const mastra = new Mastra({ // Your options... }) ``` ## 頂層選項 ### agents **類型:** `Record` 以名稱為鍵的 Agent 實例記錄。Agent 是可使用 AI 模型、Tool 及記憶作出決策和採取行動的自主系統。 詳情請參閱 [Agent 文檔](https://mastra.zisheng.pro/zh-HK/docs/agents/overview)。 ```typescript import { Mastra } from '@mastra/core' import { Agent } from '@mastra/core/agent' export const mastra = new Mastra({ agents: { weatherAgent: new Agent({ id: 'weather-agent', name: 'Weather Agent', instructions: 'You help with weather information', model: 'openai/gpt-5.6-sol', }), }, }) ``` ### backgroundTasks **類型:** `BackgroundTaskManagerConfig` 啟用並配置背景工作管理器。啟用後,Agent 可分派長時間運行的 Tool 調用(包括子 Agent 調用)以非同步方式執行,同時繼續 Agent 迴圈。工作會持久保存,因此必須配置 `storage` 後端。 詳情請參閱[背景工作文檔](https://mastra.zisheng.pro/zh-HK/docs/long-running-agents/background-tasks)。 ```typescript import { Mastra } from '@mastra/core' import { LibSQLStore } from '@mastra/libsql' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db', }), backgroundTasks: { enabled: true, globalConcurrency: 10, perAgentConcurrency: 5, backpressure: 'queue', defaultTimeoutMs: 300_000, }, }) ``` **enabled** (`boolean`): 背景工作管理器是否可用。只有當此值為 true 且已配置 storage 後端時,管理器才會初始化。這是功能可用性開關,不會令任何 Tool 自動採用背景分派;Tool 必須在 Tool 或 Agent 層級明確啟用(請參閱背景工作指南)。 (Default: `false`) **globalConcurrency** (`number`): 所有 Agent 合計可同時運行的背景工作數量上限。 (Default: `10`) **perAgentConcurrency** (`number`): 單一 Agent 可同時運行的背景工作數量上限。 (Default: `5`) **backpressure** (`'queue' | 'reject' | 'fallback-sync'`): 達到並行上限時的行為。'queue' 會等待空位,'reject' 會在加入佇列時拋出錯誤,'fallback-sync' 則改為在 Agent 迴圈中同步運行 Tool。 (Default: `'queue'`) **defaultTimeoutMs** (`number`): 每項工作的預設逾時時間(毫秒)。可按個別 Tool 或個別調用覆寫。 (Default: `300000`) **defaultRetries** (`RetryConfig`): 套用至失敗工作的預設重試政策。 **defaultRetries.maxRetries** (`number`): 工作標記為失敗前的重試次數上限。 **defaultRetries.retryDelayMs** (`number`): 每次重試之間的延遲時間(毫秒)。 **defaultRetries.backoffMultiplier** (`number`): 每次後續嘗試套用至 retryDelayMs 的倍數。 **defaultRetries.maxRetryDelayMs** (`number`): 不論退避設定為何,重試延遲的上限。 **defaultRetries.retryableErrors** (`(error: Error) => boolean`): 判斷指定錯誤是否應重試的述詞函數。預設:重試所有錯誤。 **cleanup** (`CleanupConfig`): 控制工作記錄的保留時間,以及清理程序的運行頻率。 **cleanup.completedTtlMs** (`number`): 已完成工作記錄的保留時間(毫秒)。預設:1 小時。 **cleanup.failedTtlMs** (`number`): 失敗工作記錄的保留時間(毫秒)。預設:24 小時。 **cleanup.cleanupIntervalMs** (`number`): 清理程序的運行間隔(毫秒)。預設:1 分鐘。 **waitTimeoutMs** (`number`): Agent 迴圈在繼續前等待背景工作完成的時間。若工作未能在此時限內完成,迴圈會繼續而不設定 isContinued。預設:undefined(不等待)。可按個別 Agent 或 Tool 覆寫。 **onTaskComplete** (`(task: BackgroundTask) => void | Promise`): 任何背景工作成功完成時調用的全域回呼。除個別 Tool 及個別 Agent 的回呼外亦會觸發。 **onTaskFailed** (`(task: BackgroundTask) => void | Promise`): 任何背景工作失敗時調用的全域回呼。除個別 Tool 及個別 Agent 的回呼外亦會觸發。 ### deployer **類型:** `MastraDeployer` 用於將應用程式發佈至雲端平台的部署 Provider。 詳情請參閱[部署文檔](https://mastra.zisheng.pro/zh-HK/docs/deployment/overview)。 ```typescript import { Mastra } from '@mastra/core' import { NetlifyDeployer } from '@mastra/deployer-netlify' export const mastra = new Mastra({ deployer: new NetlifyDeployer(), }) ``` ### events **類型:** `Record` 內部發佈/訂閱系統的事件處理器。將事件主題映射至處理器函數;事件發佈至相應主題時,系統會調用這些函數。 > **注意:** 此選項供 Mastra 的 Workflow 引擎內部使用。大部分使用者毋須配置此選項。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ events: { 'my-topic': async event => { console.log('Event received:', event) }, }, }) ``` ### gateways **類型:** `Record` 用於存取 LLM Provider 的自訂模型路由閘道。閘道會處理 Provider 專用的驗證、URL 建構及模型解析。你可用此選項支援自訂或自行託管的 LLM Provider。 詳情請參閱[自訂閘道文檔](https://mastra.zisheng.pro/zh-HK/models/gateways/custom-gateways)。 ```typescript import { Mastra } from '@mastra/core' import { MyPrivateGateway } from './gateways' export const mastra = new Mastra({ gateways: { private: new MyPrivateGateway(), }, }) ``` ### idGenerator **類型:** `(context?: IdGeneratorContext) => string`\ **預設值:** `crypto.randomUUID()` 用於建立唯一標識符的自訂 ID 產生器函數。Mastra 會傳入可選的上下文,讓你按正在建立的內容產生 ID。 `IdGeneratorContext` 包括: - `idType`: `'thread' | 'message' | 'run' | 'step' | 'generic'` - `source?`: `'agent' | 'workflow' | 'memory'` - `entityId?`:提出請求的 Agent/Workflow/記憶實體 ID - `threadId?`:相關時使用的對話串 ID(例如建立訊息 ID 時) - `resourceId?`:相關時使用的資源 ID(例如使用者範圍的對話串) - `role?`:建立訊息 ID 時的訊息角色 - `stepType?`:建立步驟 ID 時的 Workflow 步驟類型 > **注意:** Mastra 會在內部使用此選項,為 Workflow 運行、Agent 對話及其他資源建立 ID。大部分使用者毋須配置此選項。 ```typescript import { v4 as uuid } from '@lukeed/uuid' import { Mastra } from '@mastra/core' export const mastra = new Mastra({ idGenerator: context => { if (context?.idType === 'message' && context?.threadId) { return `msg-${context.threadId}-${uuid()}` } if (context?.idType === 'run' && context?.source && context?.entityId) { return `${context.source}-run-${context.entityId}-${uuid()}` } return uuid() }, }) ``` ### logger **類型:** `IMastraLogger | false`\ **預設值:** 開發環境使用 `INFO` 級別的 `ConsoleLogger`,生產環境則使用 `WARN` 級別 用於應用程式記錄及除錯的 Logger 實作。設為 `false` 可完全停用記錄功能。 詳情請參閱[記錄文檔](https://mastra.zisheng.pro/zh-HK/docs/observability/logging)。 ```typescript import { Mastra } from '@mastra/core' import { PinoLogger } from '@mastra/loggers' export const mastra = new Mastra({ logger: new PinoLogger({ name: 'MyApp', level: 'debug' }), }) ``` ### mcpServers **類型:** `Record` 向 MCP 相容用戶端公開 Mastra Tool、Agent、Workflow 及資源的 MCP(Model Context Protocol)伺服器。你可用此選項編寫自有 MCP 伺服器,供任何支援此協定的系統使用。 詳情請參閱 [MCP 概覽](https://mastra.zisheng.pro/zh-HK/docs/mcp/overview)。 ```typescript import { Mastra } from '@mastra/core' import { MCPServer } from '@mastra/mcp' const mcpServer = new MCPServer({ id: 'my-mcp-server', name: 'My MCP Server', version: '1.0.0', }) export const mastra = new Mastra({ mcpServers: { myServer: mcpServer, }, }) ``` ### memory **類型:** `Record` 可供 Agent 引用的記憶實例登記冊。記憶會保留過往對話的相關資料,令 Agent 在多次互動之間保持連貫。Mastra 支援保存近期訊息的訊息記錄,以及保存使用者專屬持久資料的工作記憶。語意回憶會按相關性擷取較舊的訊息。 詳情請參閱[記憶文檔](https://mastra.zisheng.pro/zh-HK/docs/memory/overview)。 > **備註:** 大部分使用者會直接在 Agent 上配置記憶。此頂層配置用於定義可由多個 Agent 共用的可重用記憶實例。 ```typescript import { Mastra } from '@mastra/core' import { Memory } from '@mastra/memory' import { LibSQLStore } from '@mastra/libsql' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:', }), memory: { chatMemory: new Memory({ options: { lastMessages: 20, }, }), }, }) ``` ### observability **類型:** `ObservabilityEntrypoint` Mastra 為 AI 應用程式提供可觀測性功能。你可使用能理解 AI 特有模式的工具監察 LLM 操作、追蹤 Agent 決策,以及為複雜 Workflow 除錯。追蹤功能會擷取模型互動、Agent 執行路徑、Tool 調用及 Workflow 步驟。 詳情請參閱[可觀測性文檔](https://mastra.zisheng.pro/zh-HK/docs/observability/overview)。 ```typescript import { Mastra } from '@mastra/core' import { LibSQLStore } from '@mastra/libsql' import { Observability, MastraStorageExporter } from '@mastra/observability' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db', }), observability: new Observability({ configs: { default: { serviceName: 'my-app', exporters: [new MastraStorageExporter()], }, }, }), }) ``` ### processors **類型:** `Record` 用於轉換 Agent 輸入及輸出的輸入/輸出處理器。處理器會在 Agent 執行管線的特定位置運行,讓你在輸入送達語言模型前修改輸入,或在輸出傳回前修改輸出。你可使用處理器加入防護機制、偵測提示注入、審核內容,或套用自訂業務邏輯。 詳情請參閱[處理器文檔](https://mastra.zisheng.pro/zh-HK/docs/agents/processors)。 > **備註:** 大部分使用者會直接在 Agent 上配置處理器。此頂層配置用於定義可由多個 Agent 共用的可重用處理器實例。 ```typescript import { Mastra } from '@mastra/core' import { ModerationProcessor } from '@mastra/core/processors' export const mastra = new Mastra({ processors: { moderation: new ModerationProcessor({ model: 'openai/gpt-5-mini', categories: ['hate', 'harassment', 'violence'], }), }, }) ``` ### pubsub **類型:** `PubSub`\ **預設值:** `EventEmitterPubSub` 用於元件之間事件驅動通訊的發佈/訂閱系統。Mastra 會在內部使用此系統處理 Workflow 事件及元件通訊。 > **注意:** 此選項供 Mastra 內部使用。大部分使用者毋須配置此選項。 ```typescript import { Mastra } from '@mastra/core' import { CustomPubSub } from './pubsub' export const mastra = new Mastra({ pubsub: new CustomPubSub(), }) ``` ### scorers **類型:** `Record` Scorer 會評估 Agent 回應及 Workflow 輸出的質素,並透過模型評分、規則及統計方法提供可量化的指標,以衡量 Agent 質素。你可使用 Scorer 追蹤效能及比較不同方法,亦可找出有待改善之處。 詳情請參閱 [Scorer 文檔](https://mastra.zisheng.pro/zh-HK/docs/evals/overview)。 > **備註:** 大部分使用者會直接在 Agent 上配置 Scorer。此頂層配置用於定義可由多個 Agent 共用的可重用 Scorer 實例。 ```typescript import { Mastra } from '@mastra/core' import { createToxicityScorer } from '@mastra/evals/scorers/prebuilt' export const mastra = new Mastra({ scorers: { toxicity: createToxicityScorer({ model: 'openai/gpt-5-mini' }), }, }) ``` ### storage **類型:** `MastraCompositeStore` 用於持久保存應用程式資料的儲存 Provider。記憶、Workflow、Trace 及其他需要持久儲存的元件都會使用此 Provider。Mastra 支援多種資料庫後端,包括 PostgreSQL、MongoDB、libSQL 等。 詳情請參閱[儲存文檔](https://mastra.zisheng.pro/zh-HK/docs/storage/overview)。 ```typescript import { Mastra } from '@mastra/core' import { LibSQLStore } from '@mastra/libsql' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db', }), }) ``` ### tools **類型:** `Record` Tool 是可重用的函數,Agent 可用它與外部系統互動。每個 Tool 都會定義輸入、輸出及執行邏輯。 詳情請參閱 [Tool 文檔](https://mastra.zisheng.pro/zh-HK/docs/agents/using-tools)。 > **備註:** 大部分使用者會直接在 Agent 上配置 Tool。此頂層配置用於定義可由多個 Agent 共用的可重用 Tool。 ```typescript import { Mastra } from '@mastra/core' import { createTool } from '@mastra/core/tools' import { z } from 'zod' const weatherTool = createTool({ id: 'get-weather', description: 'Fetches weather for a city', inputSchema: z.object({ city: z.string(), }), execute: async () => { return { temperature: 20, conditions: 'Sunny' } }, }) export const mastra = new Mastra({ tools: { weather: weatherTool, }, }) ``` ### tts **類型:** `Record` 提供語音合成功能的文字轉語音 Provider。登記語音 Provider 後,Agent 便可將文字回應轉換為語音音訊。 詳情請參閱[語音文檔](https://mastra.zisheng.pro/zh-HK/guides/voice/overview)。 > **備註:** 大部分使用者會直接在 Agent 上配置語音。此頂層配置用於定義可由多個 Agent 共用的可重用語音 Provider。 ```typescript import { Mastra } from '@mastra/core' import { OpenAIVoice } from '@mastra/voice-openai' export const mastra = new Mastra({ tts: { openai: new OpenAIVoice(), }, }) ``` ### vectors **類型:** `Record` 用於語意搜尋及嵌入的向量儲存。適用於 RAG 管線、相似度搜尋及其他以嵌入為基礎的功能。Mastra 支援多種向量資料庫,包括 Pinecone、配合 pgvector 的 PostgreSQL、OracleDB、MongoDB 等。 詳情請參閱 [RAG 文檔](https://mastra.zisheng.pro/zh-HK/guides/rag/overview)。 > **備註:** 大部分使用者在建立 RAG 管線時會直接建立向量儲存。此頂層配置用於定義可在應用程式各處共用的可重用向量儲存實例。 ```typescript import { Mastra } from '@mastra/core' import { PineconeVector } from '@mastra/pinecone' export const mastra = new Mastra({ vectors: { pinecone: new PineconeVector({ id: 'pinecone-vector', apiKey: process.env.PINECONE_API_KEY, }), }, }) ``` ### workflows **類型:** `Record` Workflow 定義按步驟執行的管線,並提供類型安全的輸入及輸出。對於包含多個步驟且有特定執行次序的工作,可使用 Workflow 控制資料如何在步驟之間流動。 詳情請參閱 [Workflow 文檔](https://mastra.zisheng.pro/zh-HK/docs/workflows/overview)。 ```typescript import { Mastra } from '@mastra/core' import { testWorkflow } from './workflows/test-workflow' export const mastra = new Mastra({ workflows: { testWorkflow, }, }) ``` ### workspace **類型:** `Workspace` Mastra Workspace 為 Agent 提供持久環境,用於儲存檔案及執行指令。除非 Agent 已配置本身的 Workspace,否則會繼承 `Mastra` 類別上的全域 Workspace。 實作詳情請參閱 [Workspace 文檔](https://mastra.zisheng.pro/zh-HK/docs/workspace/overview)。 ```typescript import { Mastra } from '@mastra/core' import { Workspace, LocalFilesystem } from '@mastra/core/workspace' const workspace = new Workspace({ filesystem: new LocalFilesystem({ basePath: './workspace' }), }) const mastra = new Mastra({ workspace, }) ``` ## 打包器選項 ### bundler.entries **類型:** `Record`\ **預設值:** `{}` 與伺服器套件一同輸出的額外程序入口,以輸出名稱對應至相對於 Mastra 目錄之來源路徑的映射表示。每個入口都會在 `.mastra/output` 中成為獨立的 `.mjs`。 此選項適用於在 Mastra 伺服器旁邊(而非伺服器內部)運行的長時間程序,例如 [LiveKit 語音 worker](https://mastra.zisheng.pro/zh-HK/guides/voice/realtime-voice)。入口會與伺服器共用輸出目錄、`package.json` 及已安裝的依賴套件,因此一次 `mastra build` 便可產生一個可部署成品,並以不同指令啟動。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { entries: { 'voice-worker': './voice-worker.ts' }, }, }) ``` 這會在 `.mastra/output/index.mjs` 旁輸出 `.mastra/output/voice-worker.mjs`。系統亦會分析只有額外入口才匯入的依賴套件,並將其安裝至輸出中。 入口名稱可包含 `/`,以建立巢狀輸出。名稱不可為代表伺服器套件的 `index`、代表 Tool 彙集器的 `tools`,亦不可由保留給 Tool 套件的 `tools/` 開頭。 > **備註:** 只有在你完全沒有設定打包器選項時,`mastra build` 才會套用 [`bundler.externals`](#bundlerexternals) 的預設值 `true`。設定 `entries` 後,如果額外入口依賴無法打包的套件(例如原生模組),亦請明確設定 `externals`。 ### bundler.externals **類型:** `boolean | string[]`\ **預設值:** `true` 運行 `mastra build` 時,Mastra 會將項目打包至 `.mastra/output` 目錄。此選項控制哪些套件不納入套件(標記為「external」),並由套件管理器另行安裝。當 Mastra 內部打包器([Rollup](https://rollupjs.org/configuration-options/#external))無法順利打包某些套件時,此選項便很有用。 `mastra build` 預設會將此選項設為 `true`。 各值的含義如下: - `true`:將項目 `package.json` 中列出的所有依賴套件標記為 external - `false`:不將任何依賴套件標記為 external;所有內容會一併打包 - `string[]`:要標記為 external 的套件名稱陣列,其餘套件會一併打包 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { externals: ['some-package', 'another-package'], }, }) ``` ### bundler.sourcemap **類型:** `boolean`\ **預設值:** `false` 為打包後的輸出啟用 source map 產生功能。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { sourcemap: true, }, }) ``` ### bundler.transpilePackages **類型:** `string[]`\ **預設值:** `[]` 列出在建置期間應透過 esbuild 轉譯原始碼的套件。此選項適用於包含 TypeScript 或其他需要在打包前編譯之程式碼的依賴套件。 只有在直接匯入未編譯的原始碼時才需要此選項。如果套件已編譯為 CommonJS 或 ESM,便毋須在此列出。 在 monorepo 設定中,Mastra 會自動偵測 Workspace 套件並將其加入此清單,因此你通常只需指定需要轉譯的外部套件。 Mastra 亦會在建置期間解析 `tsconfig.json` 的 `baseUrl` 及 `paths` 別名,包括指向 TypeScript 原始碼檔案的 ESM 樣式匯入,例如 `~/utils/logger.js`。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { transpilePackages: ['@my-org/shared-utils'], }, }) ``` ## 伺服器選項 ### server.apiRoutes **類型:** `ApiRoute[]` Mastra 會透過伺服器自動公開已登記的 Agent 及 Workflow。如需加入其他行為,你可定義自訂 HTTP 路由。 詳情請參閱[自訂 API 路由](https://mastra.zisheng.pro/zh-HK/docs/server/custom-api-routes)文檔。 ```typescript import { Mastra } from '@mastra/core' import { registerApiRoute } from '@mastra/core/server' export const mastra = new Mastra({ server: { apiRoutes: [ registerApiRoute('/my-custom-route', { method: 'GET', handler: async c => { return c.json({ message: 'Custom route' }) }, }), ], }, }) ``` ### server.auth **類型:** `MastraAuthConfig | MastraAuthProvider` 伺服器的驗證配置。Mastra 支援多種驗證 Provider,包括 JWT、Clerk、Supabase、Firebase、WorkOS 及 Auth0。 詳情請參閱[驗證文檔](https://mastra.zisheng.pro/zh-HK/docs/server/auth)。 ```typescript import { Mastra } from '@mastra/core' import { MastraJwtAuth } from '@mastra/auth' export const mastra = new Mastra({ server: { auth: new MastraJwtAuth({ secret: process.env.MASTRA_JWT_SECRET, mapUserToResourceId: user => user.id, }), }, }) ``` `mapUserToResourceId` 回呼會將已驗證使用者映射至資源 ID,以界定記憶/對話串的範圍。提供此回呼後,系統會在成功驗證後調用它,並將傳回值以 `MASTRA_RESOURCE_ID_KEY` 設定於請求上下文。詳情請參閱[授權(使用者隔離)](https://mastra.zisheng.pro/zh-HK/docs/server/middleware)。 ### server.bodySizeLimit **類型:** `number`\ **預設值:** `4_718_592`(4.5 MB) 請求主體大小上限,以位元組計算。如果應用程式需要處理較大的承載資料,請提高此上限。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { bodySizeLimit: 10 * 1024 * 1024, // 10mb }, }) ``` ### server.mcpOptions **類型:** `object`\ **預設值:** `undefined` 套用至所有 MCP HTTP 及 SSE 路由的 MCP 傳輸選項。對於無法使用持久連線及記憶體內工作階段狀態的無伺服器環境(例如 Cloudflare Workers、Vercel Edge、AWS Lambda 等),可使用此選項啟用無狀態模式。 | 屬性 | 類型 | 預設值 | 說明 | | -------------------- | -------------- | ----------- | ------------------------- | | `serverless` | `boolean` | `false` | 在不管理工作階段的情況下,以無狀態模式運行 MCP | | `sessionIdGenerator` | `() => string` | `undefined` | 自訂工作階段 ID 產生器函數 | ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { mcpOptions: { serverless: true, }, }, }) ``` ### server.build 伺服器功能的建置階段配置。這些選項控制 Swagger UI 及請求記錄等開發工具;它們在本機開發期間啟用,但在生產環境中預設停用。 | 屬性 | 類型 | 預設值 | 說明 | | ------------- | --------- | ------- | ------------------------------------------------------------------------------------------------------------------- | | `swaggerUI` | `boolean` | `false` | 在 `/swagger-ui` 啟用 Swagger UI,以互動方式探索 API(`openAPIDocs` 必須為 `true`) | | `apiReqLogs` | `boolean` | `false` | 啟用將 API 請求記錄至主控台的功能 | | `openAPIDocs` | `boolean` | `false` | 在 `/api/openapi.json` 啟用 OpenAPI 規格。Mastra 內置路由使用 `servers: [{url: "/api"}]`,自訂路由則會按路徑以 `servers: [{url: "/"}]` 覆寫。 | ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { build: { swaggerUI: true, apiReqLogs: true, openAPIDocs: true, }, }, }) ``` ### server.cors **類型:** `CorsOptions | false` 伺服器的 CORS(跨來源資源共享)配置。設為 `false` 可完全停用 CORS。此選項可為所有路由套用同一政策。如需自訂個別路由的政策,請使用 [`registerApiRoute()`](https://mastra.zisheng.pro/zh-HK/reference/server/register-api-route) 中的 `cors` 選項。 | 屬性 | 類型 | 預設值 | 說明 | | --------------- | -------------------- | -------------------------------------------------------------------------------------- | --------------- | | `origin` | `string \| string[]` | `'*'` | CORS 請求的來源 | | `allowMethods` | `string[]` | `['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']` | HTTP 方法 | | `allowHeaders` | `string[]` | `['Content-Type', 'Authorization', 'x-mastra-client-type', 'x-mastra-dev-playground']` | 請求標頭 | | `exposeHeaders` | `string[]` | `['Content-Length', 'X-Requested-With']` | 瀏覽器標頭 | | `credentials` | `boolean` | `false` | 憑證(Cookie、授權標頭) | | `maxAge` | `number` | `3600` | 預檢請求的快取時間(秒) | ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { cors: { origin: ['https://example.com'], allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization'], credentials: false, }, }, }) ``` ### server.host **類型:** `string`\ **預設值:** `localhost`(如已設定,則使用 `MASTRA_HOST` 環境變數) Mastra 開發伺服器綁定的主機位址。如已設定 `MASTRA_HOST` 環境變數,其值會優先於預設值。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { host: '0.0.0.0', }, }) ``` ### server.https **類型:** `{ key: Buffer; cert: Buffer }` 使用 TLS 運行開發伺服器的 HTTPS 配置。Mastra 透過 `mastra dev --https` 標記支援本機 HTTPS 開發,並會自動建立及管理憑證。如要自行管理憑證,請提供你的金鑰及憑證檔案: ```typescript import { Mastra } from '@mastra/core' import fs from 'node:fs' export const mastra = new Mastra({ server: { https: { key: fs.readFileSync('path/to/key.pem'), cert: fs.readFileSync('path/to/cert.pem'), }, }, }) ``` ### server.middleware **類型:** `Middleware | Middleware[]` 自訂中介軟件函數,用於在路由處理器之前或之後攔截請求。中介軟件可用於驗證、記錄、注入請求專屬上下文,或加入標頭。每個中介軟件都會接收 Hono `Context` 及 `next` 函數。傳回 `Response` 可提前終止請求,調用 `next()` 則可繼續處理。 詳情請參閱[中介軟件文檔](https://mastra.zisheng.pro/zh-HK/docs/server/middleware)。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { middleware: [ { handler: async (c, next) => { const authHeader = c.req.header('Authorization') if (!authHeader) { return new Response('Unauthorized', { status: 401 }) } await next() }, path: '/api/*', }, ], }, }) ``` ### server.onError **類型:** `(err: Error, c: Context) => Response | Promise` 發生未處理錯誤時調用的自訂錯誤處理器。你可用此處理器自訂錯誤回應、將錯誤記錄至 Sentry 等外部服務,或實作自訂錯誤格式。 所有伺服器轉接器均支援此 hook。`c` 參數提供與 Hono 相容的上下文物件:對於非 Hono 轉接器(Koa、Express、Fastify),系統會提供 shim,其中包含 `c.json()` 及 `c.req.path` 等常用方法。 ```typescript import { Mastra } from '@mastra/core' import * as Sentry from '@sentry/node' export const mastra = new Mastra({ server: { onError: (err, c) => { Sentry.captureException(err) return c.json( { error: err.message, timestamp: new Date().toISOString(), }, 500, ) }, }, }) ``` ### server.onValidationError **類型:** `(error: ZodError, context: 'query' | 'body' | 'path') => { status: number; body: unknown } | undefined` 請求未能通過 Zod schema 驗證時調用的自訂處理器。你可用此處理器自訂驗證錯誤回應、更改狀態碼,或按 API 標準格式化錯誤。 傳回 `{ status, body }` 物件可覆寫預設的 `400` 回應,傳回 `undefined` 則使用預設行為。所有伺服器轉接器(Hono、Express、Fastify、Koa)均支援此 hook。 `context` 參數表示請求中哪一部分未能通過驗證: - `'query'`:查詢參數 - `'body'`:請求主體 - `'path'`:路徑參數 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { onValidationError: (error, context) => ({ status: 422, body: { ok: false, errors: error.issues.map(i => ({ path: i.path.join('.'), message: i.message, })), source: context, }, }), }, }) ``` 你亦可在透過 `createRoute()` 建立的個別路由上設定 `onValidationError`。路由層級的 hook 優先於伺服器層級的 hook。 ### server.port **類型:** `number`\ **預設值:** `4111`(如已設定,則使用 `PORT` 環境變數) Mastra 開發伺服器綁定的連接埠。如已設定 `PORT` 環境變數,其值會優先於預設值。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { port: 8080, }, }) ``` ### server.studioBase **類型:** `string`\ **預設值:** `/` 用於託管 [Studio](https://mastra.zisheng.pro/zh-HK/docs/studio/overview) 的基礎路徑。你可使用此選項,在現有應用程式的子路徑(而非根路徑)託管 Studio。 此選項適合用於整合現有應用程式、使用 Cloudflare Zero Trust 等可受惠於共用網域的驗證工具,或在單一網域下管理多項服務。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { studioBase: '/my-mastra-studio', }, }) ``` **URL 範例:** - 預設:`http://localhost:4111/`(Studio 位於根路徑) - 使用 `studioBase`:`http://localhost:4111/my-mastra-studio/`(Studio 位於子路徑) ### server.timeout **類型:** `number`\ **預設值:** `180000`(3 分鐘) 請求逾時時間,以毫秒計算。超過此時間的請求將會終止。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { timeout: 30000, // 30 seconds }, }) ```