配置
以下參考資料涵蓋 Mastra 支援的所有選項。你可建立 Mastra 類別的實例,以初始化及配置 Mastra。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
// Your options...
})
頂層選項頂層選項 的直接連結
agentsagents 的直接連結
類型: Record<string, Agent>
以名稱為鍵的 Agent 實例記錄。Agent 是可使用 AI 模型、Tool 及記憶作出決策和採取行動的自主系統。
詳情請參閱 Agent 文檔。
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',
}),
},
})
backgroundTasksbackgroundTasks 的直接連結
類型: BackgroundTaskManagerConfig
啟用並配置背景工作管理器。啟用後,Agent 可分派長時間運行的 Tool 調用(包括子 Agent 調用)以非同步方式執行,同時繼續 Agent 迴圈。工作會持久保存,因此必須配置 storage 後端。
詳情請參閱背景工作文檔。
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:
globalConcurrency?:
perAgentConcurrency?:
backpressure?:
defaultTimeoutMs?:
defaultRetries?:
maxRetries?:
retryDelayMs?:
backoffMultiplier?:
maxRetryDelayMs?:
retryableErrors?:
cleanup?:
completedTtlMs?:
failedTtlMs?:
cleanupIntervalMs?:
waitTimeoutMs?:
onTaskComplete?:
onTaskFailed?:
deployerdeployer 的直接連結
類型: MastraDeployer
用於將應用程式發佈至雲端平台的部署 Provider。
詳情請參閱部署文檔。
import { Mastra } from '@mastra/core'
import { NetlifyDeployer } from '@mastra/deployer-netlify'
export const mastra = new Mastra({
deployer: new NetlifyDeployer(),
})
eventsevents 的直接連結
類型: Record<string, EventHandler | EventHandler[]>
內部發佈/訂閱系統的事件處理器。將事件主題映射至處理器函數;事件發佈至相應主題時,系統會調用這些函數。
此選項供 Mastra 的 Workflow 引擎內部使用。大部分使用者毋須配置此選項。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
events: {
'my-topic': async event => {
console.log('Event received:', event)
},
},
})
gatewaysgateways 的直接連結
類型: Record<string, MastraModelGateway>
用於存取 LLM Provider 的自訂模型路由閘道。閘道會處理 Provider 專用的驗證、URL 建構及模型解析。你可用此選項支援自訂或自行託管的 LLM Provider。
詳情請參閱自訂閘道文檔。
import { Mastra } from '@mastra/core'
import { MyPrivateGateway } from './gateways'
export const mastra = new Mastra({
gateways: {
private: new MyPrivateGateway(),
},
})
idGeneratoridGenerator 的直接連結
類型: (context?: IdGeneratorContext) => string
預設值: crypto.randomUUID()
用於建立唯一標識符的自訂 ID 產生器函數。Mastra 會傳入可選的上下文,讓你按正在建立的內容產生 ID。
IdGeneratorContext 包括:
idType:'thread' | 'message' | 'run' | 'step' | 'generic'source?:'agent' | 'workflow' | 'memory'entityId?:提出請求的 Agent/Workflow/記憶實體 IDthreadId?:相關時使用的對話串 ID(例如建立訊息 ID 時)resourceId?:相關時使用的資源 ID(例如使用者範圍的對話串)role?:建立訊息 ID 時的訊息角色stepType?:建立步驟 ID 時的 Workflow 步驟類型
Mastra 會在內部使用此選項,為 Workflow 運行、Agent 對話及其他資源建立 ID。大部分使用者毋須配置此選項。
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()
},
})
loggerlogger 的直接連結
類型: IMastraLogger | false
預設值: 開發環境使用 INFO 級別的 ConsoleLogger,生產環境則使用 WARN 級別
用於應用程式記錄及除錯的 Logger 實作。設為 false 可完全停用記錄功能。
詳情請參閱記錄文檔。
import { Mastra } from '@mastra/core'
import { PinoLogger } from '@mastra/loggers'
export const mastra = new Mastra({
logger: new PinoLogger({ name: 'MyApp', level: 'debug' }),
})
mcpServersmcpServers 的直接連結
類型: Record<string, MCPServerBase>
向 MCP 相容用戶端公開 Mastra Tool、Agent、Workflow 及資源的 MCP(Model Context Protocol)伺服器。你可用此選項編寫自有 MCP 伺服器,供任何支援此協定的系統使用。
詳情請參閱 MCP 概覽。
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,
},
})
memorymemory 的直接連結
類型: Record<string, MastraMemory>
可供 Agent 引用的記憶實例登記冊。記憶會保留過往對話的相關資料,令 Agent 在多次互動之間保持連貫。Mastra 支援保存近期訊息的訊息記錄,以及保存使用者專屬持久資料的工作記憶。語意回憶會按相關性擷取較舊的訊息。
詳情請參閱記憶文檔。
大部分使用者會直接在 Agent 上配置記憶。此頂層配置用於定義可由多個 Agent 共用的可重用記憶實例。
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,
},
}),
},
})
observabilityobservability 的直接連結
類型: ObservabilityEntrypoint
Mastra 為 AI 應用程式提供可觀測性功能。你可使用能理解 AI 特有模式的工具監察 LLM 操作、追蹤 Agent 決策,以及為複雜 Workflow 除錯。追蹤功能會擷取模型互動、Agent 執行路徑、Tool 調用及 Workflow 步驟。
詳情請參閱可觀測性文檔。
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()],
},
},
}),
})
processorsprocessors 的直接連結
類型: Record<string, Processor>
用於轉換 Agent 輸入及輸出的輸入/輸出處理器。處理器會在 Agent 執行管線的特定位置運行,讓你在輸入送達語言模型前修改輸入,或在輸出傳回前修改輸出。你可使用處理器加入防護機制、偵測提示注入、審核內容,或套用自訂業務邏輯。
詳情請參閱處理器文檔。
大部分使用者會直接在 Agent 上配置處理器。此頂層配置用於定義可由多個 Agent 共用的可重用處理器實例。
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'],
}),
},
})
pubsubpubsub 的直接連結
類型: PubSub
預設值: EventEmitterPubSub
用於元件之間事件驅動通訊的發佈/訂閱系統。Mastra 會在內部使用此系統處理 Workflow 事件及元件通訊。
此選項供 Mastra 內部使用。大部分使用者毋須配置此選項。
import { Mastra } from '@mastra/core'
import { CustomPubSub } from './pubsub'
export const mastra = new Mastra({
pubsub: new CustomPubSub(),
})
scorersscorers 的直接連結
類型: Record<string, Scorer>
Scorer 會評估 Agent 回應及 Workflow 輸出的質素,並透過模型評分、規則及統計方法提供可量化的指標,以衡量 Agent 質素。你可使用 Scorer 追蹤效能及比較不同方法,亦可找出有待改善之處。
詳情請參閱 Scorer 文檔。
大部分使用者會直接在 Agent 上配置 Scorer。此頂層配置用於定義可由多個 Agent 共用的可重用 Scorer 實例。
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' }),
},
})
storagestorage 的直接連結
類型: MastraCompositeStore
用於持久保存應用程式資料的儲存 Provider。記憶、Workflow、Trace 及其他需要持久儲存的元件都會使用此 Provider。Mastra 支援多種資料庫後端,包括 PostgreSQL、MongoDB、libSQL 等。
詳情請參閱儲存文檔。
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',
}),
})
toolstools 的直接連結
類型: Record<string, Tool>
Tool 是可重用的函數,Agent 可用它與外部系統互動。每個 Tool 都會定義輸入、輸出及執行邏輯。
詳情請參閱 Tool 文檔。
大部分使用者會直接在 Agent 上配置 Tool。此頂層配置用於定義可由多個 Agent 共用的可重用 Tool。
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,
},
})
ttstts 的直接連結
類型: Record<string, MastraVoice>
提供語音合成功能的文字轉語音 Provider。登記語音 Provider 後,Agent 便可將文字回應轉換為語音音訊。
詳情請參閱語音文檔。
大部分使用者會直接在 Agent 上配置語音。此頂層配置用於定義可由多個 Agent 共用的可重用語音 Provider。
import { Mastra } from '@mastra/core'
import { OpenAIVoice } from '@mastra/voice-openai'
export const mastra = new Mastra({
tts: {
openai: new OpenAIVoice(),
},
})
vectorsvectors 的直接連結
類型: Record<string, MastraVector>
用於語意搜尋及嵌入的向量儲存。適用於 RAG 管線、相似度搜尋及其他以嵌入為基礎的功能。Mastra 支援多種向量資料庫,包括 Pinecone、配合 pgvector 的 PostgreSQL、OracleDB、MongoDB 等。
詳情請參閱 RAG 文檔。
大部分使用者在建立 RAG 管線時會直接建立向量儲存。此頂層配置用於定義可在應用程式各處共用的可重用向量儲存實例。
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,
}),
},
})
workflowsworkflows 的直接連結
類型: Record<string, Workflow>
Workflow 定義按步驟執行的管線,並提供類型安全的輸入及輸出。對於包含多個步驟且有特定執行次序的工作,可使用 Workflow 控制資料如何在步驟之間流動。
詳情請參閱 Workflow 文檔。
import { Mastra } from '@mastra/core'
import { testWorkflow } from './workflows/test-workflow'
export const mastra = new Mastra({
workflows: {
testWorkflow,
},
})
workspaceworkspace 的直接連結
類型: Workspace
Mastra Workspace 為 Agent 提供持久環境,用於儲存檔案及執行指令。除非 Agent 已配置本身的 Workspace,否則會繼承 Mastra 類別上的全域 Workspace。
實作詳情請參閱 Workspace 文檔。
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.entriesbundler.entries 的直接連結
類型: Record<string, string>
預設值: {}
與伺服器套件一同輸出的額外程序入口,以輸出名稱對應至相對於 Mastra 目錄之來源路徑的映射表示。每個入口都會在 .mastra/output 中成為獨立的 <name>.mjs。
此選項適用於在 Mastra 伺服器旁邊(而非伺服器內部)運行的長時間程序,例如 LiveKit 語音 worker。入口會與伺服器共用輸出目錄、package.json 及已安裝的依賴套件,因此一次 mastra build 便可產生一個可部署成品,並以不同指令啟動。
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 的預設值 true。設定 entries 後,如果額外入口依賴無法打包的套件(例如原生模組),亦請明確設定 externals。
bundler.externalsbundler.externals 的直接連結
類型: boolean | string[]
預設值: true
運行 mastra build 時,Mastra 會將項目打包至 .mastra/output 目錄。此選項控制哪些套件不納入套件(標記為「external」),並由套件管理器另行安裝。當 Mastra 內部打包器(Rollup)無法順利打包某些套件時,此選項便很有用。
mastra build 預設會將此選項設為 true。
各值的含義如下:
true:將項目package.json中列出的所有依賴套件標記為 externalfalse:不將任何依賴套件標記為 external;所有內容會一併打包string[]:要標記為 external 的套件名稱陣列,其餘套件會一併打包
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
bundler: {
externals: ['some-package', 'another-package'],
},
})
bundler.sourcemapbundler.sourcemap 的直接連結
類型: boolean
預設值: false
為打包後的輸出啟用 source map 產生功能。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
bundler: {
sourcemap: true,
},
})
bundler.transpilePackagesbundler.transpilePackages 的直接連結
類型: string[]
預設值: []
列出在建置期間應透過 esbuild 轉譯原始碼的套件。此選項適用於包含 TypeScript 或其他需要在打包前編譯之程式碼的依賴套件。
只有在直接匯入未編譯的原始碼時才需要此選項。如果套件已編譯為 CommonJS 或 ESM,便毋須在此列出。
在 monorepo 設定中,Mastra 會自動偵測 Workspace 套件並將其加入此清單,因此你通常只需指定需要轉譯的外部套件。
Mastra 亦會在建置期間解析 tsconfig.json 的 baseUrl 及 paths 別名,包括指向 TypeScript 原始碼檔案的 ESM 樣式匯入,例如 ~/utils/logger.js。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
bundler: {
transpilePackages: ['@my-org/shared-utils'],
},
})
伺服器選項伺服器選項 的直接連結
server.apiRoutesserver.apiRoutes 的直接連結
類型: ApiRoute[]
Mastra 會透過伺服器自動公開已登記的 Agent 及 Workflow。如需加入其他行為,你可定義自訂 HTTP 路由。
詳情請參閱自訂 API 路由文檔。
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.authserver.auth 的直接連結
類型: MastraAuthConfig | MastraAuthProvider
伺服器的驗證配置。Mastra 支援多種驗證 Provider,包括 JWT、Clerk、Supabase、Firebase、WorkOS 及 Auth0。
詳情請參閱驗證文檔。
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 設定於請求上下文。詳情請參閱授權(使用者隔離)。
server.bodySizeLimitserver.bodySizeLimit 的直接連結
類型: number
預設值: 4_718_592(4.5 MB)
請求主體大小上限,以位元組計算。如果應用程式需要處理較大的承載資料,請提高此上限。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
bodySizeLimit: 10 * 1024 * 1024, // 10mb
},
})
server.mcpOptionsserver.mcpOptions 的直接連結
類型: object
預設值: undefined
套用至所有 MCP HTTP 及 SSE 路由的 MCP 傳輸選項。對於無法使用持久連線及記憶體內工作階段狀態的無伺服器環境(例如 Cloudflare Workers、Vercel Edge、AWS Lambda 等),可使用此選項啟用無狀態模式。
| 屬性 | 類型 | 預設值 | 說明 |
|---|---|---|---|
serverless | boolean | false | 在不管理工作階段的情況下,以無狀態模式運行 MCP |
sessionIdGenerator | () => string | undefined | 自訂工作階段 ID 產生器函數 |
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
mcpOptions: {
serverless: true,
},
},
})
server.buildserver.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: "/"}] 覆寫。 |
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
build: {
swaggerUI: true,
apiReqLogs: true,
openAPIDocs: true,
},
},
})
server.corsserver.cors 的直接連結
類型: CorsOptions | false
伺服器的 CORS(跨來源資源共享)配置。設為 false 可完全停用 CORS。此選項可為所有路由套用同一政策。如需自訂個別路由的政策,請使用 registerApiRoute() 中的 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 | 預檢請求的快取時間(秒) |
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.hostserver.host 的直接連結
類型: string
預設值: localhost(如已設定,則使用 MASTRA_HOST 環境變數)
Mastra 開發伺服器綁定的主機位址。如已設定 MASTRA_HOST 環境變數,其值會優先於預設值。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
host: '0.0.0.0',
},
})
server.httpsserver.https 的直接連結
類型: { key: Buffer; cert: Buffer }
使用 TLS 運行開發伺服器的 HTTPS 配置。Mastra 透過 mastra dev --https 標記支援本機 HTTPS 開發,並會自動建立及管理憑證。如要自行管理憑證,請提供你的金鑰及憑證檔案:
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.middlewareserver.middleware 的直接連結
類型: Middleware | Middleware[]
自訂中介軟件函數,用於在路由處理器之前或之後攔截請求。中介軟件可用於驗證、記錄、注入請求專屬上下文,或加入標頭。每個中介軟件都會接收 Hono Context 及 next 函數。傳回 Response 可提前終止請求,調用 next() 則可繼續處理。
詳情請參閱中介軟件文檔。
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.onErrorserver.onError 的直接連結
類型: (err: Error, c: Context) => Response | Promise<Response>
發生未處理錯誤時調用的自訂錯誤處理器。你可用此處理器自訂錯誤回應、將錯誤記錄至 Sentry 等外部服務,或實作自訂錯誤格式。
所有伺服器轉接器均支援此 hook。c 參數提供與 Hono 相容的上下文物件:對於非 Hono 轉接器(Koa、Express、Fastify),系統會提供 shim,其中包含 c.json() 及 c.req.path 等常用方法。
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.onValidationErrorserver.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':路徑參數
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.portserver.port 的直接連結
類型: number
預設值: 4111(如已設定,則使用 PORT 環境變數)
Mastra 開發伺服器綁定的連接埠。如已設定 PORT 環境變數,其值會優先於預設值。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
port: 8080,
},
})
server.studioBaseserver.studioBase 的直接連結
類型: string
預設值: /
用於託管 Studio 的基礎路徑。你可使用此選項,在現有應用程式的子路徑(而非根路徑)託管 Studio。
此選項適合用於整合現有應用程式、使用 Cloudflare Zero Trust 等可受惠於共用網域的驗證工具,或在單一網域下管理多項服務。
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.timeoutserver.timeout 的直接連結
類型: number
預設值: 180000(3 分鐘)
請求逾時時間,以毫秒計算。超過此時間的請求將會終止。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
timeout: 30000, // 30 seconds
},
})