次の方法で共有


エージェントでの MCP ツールの使用

Microsoft Agent Framework では、モデル コンテキスト プロトコル (MCP) サーバーとの統合がサポートされているため、エージェントは外部ツールやサービスにアクセスできます。 このガイドでは、MCP サーバーに接続し、エージェント内でそのツールを使用する方法について説明します。

エージェント フレームワークの .Net バージョンを 公式の MCP C# SDK と共に使用して、エージェントが MCP ツールを呼び出せるようにすることができます。

次の例は、次の方法を示しています。

  1. MCP サーバーを設定する
  2. MCP サーバーから使用可能なツールの一覧を取得する
  3. MCP ツールを AIFunction に変換して、エージェントに追加できるようにします
  4. 関数呼び出しを使用してエージェントからツールを呼び出す

MCP クライアントの設定

まず、目的の MCP サーバーに接続する MCP クライアントを作成します。

// Create an MCPClient for the GitHub server
await using var mcpClient = await McpClientFactory.CreateAsync(new StdioClientTransport(new()
{
    Name = "MCPServer",
    Command = "npx",
    Arguments = ["-y", "--verbose", "@modelcontextprotocol/server-github"],
}));

この例では:

  • 名前: MCP サーバー接続のフレンドリ名
  • コマンド: MCP サーバーを実行する実行可能ファイル (ここでは npx を使用して Node.js パッケージを実行します)
  • 引数: MCP サーバーに渡されるコマンド ライン引数

使用可能なツールの取得

接続したら、MCP サーバーから使用可能なツールの一覧を取得します。

// Retrieve the list of tools available on the GitHub server
var mcpTools = await mcpClient.ListToolsAsync().ConfigureAwait(false);

ListToolsAsync() メソッドは、MCP サーバーが公開するツールのコレクションを返します。 これらのツールは、エージェントで使用できる AITool オブジェクトに自動的に変換されます。

MCP ツールを使用したエージェントの作成

初期化中にエージェントを作成し、MCP ツールを提供します。

AIAgent agent = new AzureOpenAIClient(
    new Uri(endpoint),
    new AzureCliCredential())
     .GetChatClient(deploymentName)
     .CreateAIAgent(
         instructions: "You answer questions related to GitHub repositories only.", 
         tools: [.. mcpTools.Cast<AITool>()]);

重要なポイント:

  • 手順: MCP ツールの機能に合った明確な手順を提供する
  • ツール: MCP ツールをキャストしてオブジェクトを AITool し、ツール配列に展開する
  • エージェントは、MCP サーバーによって提供されるすべてのツールに自動的にアクセスできます。

エージェントの使用

構成が完了すると、エージェントは MCP ツールを自動的に使用してユーザー要求を満たすことができます。

// Invoke the agent and output the text result
Console.WriteLine(await agent.RunAsync("Summarize the last four commits to the microsoft/semantic-kernel repository?"));

エージェントは次の内容を実行します。

  1. ユーザーの要求を分析する
  2. 必要な MCP ツールを決定する
  3. MCP サーバーを介して適切なツールを呼び出す
  4. 結果をコヒーレント応答に合成する

環境の構成

必要な環境変数を必ず設定してください。

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? 
    throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

リソース管理

MCP クライアント リソースを常に適切に破棄します。

await using var mcpClient = await McpClientFactory.CreateAsync(...);

await usingを使用すると、MCP クライアント接続がスコープ外になったときに適切に閉じられます。

一般的な MCP サーバー

一般的な MCP サーバーは次のとおりです。

  • @modelcontextprotocol/server-github: GitHub リポジトリとデータにアクセスする
  • @modelcontextprotocol/server-filesystem: ファイル システムの操作
  • @modelcontextprotocol/server-sqlite: SQLite データベース へのアクセス

各サーバーには、エージェントの機能を拡張するさまざまなツールと機能が用意されています。 この統合により、エージェントは、モデル コンテキスト プロトコルのセキュリティと標準化の利点を維持しながら、外部データとサービスにシームレスにアクセスできます。

このサンプルを実行するための完全なソース コードと手順については、 こちらをご覧ください

Python エージェント フレームワークは、複数の接続の種類を通じてモデル コンテキスト プロトコル (MCP) サーバーと統合するための包括的なサポートを提供します。 これにより、エージェントは外部ツールとサービスにシームレスにアクセスできます。

MCP ツールの種類

エージェント フレームワークでは、次の 3 種類の MCP 接続がサポートされています。

MCPStdioTool - ローカル MCP サーバー

MCPStdioToolを使用して、標準の入力/出力を使用してローカル プロセスとして実行される MCP サーバーに接続します。

import asyncio
from agent_framework import ChatAgent, MCPStdioTool
from agent_framework.openai import OpenAIChatClient

async def local_mcp_example():
    """Example using a local MCP server via stdio."""
    async with (
        MCPStdioTool(
            name="calculator", 
            command="uvx", 
            args=["mcp-server-calculator"]
        ) as mcp_server,
        ChatAgent(
            chat_client=OpenAIChatClient(),
            name="MathAgent",
            instructions="You are a helpful math assistant that can solve calculations.",
        ) as agent,
    ):
        result = await agent.run(
            "What is 15 * 23 + 45?", 
            tools=mcp_server
        )
        print(result)

if __name__ == "__main__":
    asyncio.run(local_mcp_example())

MCPStreamableHTTPTool - HTTP/SSE MCP サーバー

MCPStreamableHTTPToolを使用して、Server-Sent イベントを使用して HTTP 経由で MCP サーバーに接続します。

import asyncio
from agent_framework import ChatAgent, MCPStreamableHTTPTool
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def http_mcp_example():
    """Example using an HTTP-based MCP server."""
    async with (
        AzureCliCredential() as credential,
        MCPStreamableHTTPTool(
            name="Microsoft Learn MCP",
            url="https://learn.microsoft.com/api/mcp",
            headers={"Authorization": "Bearer your-token"},
        ) as mcp_server,
        ChatAgent(
            chat_client=AzureAIAgentClient(async_credential=credential),
            name="DocsAgent",
            instructions="You help with Microsoft documentation questions.",
        ) as agent,
    ):
        result = await agent.run(
            "How to create an Azure storage account using az cli?",
            tools=mcp_server
        )
        print(result)

if __name__ == "__main__":
    asyncio.run(http_mcp_example())

MCPWebsocketTool - WebSocket MCP サーバー

MCPWebsocketToolを使用して、WebSocket 接続経由で MCP サーバーに接続します。

import asyncio
from agent_framework import ChatAgent, MCPWebsocketTool
from agent_framework.openai import OpenAIChatClient

async def websocket_mcp_example():
    """Example using a WebSocket-based MCP server."""
    async with (
        MCPWebsocketTool(
            name="realtime-data",
            url="wss://api.example.com/mcp",
        ) as mcp_server,
        ChatAgent(
            chat_client=OpenAIChatClient(),
            name="DataAgent",
            instructions="You provide real-time data insights.",
        ) as agent,
    ):
        result = await agent.run(
            "What is the current market status?",
            tools=mcp_server
        )
        print(result)

if __name__ == "__main__":
    asyncio.run(websocket_mcp_example())

Python エージェント フレームワークで使用できる一般的な MCP サーバー:

  • 電卓: uvx mcp-server-calculator - 数学計算
  • ファイルシステム: uvx mcp-server-filesystem - ファイル システムの操作
  • GitHub: npx @modelcontextprotocol/server-github - GitHub リポジトリへのアクセス
  • SQLite: uvx mcp-server-sqlite - データベース操作

各サーバーには、モデル コンテキスト プロトコルのセキュリティと標準化の利点を維持しながら、エージェントの機能を拡張するさまざまなツールと機能が用意されています。

次のステップ