Mastra クラス
Mastra
クラスは、あらゆる Mastra アプリケーションの中核となるオーケストレーターで、エージェント、ワークフロー、ストレージ、ロギング、テレメトリーなどを管理します。通常は、アプリケーション全体を調整するために Mastra
のインスタンスを1つ作成します。
Mastra
はトップレベルのレジストリと考えてください。
- integrations を登録すると、agents、workflows、tools から利用できるようになります。
- tools は
Mastra
に直接登録するのではなく、エージェントに関連付けられ、自動的に検出されます。
インポート
import { Mastra } from "@mastra/core/mastra";
コンストラクター
指定された構成で新しい Mastra
インスタンスを作成します。
constructor(config?: Config);
初期化
Mastra クラスは通常、src/mastra/index.ts
ファイルで初期化します:
src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra";
import { LibSQLStore } from "@mastra/libsql";
import { weatherAgent } from "./agents/weather-agent";
export const mastra = new Mastra({
agents: { weatherAgent },
storage: new LibSQLStore({
url: ":memory:",
}),
});
構成オブジェクト
コンストラクタは、動作のカスタマイズや各種 Mastra コンポーネントの統合に使用できる任意の Config
オブジェクトを受け取ります。Config
オブジェクトのプロパティはすべて任意です。
プロパティ
agents?:
Agent[]
= []
登録する Agent インスタンスの配列
tools?:
Record<string, ToolApi>
= {}
登録するカスタムツール。キーをツール名、値をツール関数とするキーと値のペアで構成されます。
storage?:
MastraStorage
データ永続化用のストレージエンジンのインスタンス
vectors?:
Record<string, MastraVector>
ベクターストアのインスタンス。セマンティック検索やベクター系ツール(例:Pinecone、PgVector、Qdrant)に使用します。
logger?:
Logger
= INFO レベルのコンソールロガー
new PinoLogger() で作成された Logger インスタンス
idGenerator?:
() => string
カスタム ID 生成関数。エージェント、ワークフロー、メモリ、その他のコンポーネントが一意の識別子を生成する際に使用します。
workflows?:
Record<string, Workflow>
= {}
登録するワークフロー。キーをワークフロー名、値をワークフローインスタンスとするキーと値のペアで構成されます。
tts?:
Record<string, MastraTTS>
Text-To-Speech サービスを登録するためのオブジェクト。
telemetry?:
OtelConfig
OpenTelemetry 連携用の設定。
deployer?:
MastraDeployer
デプロイ管理用の MastraDeployer インスタンス。
server?:
ServerConfig
= { port: 4111, host: localhost, cors: { origin: '*', allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization', 'x-mastra-client-type'], exposeHeaders: ['Content-Length', 'X-Requested-With'], credentials: false } }
ポート、ホスト、タイムアウト、API ルート、ミドルウェア、CORS 設定に加え、Swagger UI、API リクエストログ、OpenAPI ドキュメントのビルドオプションを含むサーバー設定。
mcpServers?:
Record<string, MCPServerBase>
キーが一意のサーバー識別子、値が MCPServer のインスタンスまたは MCPServerBase を継承するクラスであるオブジェクト。Mastra がこれらの MCP サーバーを把握し、必要に応じて管理できるようにします。
bundler?:
BundlerConfig
= { externals: [], sourcemap: false, transpilePackages: [] }
externals、sourcemap、transpilePackages を指定できるアセットバンドラの設定。
使い方
以下のいずれのメソッドも Mastra クラスで使用できます。例:
example.ts
import { mastra } from "./mastra";
const agent = mastra.getAgent("weatherAgent");
const result = await agent.generate("What's the weather like in London?");
メソッド
getAgent(name):
Agent
Returns an agent instance by id. Throws if agent not found.
getAgents():
Record<string, Agent>
Returns all registered agents as a key-value object.
getWorkflow(id, { serialized }):
Workflow
Returns a workflow instance by id. The serialized option (default: false) returns a simplified representation with just the name.
getWorkflows({ serialized }):
Record<string, Workflow>
Returns all registered workflows. The serialized option (default: false) returns simplified representations.
getVector(name):
MastraVector
Returns a vector store instance by name. Throws if not found.
getVectors():
Record<string, MastraVector>
Returns all registered vector stores as a key-value object.
getDeployer():
MastraDeployer | undefined
Returns the configured deployer instance, if any.
getStorage():
MastraStorage | undefined
Returns the configured storage instance.
getMemory():
MastraMemory | undefined
Returns the configured memory instance. Note: This is deprecated, memory should be added to agents directly.
getServer():
ServerConfig | undefined
Returns the server configuration including port, timeout, API routes, middleware, CORS settings, and build options.
setStorage(storage):
void
Sets the storage instance for the Mastra instance.
setLogger({ logger }):
void
Sets the logger for all components (agents, workflows, etc.).
setTelemetry(telemetry):
void
Sets the telemetry configuration for all components.
getLogger():
Logger
Gets the configured logger instance.
getTelemetry():
Telemetry | undefined
Gets the configured telemetry instance.
getLogsByRunId({ runId, transportId }):
Promise<any>
Retrieves logs for a specific run ID and transport ID.
getLogs(transportId):
Promise<any>
Retrieves all logs for a specific transport ID.
getMCPServers():
Record<string, MCPServerBase> | undefined
Retrieves all registered MCP server instances.
エラー処理
Mastra クラスのメソッドは、捕捉できる型付きエラーをスローします。
example.ts
import { mastra } from "./mastra";
try {
const agent = mastra.getAgent("weatherAgent");
const result = await agent.generate("What's the weather like in London?");
} catch (error) {
if (error instanceof Error) {
console.log(error.message);
}
}