> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # 設定 下列參考文件涵蓋 Mastra 支援的所有選項。建立 [`Mastra` 類別](https://mastra.zisheng.pro/zh-TW/reference/core/mastra-class)的執行個體即可初始化並設定 Mastra。 ```ts import { Mastra } from '@mastra/core' export const mastra = new Mastra({ // Your options... }) ``` ## 頂層選項 ### agents **型別:** `Record` 以名稱為 key 的 Agent 執行個體 record。Agent 是自主系統,可以使用 AI 模型、Tool 與 Memory 做出決策並採取行動。 詳情請參閱 [Agent 文件](https://mastra.zisheng.pro/zh-TW/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 呼叫(包括 subagent 叫用),讓它們在 Agent loop 繼續執行時以非同步方式執行。工作會持久化,因此必須設定 `storage` 後端。 詳情請參閱[背景工作文件](https://mastra.zisheng.pro/zh-TW/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 loop 中同步執行 Tool。 (Default: `'queue'`) **defaultTimeoutMs** (`number`): 每項工作的預設逾時時間(毫秒)。可針對個別 Tool 或呼叫覆寫。 (Default: `300000`) **defaultRetries** (`RetryConfig`): 套用至失敗工作的預設重試 policy。 **defaultRetries.maxRetries** (`number`): 工作標示為失敗前的重試次數上限。 **defaultRetries.retryDelayMs** (`number`): 每次重試之間的延遲時間(毫秒)。 **defaultRetries.backoffMultiplier** (`number`): 每次後續嘗試套用至 retryDelayMs 的乘數。 **defaultRetries.maxRetryDelayMs** (`number`): 無論退避值為何,重試延遲的上限。 **defaultRetries.retryableErrors** (`(error: Error) => boolean`): 判斷特定錯誤是否應重試的 predicate。預設會重試所有錯誤。 **cleanup** (`CleanupConfig`): 控制工作記錄的保留時間,以及清理作業的執行頻率。 **cleanup.completedTtlMs** (`number`): 已完成工作記錄的保留時間(毫秒)。預設為 1 小時。 **cleanup.failedTtlMs** (`number`): 失敗工作記錄的保留時間(毫秒)。預設為 24 小時。 **cleanup.cleanupIntervalMs** (`number`): 清理作業的執行間隔(毫秒)。預設為 1 分鐘。 **waitTimeoutMs** (`number`): Agent loop 在繼續前等待背景工作完成的時間。如果工作未在此時間內完成,loop 會繼續執行而不設定 isContinued。預設為 undefined(不等待)。可針對個別 Agent 或 Tool 覆寫。 **onTaskComplete** (`(task: BackgroundTask) => void | Promise`): 任何背景工作成功完成時叫用的全域 callback。除了各 Tool 與各 Agent 的 callback 之外,也會觸發此 callback。 **onTaskFailed** (`(task: BackgroundTask) => void | Promise`): 任何背景工作失敗時叫用的全域 callback。除了各 Tool 與各 Agent 的 callback 之外,也會觸發此 callback。 ### deployer **型別:** `MastraDeployer` 用於將應用程式發布至雲端平台的部署 Provider。 詳情請參閱[部署文件](https://mastra.zisheng.pro/zh-TW/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` 內部 pub/sub 系統的事件 handler。將事件 topic 對應至 handler 函式;事件發布至這些 topic 時會呼叫對應函式。 > **警告:** 此選項由 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 的自訂模型 router Gateway。Gateway 會處理 Provider 專屬驗證、URL 建構與模型解析。可用來支援自訂或自行託管的 LLM Provider。 詳情請參閱[自訂 Gateway 文件](https://mastra.zisheng.pro/zh-TW/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 generator 函式。Mastra 會傳入選填的 context,讓你能依據所建立的項目產生 ID。 `IdGeneratorContext` 包括: - `idType`:`'thread' | 'message' | 'run' | 'step' | 'generic'` - `source?`:`'agent' | 'workflow' | 'memory'` - `entityId?`:發出要求的 Agent/Workflow/Memory 實體 ID - `threadId?`:相關時的 thread ID(例如建立訊息 ID 時) - `resourceId?`:相關時的 resource ID(例如使用者範圍的 thread) - `role?`:建立訊息 ID 時的訊息角色 - `stepType?`:建立 step ID 時的 Workflow step 類型 > **警告:** Mastra 會在內部使用此選項,為 Workflow 執行作業、Agent 對話與其他 resource 建立 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-TW/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 與 resource 的 MCP(Model Context Protocol)伺服器。可用來編寫自己的 MCP 伺服器,供任何支援此通訊協定的系統使用。 詳情請參閱 [MCP 概覽](https://mastra.zisheng.pro/zh-TW/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 參照的 Memory 執行個體 registry。Memory 會保留過往對話中的相關資訊,讓 Agent 在多次互動之間保持連貫。Mastra 支援用於近期訊息的訊息歷程,以及持久保存使用者專屬詳細資料的 Working Memory。語意回想則會依相關性擷取較舊的訊息。 詳情請參閱 [Memory 文件](https://mastra.zisheng.pro/zh-TW/docs/memory/overview)。 > **備註:** 大多數使用者會直接在 Agent 上設定 Memory。此頂層設定用於定義可在多個 Agent 之間共用的可重複使用 Memory 執行個體。 ```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 應用程式提供 Observability 功能。你可以透過瞭解 AI 專屬模式的 Tool,監控 LLM 操作、追蹤 Agent 決策,並對複雜 Workflow 進行偵錯。Trace 會擷取模型互動、Agent 執行路徑、Tool 呼叫與 Workflow step。 詳情請參閱 [Observability 文件](https://mastra.zisheng.pro/zh-TW/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 輸入與輸出的 input/output processor。Processor 會在 Agent 執行 pipeline 的特定位置執行,讓你能在輸入送達語言模型前加以修改,或在輸出傳回前加以修改。可使用 processor 新增 guardrail、偵測 prompt injection、進行內容審核,或套用自訂業務邏輯。 詳情請參閱 [Processor 文件](https://mastra.zisheng.pro/zh-TW/docs/agents/processors)。 > **備註:** 大多數使用者會直接在 Agent 上設定 processor。此頂層設定用於定義可在多個 Agent 之間共用的可重複使用 processor 執行個體。 ```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` 用於元件之間事件驅動通訊的 pub/sub 系統。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-TW/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` 用於持久儲存應用程式資料的 storage Provider。由 Memory、Workflow、Trace 及其他需要持久性的元件使用。Mastra 支援多種資料庫後端,包括 PostgreSQL、MongoDB、libSQL 等。 詳情請參閱 [Storage 文件](https://mastra.zisheng.pro/zh-TW/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-TW/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` 提供語音合成功能的 text-to-speech Provider。註冊 voice Provider 可讓 Agent 將文字回應轉換為語音音訊。 詳情請參閱 [Voice 文件](https://mastra.zisheng.pro/zh-TW/guides/voice/overview)。 > **備註:** 大多數使用者會直接在 Agent 上設定 voice。此頂層設定用於定義可在多個 Agent 之間共用的可重複使用 voice Provider。 ```typescript import { Mastra } from '@mastra/core' import { OpenAIVoice } from '@mastra/voice-openai' export const mastra = new Mastra({ tts: { openai: new OpenAIVoice(), }, }) ``` ### vectors **型別:** `Record` 用於語意搜尋與 embedding 的 vector store。應用於 RAG pipeline、相似度搜尋及其他 embedding 功能。Mastra 支援多種向量資料庫,包括 Pinecone、搭配 pgvector 的 PostgreSQL、OracleDB、MongoDB 等。 詳情請參閱 [RAG 文件](https://mastra.zisheng.pro/zh-TW/guides/rag/overview)。 > **備註:** 大多數使用者會在建立 RAG pipeline 時直接建立 vector store。此頂層設定用於定義可在應用程式中共用的可重複使用 vector store 執行個體。 ```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 會定義具有型別安全輸入與輸出的 step 式執行 pipeline。需要多個 step 且有特定執行順序時,可使用 Workflow 來控制資料在 step 之間的流動方式。 詳情請參閱 [Workflow 文件](https://mastra.zisheng.pro/zh-TW/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-TW/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 選項 ### bundler.entries **型別:** `Record`\ **預設值:** `{}` 與伺服器 bundle 一同輸出的其他處理程序 entry,以輸出名稱到 Mastra 目錄相對來源路徑的 map 表示。每個 entry 都會在 `.mastra/output` 中成為獨立的 `.mjs`。 可用於在 Mastra 伺服器旁而非其中執行的長時間執行處理程序,例如 [LiveKit voice worker](https://mastra.zisheng.pro/zh-TW/guides/voice/realtime-voice)。entry 會與伺服器共用輸出目錄、`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`。系統也會分析只由其他 entry 匯入的相依套件,並將它們安裝至輸出。 entry 名稱可包含 `/` 以巢狀排列輸出。名稱不能是伺服器 bundle 所用的 `index`、Tool aggregator 所用的 `tools`,也不能以為 Tool bundle 保留的 `tools/` 開頭。 > **備註:** 只有完全未設定任何 bundler 選項時,`mastra build` 才會套用 [`bundler.externals`](#bundlerexternals) 的預設值 `true`。一旦設定 `entries`,若其他 entry 依賴無法封裝的套件(例如原生模組),也請明確設定 `externals`。 ### bundler.externals **型別:** `boolean | string[]`\ **預設值:** `true` 執行 `mastra build` 時,Mastra 會將專案封裝至 `.mastra/output` 目錄。此選項控制要從 bundle 排除(標記為「external」)並透過套件管理器另外安裝的套件。當 Mastra 內部 bundler([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,便不需要列於此處。 Mastra 會自動偵測 monorepo 設定中的 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 選項 ### server.apiRoutes **型別:** `ApiRoute[]` Mastra 會透過伺服器自動公開已註冊的 Agent 與 Workflow。若需其他行為,可以定義自己的 HTTP route。 詳情請參閱[自訂 API route](https://mastra.zisheng.pro/zh-TW/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-TW/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` callback 會將已驗證使用者對應至 resource ID,以界定 Memory/thread 範圍。若有提供,此 callback 會在驗證成功後呼叫,傳回值則會在 request context 中設為 `MASTRA_RESOURCE_ID_KEY`。詳情請參閱[授權(使用者隔離)](https://mastra.zisheng.pro/zh-TW/docs/server/middleware)。 ### server.bodySizeLimit **型別:** `number`\ **預設值:** `4_718_592`(4.5 MB) 要求本文的大小上限(位元組)。如果應用程式需要處理更大的 payload,請提高此限制。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { bodySizeLimit: 10 * 1024 * 1024, // 10mb }, }) ``` ### server.mcpOptions **型別:** `object`\ **預設值:** `undefined` 套用至所有 MCP HTTP 與 SSE route 的 MCP transport 選項。在無法使用持久連線與記憶體內 session 狀態的 serverless 環境(Cloudflare Workers、Vercel Edge、AWS Lambda 等),可使用此選項啟用無狀態模式。 | 屬性 | 型別 | 預設值 | 說明 | | -------------------- | -------------- | ----------- | --------------------------- | | `serverless` | `boolean` | `false` | 以無狀態模式執行 MCP,不進行 session 管理 | | `sessionIdGenerator` | `() => string` | `undefined` | 自訂 session ID generator 函式 | ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { mcpOptions: { serverless: true, }, }, }) ``` ### server.build 伺服器功能的建置階段設定。這些選項控制 Swagger UI 與要求記錄等開發 Tool;它們會在本機開發期間啟用,但在正式環境中預設停用。 | 屬性 | 型別 | 預設值 | 說明 | | ------------- | --------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- | | `swaggerUI` | `boolean` | `false` | 在 `/swagger-ui` 啟用 Swagger UI,以互動方式探索 API(`openAPIDocs` 必須設為 `true`) | | `apiReqLogs` | `boolean` | `false` | 啟用 API 要求的 console 記錄 | | `openAPIDocs` | `boolean` | `false` | 在 `/api/openapi.json` 啟用 OpenAPI 規格。Mastra 內建 route 使用 `servers: [{url: "/api"}]`,自訂 route 則會取得各路徑的 `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(Cross-Origin Resource Sharing)設定。設為 `false` 可完全停用 CORS。此選項可為所有 route 套用同一 policy。若要為自訂 route 使用專屬 policy,請使用 [`registerApiRoute()`](https://mastra.zisheng.pro/zh-TW/reference/server/register-api-route) 的 `cors` 選項。 | 屬性 | 型別 | 預設值 | 說明 | | --------------- | -------------------- | -------------------------------------------------------------------------------------- | -------------------- | | `origin` | `string \| string[]` | `'*'` | CORS 要求的 origin | | `allowMethods` | `string[]` | `['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']` | HTTP 方法 | | `allowHeaders` | `string[]` | `['Content-Type', 'Authorization', 'x-mastra-client-type', 'x-mastra-dev-playground']` | 要求 header | | `exposeHeaders` | `string[]` | `['Content-Length', 'X-Requested-With']` | 瀏覽器 header | | `credentials` | `boolean` | `false` | 認證(cookie、授權 header) | | `maxAge` | `number` | `3600` | preflight 要求的快取時間(秒) | ```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 開發伺服器綁定的 host 位址。如果已設定 `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` flag 支援本機 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[]` 在 route handler 之前或之後攔截要求的自訂 middleware 函式。Middleware 可用於驗證、記錄、注入要求專屬 context 或新增 header。每個 middleware 都會接收 Hono `Context` 與 `next` 函式。傳回 `Response` 可立即結束要求;呼叫 `next()` 則繼續處理。 詳情請參閱 [Middleware 文件](https://mastra.zisheng.pro/zh-TW/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` 發生未處理錯誤時呼叫的自訂錯誤 handler。可用來自訂錯誤回應、將錯誤記錄至 Sentry 等外部服務,或實作自訂錯誤格式。 所有伺服器 adapter 都支援此 hook。`c` 參數提供與 Hono 相容的 context 物件:若 adapter 並非 Hono(Koa、Express、Fastify),系統會提供包含 `c.json()` 與 `c.req.path` 等常用方法的 shim。 ```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 驗證時呼叫的自訂 handler。可用來自訂驗證錯誤回應、變更狀態碼,或依 API 標準格式化錯誤。 傳回 `{ status, body }` 物件可覆寫預設的 `400` 回應;傳回 `undefined` 則使用預設行為。所有伺服器 adapter(Hono、Express、Fastify、Koa)都支援此 hook。 `context` 參數表示要求中哪個部分未通過驗證: - `'query'`: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()` 建立的個別 route 上設定 `onValidationError`。route 層級的 hook 優先於 server 層級的 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-TW/docs/studio/overview) 的基底路徑。可用來將 Studio 託管於現有應用程式的子路徑,而非根目錄。 整合現有應用程式、使用 Cloudflare Zero Trust 等能受益於共用網域的驗證 Tool,或在單一網域下管理多項服務時,此選項很有用。 ```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 }, }) ```