Skip to Content
リファレンスツールリファレンス: MastraMCPClient | ツールディスカバリー | Mastra ドキュメント

MastraMCPClient(非推奨)

MastraMCPClient クラスは、Model Context Protocol(MCP)サーバーとやり取りするためのクライアント実装を提供します。このクラスは、MCPプロトコルを通じて接続管理、リソースの発見、およびツールの実行を行います。

非推奨のお知らせ

MastraMCPClientMCPClient への移行に伴い非推奨となります。単一の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:

string
このクライアントインスタンスの名前識別子。

version?:

string
= 1.0.0
クライアントのバージョン。

server:

MastraMCPServerDefinition
stdio サーバー接続または SSE サーバー接続のいずれかの構成パラメーター。ログハンドラーやサーバーログの設定も含めることができます。

capabilities?:

ClientCapabilities
= {}
クライアントのオプション機能設定。

timeout?:

number
= 60000
クライアントツール呼び出しのタイムアウト時間(ミリ秒単位)。

MastraMCPServerDefinition

MCP サーバーはこの定義を使って設定できます。クライアントは、指定されたパラメーターに基づいて自動的にトランスポートタイプを検出します:

  • command が指定されている場合、Stdio トランスポートを使用します。
  • url が指定されている場合、まず Streamable HTTP トランスポートを試み、初回接続に失敗した場合はレガシー SSE トランスポートにフォールバックします。

command?:

string
Stdio サーバー用:実行するコマンド。

args?:

string[]
Stdio サーバー用:コマンドに渡す引数。

env?:

Record<string, string>
Stdio サーバー用:コマンドに設定する環境変数。

url?:

URL
HTTP サーバー(Streamable HTTP または SSE)用:サーバーの URL。

requestInit?:

RequestInit
HTTP サーバー用:fetch API のリクエスト設定。

eventSourceInit?:

EventSourceInit
SSE フォールバック用:SSE 接続のためのカスタム fetch 設定。SSE でカスタムヘッダーを使用する場合に必須です。

logger?:

LogHandler
オプションの追加ログハンドラー。

timeout?:

number
サーバー固有のタイムアウト(ミリ秒単位)。

capabilities?:

ClientCapabilities
サーバー固有の機能設定。

enableServerLogs?:

boolean
= true
このサーバーのログを有効にするかどうか。

LogHandler

LogHandler 関数は LogMessage オブジェクトをパラメーターとして受け取り、void を返します。LogMessage オブジェクトには以下のプロパティがあります。LoggingLevel 型は debuginfowarnerror の値を持つ文字列の列挙型です。


level:

LoggingLevel
ログレベル(debug, info, warn, error)

message:

string
ログメッセージの内容

timestamp:

Date
ログが生成された日時

serverName:

string
ログを生成したサーバー名

details?:

Record<string, any>
オプションの追加ログ詳細

メソッド

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接続で認証やカスタムヘッダーを使用する場合、requestIniteventSourceInitの両方を設定する必要があります。これは、SSE接続がブラウザのEventSource APIを使用しており、カスタムヘッダーを直接サポートしていないためです。

eventSourceInitの設定により、SSE接続で使用される内部のfetchリクエストをカスタマイズでき、認証ヘッダーが正しく含まれるようになります。 eventSourceInitがない場合、requestInitで指定した認証ヘッダーは接続リクエストに含まれず、401 Unauthorizedエラーが発生します。

関連情報