MastraMCPClient(非推奨)
MastraMCPClient
クラスは、Model Context Protocol(MCP)サーバーとやり取りするためのクライアント実装を提供します。このクラスは、MCPプロトコルを通じて接続管理、リソースの発見、およびツールの実行を行います。
非推奨のお知らせ
MastraMCPClient
は MCPClient
への移行に伴い非推奨となります。単一のMCPサーバーと複数のMCPサーバーを管理するために異なるインターフェースを用意するのではなく、たとえ単一のMCPサーバーを使用する場合でも複数サーバー管理用のインターフェースを推奨することにしました。
コンストラクター
MastraMCPClient の新しいインスタンスを作成します。
constructor({
name,
version = '1.0.0',
server,
capabilities = {},
timeout = 60000,
}: {
name: string;
server: MastraMCPServerDefinition;
capabilities?: ClientCapabilities;
version?: string;
timeout?: number;
})
パラメーター
name:
version?:
server:
capabilities?:
timeout?:
MastraMCPServerDefinition
MCP サーバーはこの定義を使って設定できます。クライアントは、指定されたパラメーターに基づいて自動的にトランスポートタイプを検出します:
command
が指定されている場合、Stdio トランスポートを使用します。url
が指定されている場合、まず Streamable HTTP トランスポートを試み、初回接続に失敗した場合はレガシー SSE トランスポートにフォールバックします。
command?:
args?:
env?:
url?:
requestInit?:
eventSourceInit?:
logger?:
timeout?:
capabilities?:
enableServerLogs?:
LogHandler
LogHandler
関数は LogMessage
オブジェクトをパラメーターとして受け取り、void を返します。LogMessage
オブジェクトには以下のプロパティがあります。LoggingLevel
型は debug
、info
、warn
、error
の値を持つ文字列の列挙型です。
level:
message:
timestamp:
serverName:
details?:
メソッド
connect()
MCPサーバーへの接続を確立します。
async connect(): Promise<void>
disconnect()
MCPサーバーとの接続を切断します。
async disconnect(): Promise<void>
resources()
サーバーから利用可能なリソースの一覧を取得します。
async resources(): Promise<ListResourcesResult>
tools()
サーバーから利用可能なツールを取得し、初期化してMastra互換のツール形式に変換します。
async tools(): Promise<Record<string, Tool>>
ツール名を対応するMastraツール実装にマッピングしたオブジェクトを返します。
例
Mastra Agentとの併用
Stdioサーバーを使った例
import { Agent } from "@mastra/core/agent";
import { MastraMCPClient } from "@mastra/mcp";
import { openai } from "@ai-sdk/openai";
// Initialize the MCP client using mcp/fetch as an example https://hub.docker.com/r/mcp/fetch
// Visit https://github.com/docker/mcp-servers for other reference docker mcp servers
const fetchClient = new MastraMCPClient({
name: "fetch",
server: {
command: "docker",
args: ["run", "-i", "--rm", "mcp/fetch"],
logger: (logMessage) => {
console.log(`[${logMessage.level}] ${logMessage.message}`);
},
},
});
// Create a Mastra Agent
const agent = new Agent({
name: "Fetch agent",
instructions:
"You are able to fetch data from URLs on demand and discuss the response data with the user.",
model: openai("gpt-4o-mini"),
});
try {
// Connect to the MCP server
await fetchClient.connect();
// Gracefully handle process exits so the docker subprocess is cleaned up
process.on("exit", () => {
fetchClient.disconnect();
});
// Get available tools
const tools = await fetchClient.tools();
// Use the agent with the MCP tools
const response = await agent.generate(
"Tell me about mastra.ai/docs. Tell me generally what this page is and the content it includes.",
{
toolsets: {
fetch: tools,
},
},
);
console.log("\n\n" + response.text);
} catch (error) {
console.error("Error:", error);
} finally {
// Always disconnect when done
await fetchClient.disconnect();
}
SSEサーバーを使った例
// Initialize the MCP client using an SSE server
const sseClient = new MastraMCPClient({
name: "sse-client",
server: {
url: new URL("https://your-mcp-server.com/sse"),
// Optional fetch request configuration - Note: requestInit alone isn't enough for SSE
requestInit: {
headers: {
Authorization: "Bearer your-token",
},
},
// Required for SSE connections with custom headers
eventSourceInit: {
fetch(input: Request | URL | string, init?: RequestInit) {
const headers = new Headers(init?.headers || {});
headers.set("Authorization", "Bearer your-token");
return fetch(input, {
...init,
headers,
});
},
},
// Optional additional logging configuration
logger: (logMessage) => {
console.log(
`[${logMessage.level}] ${logMessage.serverName}: ${logMessage.message}`,
);
},
// Disable server logs
enableServerLogs: false,
},
});
// The rest of the usage is identical to the stdio example
SSE認証に関する重要な注意点
SSE接続で認証やカスタムヘッダーを使用する場合、requestInit
とeventSourceInit
の両方を設定する必要があります。これは、SSE接続がブラウザのEventSource APIを使用しており、カスタムヘッダーを直接サポートしていないためです。
eventSourceInit
の設定により、SSE接続で使用される内部のfetchリクエストをカスタマイズでき、認証ヘッダーが正しく含まれるようになります。
eventSourceInit
がない場合、requestInit
で指定した認証ヘッダーは接続リクエストに含まれず、401 Unauthorizedエラーが発生します。
関連情報
- アプリケーションで複数のMCPサーバーを管理する場合は、MCPClientのドキュメントをご覧ください
- Model Context Protocolの詳細については、@modelcontextprotocol/sdkのドキュメント をご参照ください。