> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # 配置 以下参考涵盖 Mastra 支持的所有选项。你可以通过实例化 [`Mastra` class](https://mastra.zisheng.pro/reference/core/mastra-class) 来初始化和配置 Mastra。 ```ts import { Mastra } from '@mastra/core' export const mastra = new Mastra({ // Your options... }) ``` ## 顶层选项 ### agents **Type:** `Record` 以名称为键的 Agent 实例记录。Agent 是能够使用 AI 模型、Tool 和 memory 做出决策并执行操作的自主系统。 有关详细信息,请参阅 [Agent 文档](https://mastra.zisheng.pro/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 **Type:** `BackgroundTaskManagerConfig` 启用并配置后台任务管理器。启用后,Agent 可以分派长时间运行的 Tool 调用(包括 subagent 调用),使其在 agentic loop 继续运行的同时异步执行。任务会被持久化,因此必须配置 `storage` 后端。 有关详细信息,请参阅[后台任务文档](https://mastra.zisheng.pro/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' 改为在 agentic loop 中同步运行 Tool。 (Default: `'queue'`) **defaultTimeoutMs** (`number`): 每个任务的默认超时时间(毫秒)。可按 Tool 或按调用覆盖。 (Default: `300000`) **defaultRetries** (`RetryConfig`): 应用于失败任务的默认重试策略。 **defaultRetries.maxRetries** (`number`): 任务标记为失败前的最大重试次数。 **defaultRetries.retryDelayMs** (`number`): 两次重试之间的延迟(毫秒)。 **defaultRetries.backoffMultiplier** (`number`): 后续每次尝试应用于 retryDelayMs 的倍数。 **defaultRetries.maxRetryDelayMs** (`number`): 无论 backoff 如何,重试延迟的上限。 **defaultRetries.retryableErrors** (`(error: Error) => boolean`): 决定是否应重试给定错误的 predicate。默认:重试所有错误。 **cleanup** (`CleanupConfig`): 控制任务记录的保留时长和清理进程的运行频率。 **cleanup.completedTtlMs** (`number`): 已完成任务记录的保留时长(毫秒)。默认:1 小时。 **cleanup.failedTtlMs** (`number`): 失败任务记录的保留时长(毫秒)。默认:24 小时。 **cleanup.cleanupIntervalMs** (`number`): 清理进程的运行间隔(毫秒)。默认:1 分钟。 **waitTimeoutMs** (`number`): agentic loop 在继续执行前等待后台任务完成的时长。如果任务未在此时间内完成,loop 会继续执行且不设置 isContinued。默认:undefined(不等待)。可按 Agent 或 Tool 覆盖。 **onTaskComplete** (`(task: BackgroundTask) => void | Promise`): 任意后台任务成功完成时调用的全局 callback。除按 Tool 和按 Agent 的 callback 外也会触发。 **onTaskFailed** (`(task: BackgroundTask) => void | Promise`): 任意后台任务失败时调用的全局 callback。除按 Tool 和按 Agent 的 callback 外也会触发。 ### deployer **Type:** `MastraDeployer` 用于将应用发布到云平台的部署 Provider。 有关详细信息,请参阅[部署文档](https://mastra.zisheng.pro/docs/deployment/overview)。 ```typescript import { Mastra } from '@mastra/core' import { NetlifyDeployer } from '@mastra/deployer-netlify' export const mastra = new Mastra({ deployer: new NetlifyDeployer(), }) ``` ### events **Type:** `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 **Type:** `Record` 用于访问 LLM Provider 的自定义模型路由 Gateway。Gateway 处理 Provider 特定的身份验证、URL 构造和模型解析。使用此选项可添加对自定义或自行托管的 LLM Provider 的支持。 有关详细信息,请参阅[自定义 Gateway 文档](https://mastra.zisheng.pro/models/gateways/custom-gateways)。 ```typescript import { Mastra } from '@mastra/core' import { MyPrivateGateway } from './gateways' export const mastra = new Mastra({ gateways: { private: new MyPrivateGateway(), }, }) ``` ### idGenerator **Type:** `(context?: IdGeneratorContext) => string`\ **Default:** `crypto.randomUUID()` 用于创建唯一标识符的自定义 ID 生成函数。Mastra 会传递可选上下文,使你能根据正在创建的对象生成 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?`:创建步骤 ID 时的 Workflow 步骤类型 > **注意:** Mastra 在内部使用此选项为 Workflow run、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 **Type:** `IMastraLogger | false`\ **默认值:** `ConsoleLogger`,开发环境使用 `INFO` 级别,生产环境使用 `WARN` 级别 用于应用日志记录和调试的 Logger 实现。设为 `false` 可完全禁用日志记录。 有关详细信息,请参阅[日志文档](https://mastra.zisheng.pro/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 **Type:** `Record` 向兼容 MCP 的客户端公开 Mastra Tool、Agent、Workflow 和资源的 MCP (Model Context Protocol) server。使用此选项可编写自己的 MCP server,供任何支持该协议的系统使用。 有关详细信息,请参阅 [MCP 概览](https://mastra.zisheng.pro/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 **Type:** `Record` 可供 Agent 引用的 memory 实例注册表。Memory 通过保留过往对话中的相关信息,使 Agent 在多次交互中保持连贯。Mastra 支持用于近期消息的消息历史记录,以及用于持久化用户特定详细信息的 working memory。Semantic recall 会根据相关性检索较早的消息。 有关详细信息,请参阅 [Memory 文档](https://mastra.zisheng.pro/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 **Type:** `ObservabilityEntrypoint` Mastra 为 AI 应用提供可观测性功能。你可以使用理解 AI 特有模式的 Tool 监控 LLM 操作、追踪 Agent 决策并调试复杂 Workflow。Tracing 会捕获模型交互、Agent 执行路径、Tool 调用和 Workflow 步骤。 有关详细信息,请参阅[可观测性文档](https://mastra.zisheng.pro/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 **Type:** `Record` 用于转换 Agent 输入和输出的输入/输出 Processor。Processor 在 Agent 执行流水线的特定位置运行,使你可以在输入到达语言模型之前修改输入,或在返回输出之前修改输出。可使用 Processor 添加 guardrail、检测 prompt injection、审核内容或应用自定义业务逻辑。 有关详细信息,请参阅 [Processor 文档](https://mastra.zisheng.pro/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 **Type:** `PubSub`\ **Default:** `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 **Type:** `Record` Scorer 用于评估 Agent 响应和 Workflow 输出的质量。它们通过模型评分、基于规则和统计方法,提供衡量 Agent 质量的量化指标。可使用 Scorer 跟踪表现并比较不同方法,还可以识别需要改进的方面。 有关详细信息,请参阅 [Scorer 文档](https://mastra.zisheng.pro/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 **Type:** `MastraCompositeStore` 用于持久化应用数据的 storage Provider。供 memory、Workflow、Trace 和其他需要持久化的组件使用。Mastra 支持 PostgreSQL、MongoDB、libSQL 等多种数据库后端。 有关详细信息,请参阅 [Storage 文档](https://mastra.zisheng.pro/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 **Type:** `Record` Tool 是 Agent 可用于与外部系统交互的可复用函数。每个 Tool 都定义输入、输出和执行逻辑。 有关详细信息,请参阅 [Tool 文档](https://mastra.zisheng.pro/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 **Type:** `Record` 提供语音合成功能的 text-to-speech Provider。注册语音 Provider,使 Agent 能够将文本响应转换为语音音频。 有关详细信息,请参阅[语音文档](https://mastra.zisheng.pro/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 **Type:** `Record` 用于语义搜索和 embedding 的 vector store。用于 RAG 流水线、相似度搜索和其他基于 embedding 的功能。Mastra 支持 Pinecone、带 pgvector 的 PostgreSQL、OracleDB、MongoDB 等多种向量数据库。 有关详细信息,请参阅 [RAG 文档](https://mastra.zisheng.pro/guides/rag/overview)。 > **备注:** 大多数用户在构建 RAG 流水线时直接创建 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 **Type:** `Record` Workflow 定义基于步骤的执行流水线,并提供类型安全的输入和输出。对于包含多个步骤且执行顺序明确的任务,可使用 Workflow 控制数据在步骤之间的流动方式。 有关详细信息,请参阅 [Workflow 文档](https://mastra.zisheng.pro/docs/workflows/overview)。 ```typescript import { Mastra } from '@mastra/core' import { testWorkflow } from './workflows/test-workflow' export const mastra = new Mastra({ workflows: { testWorkflow, }, }) ``` ### workspace **Type:** `Workspace` Mastra Workspace 为 Agent 提供用于存储文件和执行命令的持久环境。除非配置了自己的 Workspace,否则 Agent 会继承 `Mastra` class 上的全局 Workspace。 有关实现细节,请参阅 [Workspace 文档](https://mastra.zisheng.pro/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 **Type:** `Record`\ **Default:** `{}` 与 server bundle 一起输出的额外进程入口,以输出名称到相对于 Mastra 目录的源路径的映射形式提供。每个入口都会在 `.mastra/output` 中生成自己的 `.mjs`。 此选项适用于在 Mastra server 旁而非其内部运行的长时间运行进程,例如 [LiveKit voice worker](https://mastra.zisheng.pro/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`。系统也会分析仅由额外入口 import 的依赖项,并将其安装到输出中。 入口名称可以包含 `/` 以嵌套输出。名称不能是 server bundle 使用的 `index`、Tool 聚合器使用的 `tools`,也不能以为 Tool bundle 保留的 `tools/` 开头。 > **备注:** 只有完全未设置 bundler 选项时,`mastra build` 才会应用 [`bundler.externals`](#bundlerexternals) 的默认值 `true`。设置 `entries` 后,如果额外入口依赖无法打包的包(例如原生模块),也请显式设置 `externals`。 ### bundler.externals **Type:** `boolean | string[]`\ **Default:** `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 **Type:** `boolean`\ **Default:** `false` 为打包输出启用 source map 生成。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { sourcemap: true, }, }) ``` ### bundler.transpilePackages **Type:** `string[]`\ **Default:** `[]` 构建过程中应通过 esbuild 转译源代码的包列表。对于包含 TypeScript 或其他需要在打包前编译的代码的依赖项,请使用此选项。 只有直接 import 未编译的源代码时才需要此选项。如果包已编译为 CommonJS 或 ESM,则无需在此处列出。 Mastra 会自动检测 monorepo 设置中的 Workspace 包并将其添加到此列表,因此通常只需指定需要转译的外部包。 Mastra 还会在构建期间解析 `tsconfig.json` 的 `baseUrl` 和 `paths` 别名,包括指向 TypeScript 源文件的 ESM 风格 import,例如 `~/utils/logger.js`。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { transpilePackages: ['@my-org/shared-utils'], }, }) ``` ## Server 选项 ### server.apiRoutes **Type:** `ApiRoute[]` Mastra 会通过 server 自动公开已注册的 Agent 和 Workflow。要添加其他行为,可以定义自己的 HTTP 路由。 有关详细信息,请参阅[自定义 API 路由](https://mastra.zisheng.pro/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 **Type:** `MastraAuthConfig | MastraAuthProvider` 服务器的身份验证配置。Mastra 支持多种身份验证 Provider,包括 JWT、Clerk、Supabase、Firebase、WorkOS 和 Auth0。 有关详细信息,请参阅[身份验证文档](https://mastra.zisheng.pro/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 后,系统会在身份验证成功后调用它,并将返回值作为 `MASTRA_RESOURCE_ID_KEY` 设置到请求上下文中。有关详细信息,请参阅[授权(用户隔离)](https://mastra.zisheng.pro/docs/server/middleware)。 ### server.bodySizeLimit **Type:** `number`\ **Default:** `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 **Type:** `object`\ **Default:** `undefined` 应用于所有 MCP HTTP 和 SSE 路由的 MCP transport 选项。对于无法使用持久连接和内存中 session 状态的 serverless 环境(Cloudflare Workers、Vercel Edge、AWS Lambda 等),可使用此选项启用无状态模式。 | 属性 | 类型 | 默认值 | 说明 | | -------------------- | -------------- | ----------- | --------------------------- | | `serverless` | `boolean` | `false` | 以不使用 session 管理的无状态模式运行 MCP | | `sessionIdGenerator` | `() => string` | `undefined` | 自定义 session ID 生成函数 | ```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 请求日志 | | `openAPIDocs` | `boolean` | `false` | 在 `/api/openapi.json` 启用 OpenAPI 规范。Mastra 内置路由使用 `servers: [{url: "/api"}]`,自定义路由则获得按路径设置的 `servers: [{url: "/"}]` override。 | ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { build: { swaggerUI: true, apiReqLogs: true, openAPIDocs: true, }, }, }) ``` ### server.cors **Type:** `CorsOptions | false` 服务器的 CORS (Cross-Origin Resource Sharing) 配置。设为 `false` 可完全禁用 CORS。使用此选项可为所有路由应用同一策略。要为特定自定义路由设置策略,请使用 [`registerApiRoute()`](https://mastra.zisheng.pro/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、authorization 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 **Type:** `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 **Type:** `{ 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 **Type:** `Middleware | Middleware[]` 用于在路由 handler 之前或之后拦截请求的自定义 middleware 函数。Middleware 可用于身份验证、日志记录、注入请求特定上下文或添加 header。每个 middleware 都会接收 Hono `Context` 和 `next` 函数。返回 `Response` 可提前终止请求,调用 `next()` 则继续处理。 有关详细信息,请参阅 [Middleware 文档](https://mastra.zisheng.pro/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 **Type:** `(err: Error, c: Context) => Response | Promise` 发生未处理错误时调用的自定义错误 handler。可用它自定义错误响应、将错误记录到 Sentry 等外部服务,或实现自定义错误格式。 所有服务器 adapter 都支持此 hook。`c` 参数提供兼容 Hono 的上下文对象:对于非 Hono adapter(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 **Type:** `(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()` 创建的单个路由上设置 `onValidationError`。路由级 hook 优先于服务器级 hook。 ### server.port **Type:** `number`\ **默认值:** `4111`(如果设置了 `PORT` 环境变量,则使用该值) Mastra 开发服务器绑定的端口。如果设置了 `PORT` 环境变量,它优先于默认值。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { port: 8080, }, }) ``` ### server.studioBase **Type:** `string`\ **Default:** `/` 托管 [Studio](https://mastra.zisheng.pro/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 **Type:** `number`\ **Default:** `180000` (3 minutes) 请求超时时间(毫秒)。超过此时长的请求将被终止。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ server: { timeout: 30000, // 30 seconds }, }) ```