MCP の概要
Mastra は、AI エージェントを外部のツールやリソースに接続するためのオープン標準である Model Context Protocol (MCP) をサポートしています。汎用的なプラグインシステムとして機能し、言語やホスティング環境にかかわらずエージェントがツールを呼び出せます。
Mastra は MCP サーバーの作成にも利用でき、MCP インターフェースを通じてエージェント、ツール、その他の構造化リソースを公開します。これらは、プロトコルをサポートするあらゆるシステムやエージェントから利用できます。
Mastra は現在、2 つの MCP クラスをサポートしています:
MCPClient
: ツール、リソース、プロンプトへのアクセスや、エリシテーション(情報引き出し)要求の処理のために、1 つまたは複数の MCP サーバーに接続します。MCPServer
: MCP 互換クライアントに対して、Mastra のツール、エージェント、ワークフロー、プロンプト、リソースを公開します。
はじめに
MCP を利用するには、必要な依存関係をインストールします。
npm install @mastra/mcp@latest
MCPClient
の設定
MCPClient
は、Mastra のプリミティブを外部の MCP サーバーに接続します。サーバーはローカルパッケージ(npx
で実行)またはリモートの HTTP(S) エンドポイントのいずれかです。各サーバーは、ホスティング形態に応じて command
または url
のいずれかで設定する必要があります。
import { MCPClient } from "@mastra/mcp";
export const testMcpClient = new MCPClient({
id: "test-mcp-client",
servers: {
wikipedia: {
command: "npx",
args: ["-y", "wikipedia-mcp"]
},
weather: {
url: new URL(`https://server.smithery.ai/@smithery-ai/national-weather-service/mcp?api_key=${process.env.SMITHERY_API_KEY}`)
},
}
});
すべての設定オプションについては MCPClient を参照してください。
エージェントでのMCPClient
の使用
エージェントでMCPサーバーのツールを使うには、MCPClient
をインポートし、tools
パラメータで.getTools()
を呼び出します。これにより、定義済みのMCPサーバーからツールが読み込まれ、エージェントで利用できるようになります。
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { testMcpClient } from "../mcp/test-mcp-client";
export const testAgent = new Agent({
name: "Test Agent",
description: "You are a helpful AI assistant",
instructions: `
You are a helpful assistant that has access to the following MCP Servers.
- Wikipedia MCP Server
- US National Weather Service
Answer questions using the information you find using the MCP Servers.`,
model: openai("gpt-4o-mini"),
tools: await testMcpClient.getTools()
});
設定オプションの全一覧はAgent Classを参照してください。
MCPServer
の設定
Mastra アプリケーションのエージェント、ツール、ワークフローを HTTP(S) 経由で外部システムに公開するには、MCPServer
クラスを使用します。これにより、プロトコルをサポートするあらゆるシステムやエージェントから利用可能になります。
import { MCPServer } from "@mastra/mcp";
import { testAgent } from "../agents/test-agent";
import { testWorkflow } from "../workflows/test-workflow";
import { testTool } from "../tools/test-tool";
export const testMcpServer = new MCPServer({
id: "test-mcp-server",
name: "Test Server",
version: "1.0.0",
agents: { testAgent },
tools: { testTool },
workflows: { testWorkflow }
});
設定オプションの一覧については、MCPServer を参照してください。
MCPServer
の登録
プロトコルに対応する他のシステムやエージェントで MCP サーバーを利用可能にするには、メインの Mastra
インスタンスで mcpServers
に登録します。
import { Mastra } from "@mastra/core/mastra";
import { testMcpServer } from "./mcp/test-mcp-server";
export const mastra = new Mastra({
// ...
mcpServers: { testMcpServer }
});
静的ツールと動的ツール
MCPClient
は、接続先サーバーからツールを取得するために、さまざまなアプリケーションアーキテクチャに適した2つのアプローチを提供します:
機能 | 静的構成 (await mcp.getTools() ) | 動的構成 (await mcp.getToolsets() ) |
---|---|---|
ユースケース | 単一ユーザー向けの静的設定(例:CLI ツール) | 複数ユーザー向けの動的設定(例:SaaS アプリ) |
構成 | エージェント初期化時に固定 | リクエストごとに動的 |
認証情報 | すべての利用で共有 | ユーザー/リクエストごとに可変 |
エージェント設定 | Agent コンストラクターでツールを追加 | .generate() または .stream() のオプションとしてツールを渡す |
静的ツール
すべての設定済み MCP サーバーからツールを取得するには、.getTools()
メソッドを使用します。これは、設定(API キーなど)がユーザーやリクエスト間で静的かつ一貫している場合に適しています。エージェントを定義する際に一度だけ呼び出し、その結果を tools
プロパティに渡してください。
詳細は getTools() を参照してください。
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { testMcpClient } from "../mcp/test-mcp-client";
export const testAgent = new Agent({
// ...
tools: await testMcpClient.getTools()
});
動的ツール
各リクエストやユーザーごとにツールの構成が変わる場合(例:各ユーザーが自分の API キーを提供するマルチテナントシステム)、.getToolsets()
メソッドを使用します。このメソッドは、エージェントの .generate()
または .stream()
呼び出しの toolsets
オプションに渡せるツールセットを返します。
import { MCPClient } from "@mastra/mcp";
import { mastra } from "./mastra";
async function handleRequest(userPrompt: string, userApiKey: string) {
const userMcp = new MCPClient({
servers: {
weather: {
url: new URL("http://localhost:8080/mcp"),
requestInit: {
headers: {
Authorization: `Bearer ${userApiKey}`
}
}
}
}
});
const agent = mastra.getAgent("testAgent");
const response = await agent.generate(userPrompt, {
toolsets: await userMcp.getToolsets()
});
await userMcp.disconnect();
return Response.json({
data: response.text
});
}
詳細は getToolsets() を参照してください。
MCP レジストリへの接続
MCP サーバーはレジストリ経由で探索できます。MCPClient
を使って一般的なレジストリに接続する方法は次のとおりです。
Klavis AI
Klavis AI は、ホスティング型でエンタープライズ認証に対応した高品質な MCP サーバーを提供します。
import { MCPClient } from "@mastra/mcp";
const mcp = new MCPClient({
servers: {
salesforce: {
url: new URL("https://salesforce-mcp-server.klavis.ai/mcp/?instance_id={private-instance-id}"),
},
hubspot: {
url: new URL("https://hubspot-mcp-server.klavis.ai/mcp/?instance_id={private-instance-id}"),
},
},
});
Klavis AI は、本番運用向けにエンタープライズレベルの認証とセキュリティを提供します。
Mastra と Klavis の統合方法の詳細については、ドキュメント をご覧ください。