Mastra Client SDK
Mastra Client SDKは、クライアント環境から Mastra Server とやり取りするための、シンプルで型安全なインターフェースを提供します。
前提条件
ローカル開発を円滑に進めるため、以下を用意してください:
- Node.js
v18
以上 - TypeScript
v4.7
以上(TypeScript を使用する場合) - ローカルの Mastra サーバーが起動していること(通常はポート
4111
)
使い方
Mastra Client SDK はブラウザ環境向けに設計されており、Mastra サーバーへの HTTP リクエストにはネイティブの fetch
API を使用します。
インストール
Mastra Client SDK を使用するには、必要な依存関係をインストールしてください:
npm
npm install @mastra/client-js@latest
MastraClient
を初期化する
baseUrl
を指定して初期化すると、MastraClient
はエージェント、ツール、ワークフローを呼び出すための型安全なインターフェースを公開します。
import { MastraClient } from "@mastra/client-js";
export const mastraClient = new MastraClient({
baseUrl: process.env.MASTRA_API_URL || "http://localhost:4111"
});
コア API
Mastra Client SDK は、Mastra Server が提供するすべてのリソースを公開します。
- Agents: 応答を生成し、会話をストリーミング配信します。
- Memory: 会話スレッドとメッセージ履歴を管理します。
- Tools: ツールを実行・管理します。
- Workflows: ワークフローをトリガーし、実行状況を追跡します。
- Vectors: セマンティック検索のためにベクトル埋め込みを使用します。
- Logs: ログを確認し、システムの挙動をデバッグします。
- Telemetry: アプリのパフォーマンスを監視し、アクティビティをトレースします。
応答の生成
role
と content
を含むメッセージオブジェクトの配列を渡して .generate()
を呼び出します:
import { mastraClient } from "lib/mastra-client";
const testAgent = async () => {
try {
const agent = mastraClient.getAgent("testAgent");
const response = await agent.generate({
messages: [
{
role: "user",
content: "Hello"
}
]
});
console.log(response.text);
} catch (error) {
return "応答の生成中にエラーが発生しました";
}
};
詳細は .generate() を参照してください。
ストリーミング応答
role
と content
を含むメッセージオブジェクトの配列でリアルタイム応答を受け取るには、.stream()
を使用します:
import { mastraClient } from "lib/mastra-client";
const testAgent = async () => {
try {
const agent = mastraClient.getAgent("testAgent");
const stream = await agent.stream({
messages: [
{
role: "user",
content: "Hello"
}
]
});
stream.processDataStream({
onTextPart: (text) => {
console.log(text);
}
});
} catch (error) {
return "応答の生成中にエラーが発生しました";
}
};
詳細は .stream() を参照してください。
設定オプション
MastraClient
は、リクエストの挙動を制御するために retries
、backoffMs
、headers
などのオプションパラメータを受け取ります。これらのパラメータは、リトライの制御や診断用メタデータの付加に役立ちます。
import { MastraClient } from "@mastra/client-js";
export const mastraClient = new MastraClient({
// ...
retries: 3,
backoffMs: 300,
maxBackoffMs: 5000,
headers: {
"X-Development": "true",
},
});
さらに詳しい設定オプションは MastraClient を参照してください。
リクエストのキャンセルを追加する
MastraClient
は、標準の Node.js の AbortSignal
API によるリクエストのキャンセルをサポートします。ユーザーが操作を中断した場合や、古いネットワーク呼び出しを整理する場合など、実行中のリクエストを取り消すのに便利です。
すべてのリクエストでキャンセルを有効にするには、クライアントのコンストラクターに AbortSignal
を渡します。
import { MastraClient } from "@mastra/client-js";
export const controller = new AbortController();
export const mastraClient = new MastraClient({
baseUrl: process.env.MASTRA_API_URL || "http://localhost:4111",
abortSignal: controller.signal
});
AbortController
の使用
.abort()
を呼び出すと、そのシグナルに紐づいた進行中のリクエストがキャンセルされます。
import { mastraClient, controller } from "lib/mastra-client";
const handleAbort = () => {
controller.abort();
};
クライアントツール
createTool()
関数を使って、クライアントサイドのアプリケーション内でツールを直接定義します。.generate()
または .stream()
の呼び出しで、clientTools
パラメータを通じてエージェントに渡します。
これにより、エージェントは DOM 操作、ローカルストレージへのアクセス、その他の Web API などのブラウザ側の機能をトリガーでき、ツールをサーバーではなくユーザーの環境で実行できるようになります。
import { createTool } from '@mastra/client-js';
import { z } from 'zod';
const handleClientTool = async () => {
try {
const agent = mastraClient.getAgent("colorAgent");
const colorChangeTool = createTool({
id: "color-change-tool",
description: "Changes the HTML background color",
inputSchema: z.object({
color: z.string()
}),
outputSchema: z.object({
success: z.boolean()
}),
execute: async ({ context }) => {
const { color } = context
document.body.style.backgroundColor = color;
return { success: true };
}
});
const response = await agent.generate({
messages: "Change the background to blue",
clientTools: { colorChangeTool }
});
console.log(response);
} catch (error) {
console.error(error);
}
};
クライアントツールのエージェント
これは、上で定義したブラウザベースのクライアントツールと連携し、ユーザーからのリクエストに対して16進カラーコードを返すように構成された、標準的な Mastra のエージェントです。
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
export const colorAgent = new Agent({
name: "test-agent",
instructions: `You are a helpful CSS assistant.
You can change the background color of web pages.
Respond with a hex reference for the color requested by the user`,
model: openai("gpt-4o-mini")
});
サーバーサイド環境
MastraClient
は、API ルートやサーバーレス関数、アクションなどのサーバーサイド環境でも使用できます。使い方は概ね同様ですが、クライアントに返すレスポンスを再生成する必要がある場合があります。
export async function action() {
const agent = mastraClient.getAgent("testAgent");
const stream = await agent.stream({
messages: [{ role: "user", content: "Hello" }]
});
return new Response(stream.body);
}