> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # 設定 以下のリファレンスでは、Mastra がサポートするすべてのオプションを説明します。[`Mastra` クラス](https://mastra.zisheng.pro/ja/reference/core/mastra-class)をインスタンス化して、Mastra を初期化および設定します。 ```ts import { Mastra } from '@mastra/core' export const mastra = new Mastra({ // Your options... }) ``` ## トップレベルオプション ### agents **型:** `Record` 名前をキーとする Agent インスタンスのレコードです。Agent は、AI モデル、Tool、Memory を使用して意思決定と操作を行える自律システムです。 詳しくは、[Agent のドキュメント](https://mastra.zisheng.pro/ja/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 ループは継続します。タスクは永続化されるため、`storage` バックエンドの設定が必要です。 詳しくは、[バックグラウンドタスクのドキュメント](https://mastra.zisheng.pro/ja/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 または Agent のレイヤーで明示的に有効化する必要があります(バックグラウンドタスクガイドを参照)。 (Default: `false`) **globalConcurrency** (`number`): すべての Agent を通じて同時実行できるバックグラウンドタスクの最大数。 (Default: `10`) **perAgentConcurrency** (`number`): 1つの 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`): 2回目以降の各試行で 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/ja/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 システム用のイベントハンドラーです。イベントトピックを、そのトピックへイベントが公開されたときに呼び出されるハンドラー関数へ対応付けます。 > **警告:** これは 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 にアクセスするためのカスタムモデルルーター Gateway です。Gateway は、Provider 固有の認証、URL の構築、モデルの解決を処理します。カスタムまたはセルフホストの LLM Provider をサポートする場合に使用します。 詳しくは、[カスタム Gateway のドキュメント](https://mastra.zisheng.pro/ja/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、Memory エンティティの ID - `threadId?`:関連する場合の Thread ID(Message ID の作成時など) - `resourceId?`:関連する場合の Resource ID(ユーザースコープの Thread など) - `role?`:Message ID の作成時に使用する Message の Role - `stepType?`:Step ID の作成時に使用する Workflow Step の型 > **警告:** これは、Workflow の実行、Agent の会話、その他のリソース用の ID を作成するために Mastra が内部で使用します。ほとんどのユーザーは、このオプションを設定する必要はありません。 ```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` レベル、本番環境では `WARN` レベルの `ConsoleLogger` アプリケーションのログ記録とデバッグに使用する Logger 実装です。ログ記録を完全に無効化するには、`false` に設定します。 詳しくは、[ログのドキュメント](https://mastra.zisheng.pro/ja/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` Mastra の Tool、Agent、Workflow、リソースを MCP 互換クライアントへ公開する MCP(Model Context Protocol)サーバーです。このオプションを使用すると、プロトコルをサポートする任意のシステムから利用できる独自の MCP サーバーを作成できます。 詳しくは、[MCP の概要](https://mastra.zisheng.pro/ja/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 インスタンスのレジストリです。Memory は過去の会話から関連情報を保持し、やり取りを通じて Agent の一貫性を維持します。Mastra は、最近の Message を保持する Message 履歴と、ユーザー固有の詳細を永続化する Working Memory をサポートしています。Semantic Recall は、関連性に基づいて以前の Message を取得します。 詳しくは、[Memory のドキュメント](https://mastra.zisheng.pro/ja/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 の意思決定を Trace し、複雑な Workflow をデバッグできます。Tracing は、モデルとのやり取り、Agent の実行経路、Tool の呼び出し、Workflow の Step を記録します。 詳しくは、[Observability のドキュメント](https://mastra.zisheng.pro/ja/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 の入力と出力を変換する入出力 Processor です。Processor は Agent の実行パイプライン内の特定の時点で動作し、言語モデルへ届く前の入力や、返される前の出力を変更できます。Processor を使用して、Guardrail の追加、Prompt Injection の検出、コンテンツのモデレーション、カスタムビジネスロジックの適用を行えます。 詳しくは、[Processor のドキュメント](https://mastra.zisheng.pro/ja/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 システムです。Workflow のイベント処理とコンポーネント間通信のために、Mastra が内部で使用します。 > **警告:** これは 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/ja/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/ja/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/ja/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/ja/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` Semantic Search と Embedding 用の Vector Store です。RAG パイプライン、類似検索、その他の Embedding ベースの機能で使用されます。Mastra は Pinecone、pgvector を使用した PostgreSQL、OracleDB、MongoDB など、複数の Vector Database をサポートしています。 詳しくは、[RAG のドキュメント](https://mastra.zisheng.pro/ja/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 **型:** `Record` Workflow は、型安全な入力と出力を持つ Step ベースの実行パイプラインを定義します。特定の実行順序で複数の Step を処理するタスクには Workflow を使用します。Step 間のデータフローを制御できます。 詳しくは、[Workflow のドキュメント](https://mastra.zisheng.pro/ja/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/ja/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`\ **デフォルト:** `{}` サーバーバンドルとともに出力する追加のプロセスエントリーです。出力名を、Mastra ディレクトリからの相対ソースパスへ対応付けます。各エントリーは `.mastra/output` 内に個別の `.mjs` として生成されます。 [LiveKit Voice Worker](https://mastra.zisheng.pro/ja/guides/voice/realtime-voice) のように、Mastra サーバーの内部ではなく、その横で動作する長時間実行プロセスに使用します。エントリーはサーバーと出力ディレクトリ、`package.json`、インストール済みの依存関係を共有するため、1回の `mastra build` で異なるコマンドから起動できる1つのデプロイ可能な成果物が生成されます。 ```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 する依存関係も解析され、出力へインストールされます。 エントリー名には `/` を含めて、出力をネストできます。サーバーバンドルである `index`、Tool Aggregator である `tools` は使用できません。また、Tool バンドル用に予約されているため、`tools/` で始めることもできません。 > **注記:** `mastra build` が [`bundler.externals`](#bundlerexternals) のデフォルト値 `true` を適用するのは、Bundler オプションを一切設定していない場合だけです。`entries` を設定した場合、追加エントリーがネイティブモジュールなどバンドルできないパッケージに依存するなら、`externals` も明示的に設定してください。 ### bundler.externals **型:** `boolean | string[]`\ **デフォルト:** `true` `mastra build` を実行すると、Mastra はプロジェクトを `.mastra/output` ディレクトリへバンドルします。このオプションでは、バンドルから除外し(「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` バンドル出力のソースマップ生成を有効にします。 ```typescript import { Mastra } from '@mastra/core' export const mastra = new Mastra({ bundler: { sourcemap: true, }, }) ``` ### bundler.transpilePackages **型:** `string[]`\ **デフォルト:** `[]` ビルド処理中に esbuild でソースコードをトランスパイルするパッケージの一覧です。TypeScript など、バンドル前にコンパイルが必要なコードを含む依存関係に使用します。 このオプションが必要なのは、未コンパイルのソースコードを直接 import する場合だけです。パッケージがすでに CommonJS または ESM へコンパイルされている場合、ここに記載する必要はありません。 Mastra は monorepo 構成の Workspace パッケージを自動検出してこの一覧へ追加するため、通常はトランスパイルが必要な外部パッケージだけを指定します。 Mastra はビルド時に `tsconfig.json` の `baseUrl` と `paths` エイリアスも解決します。これには、TypeScript ソースファイルを指す `~/utils/logger.js` などの ESM 形式の import も含まれます。 ```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/ja/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 は JWT、Clerk、Supabase、Firebase、WorkOS、Auth0 など、複数の認証 Provider をサポートしています。 詳しくは、[認証のドキュメント](https://mastra.zisheng.pro/ja/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` コールバックは、認証済みユーザーを Memory または Thread のスコープに使用する Resource ID へ対応付けます。指定すると、認証成功後に呼び出され、戻り値がリクエストコンテキストの `MASTRA_RESOURCE_ID_KEY` に設定されます。詳しくは、[認可(ユーザー分離)](https://mastra.zisheng.pro/ja/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 Transport オプションです。永続的な接続やインメモリーのセッション状態を利用できないサーバーレス環境(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 やリクエストログなどの開発 Tool を制御します。 | プロパティ | 型 | デフォルト | 説明 | | ------------- | --------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `swaggerUI` | `boolean` | `false` | 対話的な API 調査のため、`/swagger-ui` で Swagger UI を有効にします(`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(Cross-Origin Resource Sharing)設定です。CORS を完全に無効化するには、`false` に設定します。すべてのルートに1つのポリシーを適用する場合に使用します。カスタムルート固有のポリシーには、[`registerApiRoute()`](https://mastra.zisheng.pro/ja/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']` | リクエストヘッダー。 | | `exposeHeaders` | `string[]` | `['Content-Length', 'X-Requested-With']` | ブラウザーへ公開するヘッダー。 | | `credentials` | `boolean` | `false` | 認証情報(Cookie、Authorization ヘッダー)。 | | `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[]` ルートハンドラーの前後でリクエストをインターセプトするカスタム Middleware 関数です。Middleware は、認証、ログ記録、リクエスト固有のコンテキストの注入、ヘッダーの追加に使用できます。各 Middleware は Hono の `Context` と `next` 関数を受け取ります。リクエストの処理をそこで終了するには `Response` を返し、処理を続行するには `next()` を呼び出します。 詳しくは、[Middleware のドキュメント](https://mastra.zisheng.pro/ja/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 は、すべての Server Adapter でサポートされています。`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 **型:** `(error: ZodError, context: 'query' | 'body' | 'path') => { status: number; body: unknown } | undefined` リクエストが Zod スキーマのバリデーションに失敗したときに呼び出されるカスタムハンドラーです。バリデーションエラー応答のカスタマイズ、ステータスコードの変更、API 標準に合わせたエラー形式の調整に使用します。 デフォルトの `400` 応答を上書きするには `{ status, body }` オブジェクトを返し、デフォルトの動作を使用するには `undefined` を返します。この Hook は、すべての Server Adapter(Hono、Express、Fastify、Koa)でサポートされています。 `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/ja/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 }, }) ```