設定
下列參考文件涵蓋 Mastra 支援的所有選項。建立 Mastra 類別的執行個體即可初始化並設定 Mastra。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
// Your options...
})
頂層選項「頂層選項」的直接連結
agents「agents」的直接連結
型別: Record<string, Agent>
以名稱為 key 的 Agent 執行個體 record。Agent 是自主系統,可以使用 AI 模型、Tool 與 Memory 做出決策並採取行動。
詳情請參閱 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',
}),
},
})
backgroundTasks「backgroundTasks」的直接連結
型別: BackgroundTaskManagerConfig
啟用並設定背景工作管理器。啟用後,Agent 可派送長時間執行的 Tool 呼叫(包括 subagent 叫用),讓它們在 Agent loop 繼續執行時以非同步方式執行。工作會持久化,因此必須設定 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?:
deployer「deployer」的直接連結
型別: MastraDeployer
用於將應用程式發布至雲端平台的部署 Provider。
詳情請參閱部署文件。
import { Mastra } from '@mastra/core'
import { NetlifyDeployer } from '@mastra/deployer-netlify'
export const mastra = new Mastra({
deployer: new NetlifyDeployer(),
})
events「events」的直接連結
型別: Record<string, EventHandler | EventHandler[]>
內部 pub/sub 系統的事件 handler。將事件 topic 對應至 handler 函式;事件發布至這些 topic 時會呼叫對應函式。
此選項由 Mastra 的 Workflow 引擎在內部使用。大多數使用者不需要設定此選項。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
events: {
'my-topic': async event => {
console.log('Event received:', event)
},
},
})
gateways「gateways」的直接連結
型別: Record<string, MastraModelGateway>
用於存取 LLM Provider 的自訂模型 router Gateway。Gateway 會處理 Provider 專屬驗證、URL 建構與模型解析。可用來支援自訂或自行託管的 LLM Provider。
詳情請參閱自訂 Gateway 文件。
import { Mastra } from '@mastra/core'
import { MyPrivateGateway } from './gateways'
export const mastra = new Mastra({
gateways: {
private: new MyPrivateGateway(),
},
})
idGenerator「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 實體 IDthreadId?:相關時的 thread ID(例如建立訊息 ID 時)resourceId?:相關時的 resource ID(例如使用者範圍的 thread)role?:建立訊息 ID 時的訊息角色stepType?:建立 step ID 時的 Workflow step 類型
Mastra 會在內部使用此選項,為 Workflow 執行作業、Agent 對話與其他 resource 建立 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()
},
})
logger「logger」的直接連結
型別: 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' }),
})
mcpServers「mcpServers」的直接連結
型別: Record<string, MCPServerBase>
向 MCP 相容使用者端公開 Mastra Tool、Agent、Workflow 與 resource 的 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,
},
})
memory「memory」的直接連結
型別: Record<string, MastraMemory>
可供 Agent 參照的 Memory 執行個體 registry。Memory 會保留過往對話中的相關資訊,讓 Agent 在多次互動之間保持連貫。Mastra 支援用於近期訊息的訊息歷程,以及持久保存使用者專屬詳細資料的 Working Memory。語意回想則會依相關性擷取較舊的訊息。
詳情請參閱 Memory 文件。
大多數使用者會直接在 Agent 上設定 Memory。此頂層設定用於定義可在多個 Agent 之間共用的可重複使用 Memory 執行個體。
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「observability」的直接連結
型別: ObservabilityEntrypoint
Mastra 為 AI 應用程式提供 Observability 功能。你可以透過瞭解 AI 專屬模式的 Tool,監控 LLM 操作、追蹤 Agent 決策,並對複雜 Workflow 進行偵錯。Trace 會擷取模型互動、Agent 執行路徑、Tool 呼叫與 Workflow step。
詳情請參閱 Observability 文件。
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「processors」的直接連結
型別: Record<string, Processor>
用於轉換 Agent 輸入與輸出的 input/output processor。Processor 會在 Agent 執行 pipeline 的特定位置執行,讓你能在輸入送達語言模型前加以修改,或在輸出傳回前加以修改。可使用 processor 新增 guardrail、偵測 prompt injection、進行內容審核,或套用自訂業務邏輯。
詳情請參閱 Processor 文件。
大多數使用者會直接在 Agent 上設定 processor。此頂層設定用於定義可在多個 Agent 之間共用的可重複使用 processor 執行個體。
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」的直接連結
型別: PubSub
預設值: EventEmitterPubSub
用於元件之間事件驅動通訊的 pub/sub 系統。Mastra 會在內部將其用於 Workflow 事件處理與元件通訊。
此選項由 Mastra 在內部使用。大多數使用者不需要設定此選項。
import { Mastra } from '@mastra/core'
import { CustomPubSub } from './pubsub'
export const mastra = new Mastra({
pubsub: new CustomPubSub(),
})
scorers「scorers」的直接連結
型別: 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' }),
},
})
storage「storage」的直接連結
型別: MastraCompositeStore
用於持久儲存應用程式資料的 storage Provider。由 Memory、Workflow、Trace 及其他需要持久性的元件使用。Mastra 支援多種資料庫後端,包括 PostgreSQL、MongoDB、libSQL 等。
詳情請參閱 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',
}),
})
tools「tools」的直接連結
型別: 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,
},
})
tts「tts」的直接連結
型別: Record<string, MastraVoice>
提供語音合成功能的 text-to-speech Provider。註冊 voice Provider 可讓 Agent 將文字回應轉換為語音音訊。
詳情請參閱 Voice 文件。
大多數使用者會直接在 Agent 上設定 voice。此頂層設定用於定義可在多個 Agent 之間共用的可重複使用 voice Provider。
import { Mastra } from '@mastra/core'
import { OpenAIVoice } from '@mastra/voice-openai'
export const mastra = new Mastra({
tts: {
openai: new OpenAIVoice(),
},
})
vectors「vectors」的直接連結
型別: Record<string, MastraVector>
用於語意搜尋與 embedding 的 vector store。應用於 RAG pipeline、相似度搜尋及其他 embedding 功能。Mastra 支援多種向量資料庫,包括 Pinecone、搭配 pgvector 的 PostgreSQL、OracleDB、MongoDB 等。
詳情請參閱 RAG 文件。
大多數使用者會在建立 RAG pipeline 時直接建立 vector store。此頂層設定用於定義可在應用程式中共用的可重複使用 vector store 執行個體。
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「workflows」的直接連結
型別: Record<string, Workflow>
Workflow 會定義具有型別安全輸入與輸出的 step 式執行 pipeline。需要多個 step 且有特定執行順序時,可使用 Workflow 來控制資料在 step 之間的流動方式。
詳情請參閱 Workflow 文件。
import { Mastra } from '@mastra/core'
import { testWorkflow } from './workflows/test-workflow'
export const mastra = new Mastra({
workflows: {
testWorkflow,
},
})
workspace「workspace」的直接連結
型別: 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 選項「Bundler 選項」的直接連結
bundler.entries「bundler.entries」的直接連結
型別: Record<string, string>
預設值: {}
與伺服器 bundle 一同輸出的其他處理程序 entry,以輸出名稱到 Mastra 目錄相對來源路徑的 map 表示。每個 entry 都會在 .mastra/output 中成為獨立的 <name>.mjs。
可用於在 Mastra 伺服器旁而非其中執行的長時間執行處理程序,例如 LiveKit voice worker。entry 會與伺服器共用輸出目錄、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。系統也會分析只由其他 entry 匯入的相依套件,並將它們安裝至輸出。
entry 名稱可包含 / 以巢狀排列輸出。名稱不能是伺服器 bundle 所用的 index、Tool aggregator 所用的 tools,也不能以為 Tool bundle 保留的 tools/ 開頭。
只有完全未設定任何 bundler 選項時,mastra build 才會套用 bundler.externals 的預設值 true。一旦設定 entries,若其他 entry 依賴無法封裝的套件(例如原生模組),也請明確設定 externals。
bundler.externals「bundler.externals」的直接連結
型別: boolean | string[]
預設值: true
執行 mastra build 時,Mastra 會將專案封裝至 .mastra/output 目錄。此選項控制要從 bundle 排除(標記為「external」)並透過套件管理器另外安裝的套件。當 Mastra 內部 bundler(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.sourcemap「bundler.sourcemap」的直接連結
型別: boolean
預設值: false
為封裝輸出啟用 source map 生成。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
bundler: {
sourcemap: true,
},
})
bundler.transpilePackages「bundler.transpilePackages」的直接連結
型別: string[]
預設值: []
在建置流程中,應透過 esbuild 轉譯原始碼的套件清單。相依套件包含 TypeScript 或其他必須先編譯才能封裝的程式碼時,請使用此選項。
只有直接匯入未編譯的原始碼時才需要此選項。若套件已編譯為 CommonJS 或 ESM,便不需要列於此處。
Mastra 會自動偵測 monorepo 設定中的 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 選項「Server 選項」的直接連結
server.apiRoutes「server.apiRoutes」的直接連結
型別: ApiRoute[]
Mastra 會透過伺服器自動公開已註冊的 Agent 與 Workflow。若需其他行為,可以定義自己的 HTTP route。
詳情請參閱自訂 API route 文件。
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「server.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 callback 會將已驗證使用者對應至 resource ID,以界定 Memory/thread 範圍。若有提供,此 callback 會在驗證成功後呼叫,傳回值則會在 request context 中設為 MASTRA_RESOURCE_ID_KEY。詳情請參閱授權(使用者隔離)。
server.bodySizeLimit「server.bodySizeLimit」的直接連結
型別: number
預設值: 4_718_592(4.5 MB)
要求本文的大小上限(位元組)。如果應用程式需要處理更大的 payload,請提高此限制。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
bodySizeLimit: 10 * 1024 * 1024, // 10mb
},
})
server.mcpOptions「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 函式 |
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
mcpOptions: {
serverless: true,
},
},
})
server.build「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: "/"}] 覆寫值。 |
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
build: {
swaggerUI: true,
apiReqLogs: true,
openAPIDocs: true,
},
},
})
server.cors「server.cors」的直接連結
型別: CorsOptions | false
伺服器的 CORS(Cross-Origin Resource Sharing)設定。設為 false 可完全停用 CORS。此選項可為所有 route 套用同一 policy。若要為自訂 route 使用專屬 policy,請使用 registerApiRoute() 的 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 要求的快取時間(秒) |
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「server.host」的直接連結
型別: string
預設值: localhost(若已設定則使用 MASTRA_HOST 環境變數)
Mastra 開發伺服器綁定的 host 位址。如果已設定 MASTRA_HOST 環境變數,該值會優先於預設值。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
host: '0.0.0.0',
},
})
server.https「server.https」的直接連結
型別: { key: Buffer; cert: Buffer }
以 TLS 執行開發伺服器的 HTTPS 設定。Mastra 透過 mastra dev --https flag 支援本機 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.middleware「server.middleware」的直接連結
型別: Middleware | Middleware[]
在 route handler 之前或之後攔截要求的自訂 middleware 函式。Middleware 可用於驗證、記錄、注入要求專屬 context 或新增 header。每個 middleware 都會接收 Hono Context 與 next 函式。傳回 Response 可立即結束要求;呼叫 next() 則繼續處理。
詳情請參閱 Middleware 文件。
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「server.onError」的直接連結
型別: (err: Error, c: Context) => Response | Promise<Response>
發生未處理錯誤時呼叫的自訂錯誤 handler。可用來自訂錯誤回應、將錯誤記錄至 Sentry 等外部服務,或實作自訂錯誤格式。
所有伺服器 adapter 都支援此 hook。c 參數提供與 Hono 相容的 context 物件:若 adapter 並非 Hono(Koa、Express、Fastify),系統會提供包含 c.json() 與 c.req.path 等常用方法的 shim。
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「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':路徑參數
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「server.port」的直接連結
型別: number
預設值: 4111(若已設定則使用 PORT 環境變數)
Mastra 開發伺服器綁定的連接埠。如果已設定 PORT 環境變數,該值會優先於預設值。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
port: 8080,
},
})
server.studioBase「server.studioBase」的直接連結
型別: string
預設值: /
託管 Studio 的基底路徑。可用來將 Studio 託管於現有應用程式的子路徑,而非根目錄。
整合現有應用程式、使用 Cloudflare Zero Trust 等能受益於共用網域的驗證 Tool,或在單一網域下管理多項服務時,此選項很有用。
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「server.timeout」的直接連結
型別: number
預設值: 180000(3 分鐘)
要求逾時時間(毫秒)。超過此時間的要求將會終止。
import { Mastra } from '@mastra/core'
export const mastra = new Mastra({
server: {
timeout: 30000, // 30 seconds
},
})