次の方法で共有


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

モデル コンテキスト プロトコルは、アプリケーションが大規模言語モデル (LLM) にツールとコンテキスト データを提供する方法を定義するオープン標準です。 これにより、外部ツールをモデル ワークフローに一貫性のあるスケーラブルに統合できます。

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

サード パーティ製 MCP サーバーの使用に関する考慮事項

モデル コンテキスト プロトコル サーバーの使用は、お客様とサービス プロバイダー間の条件に従います。 Microsoft 以外のサービスに接続すると、データの一部 (プロンプト コンテンツなど) が Microsoft 以外のサービスに渡されるか、アプリケーションが Microsoft 以外のサービスからデータを受信する可能性があります。 お客様は、Microsoft 以外のサービスとデータの使用と、その使用に関連する料金について責任を負います。

この記事で説明されている MCP ツールで使用することを決定したリモート MCP サーバーは、Microsoft ではなく第三者によって作成されました。 Microsoft は、これらのサーバーをテストまたは検証していません。 Microsoft は、お客様によるリモート MCP サーバーの使用に関して、お客様または他のユーザーに対して一切の責任を負いません。

Agent Framework ベースのアプリケーションに追加する MCP サーバーを慎重に確認して追跡することをお勧めします。 また、プロキシではなく、信頼されたサービス プロバイダー自体によってホストされているサーバーに依存することもお勧めします。

MCP ツールを使用すると、リモート MCP サーバーが必要とする可能性がある認証キーやスキーマなどのカスタム ヘッダーを渡すことができます。 リモート MCP サーバーと共有されているすべてのデータを確認し、監査目的でデータをログに記録することをお勧めします。 データの保持と場所に関する Microsoft 以外のプラクティスを認識する。

Important

ヘッダーは、各実行時にtool_resourcesに含めることでのみ指定できます。 この方法で、API キー、OAuth アクセス トークン、またはその他の資格情報を要求に直接配置できます。 渡すヘッダーは、現在の実行でのみ使用でき、永続化されません。

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 DefaultAzureCredential())
     .GetChatClient(deploymentName)
     .AsAIAgent(
         instructions: "You answer questions related to GitHub repositories only.",
         tools: [.. mcpTools.Cast<AITool>()]);

Warnung

DefaultAzureCredential は開発には便利ですが、運用環境では慎重に考慮する必要があります。 運用環境では、待機時間の問題、意図しない資格情報のプローブ、フォールバック メカニズムによる潜在的なセキュリティ リスクを回避するために、特定の資格情報 ( ManagedIdentityCredential など) を使用することを検討してください。

重要なポイント:

  • 手順: 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 データベース へのアクセス

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

このサンプルを実行するための完全なソース コードと手順は、 https://github.com/microsoft/agent-framework/tree/main/dotnet/samples/GettingStarted/ModelContextProtocol/Agent_MCP_Serverで入手できます。

ヒント

実行可能な完全な例については、 .NET サンプル を参照してください。

これにより、エージェントは外部ツールとサービスにシームレスにアクセスできます。

MCP ツールの種類

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

MCPStdioTool - ローカル MCP サーバー

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

import asyncio
from agent_framework import Agent, 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,
        Agent(
            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 Agent, 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,
        Agent(
            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 Agent, 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,
        Agent(
            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 - データベース操作

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

完全な例

# Copyright (c) Microsoft. All rights reserved.

import os

from agent_framework import Agent, MCPStreamableHTTPTool
from agent_framework.openai import OpenAIResponsesClient
from httpx import AsyncClient

"""
MCP Authentication Example

This example demonstrates how to authenticate with MCP servers using API key headers.

For more authentication examples including OAuth 2.0 flows, see:
- https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/clients/simple-auth-client
- https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/servers/simple-auth
"""


async def api_key_auth_example() -> None:
    """Example of using API key authentication with MCP server."""
    # Configuration
    mcp_server_url = os.getenv("MCP_SERVER_URL", "your-mcp-server-url")
    api_key = os.getenv("MCP_API_KEY")

    # Create authentication headers
    # Common patterns:
    # - Bearer token: "Authorization": f"Bearer {api_key}"
    # - API key header: "X-API-Key": api_key
    # - Custom header: "Authorization": f"ApiKey {api_key}"
    auth_headers = {
        "Authorization": f"Bearer {api_key}",
    }

    # Create HTTP client with authentication headers
    http_client = AsyncClient(headers=auth_headers)

    # Create MCP tool with the configured HTTP client
    async with (
        MCPStreamableHTTPTool(
            name="MCP tool",
            description="MCP tool description",
            url=mcp_server_url,
            http_client=http_client,  # Pass HTTP client with authentication headers
        ) as mcp_tool,
        Agent(
            client=OpenAIResponsesClient(),
            name="Agent",
            instructions="You are a helpful assistant.",
            tools=mcp_tool,
        ) as agent,
    ):
        query = "What tools are available to you?"
        print(f"User: {query}")
        result = await agent.run(query)
        print(f"Agent: {result.text}")

エージェントを MCP サーバーとして公開する

エージェントを MCP サーバーとして公開し、MCP と互換性のあるクライアント (VS Code GitHub Copilot エージェントやその他のエージェントなど) によってツールとして使用できます。 エージェントの名前と説明が MCP サーバーメタデータになります。

.AsAIFunction()を使用して関数ツールでエージェントをラップし、McpServerToolを作成して、MCP サーバーに登録します。

using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Server;

// Create the agent
AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
        .GetChatClient("gpt-4o-mini")
        .AsAIAgent(instructions: "You are good at telling jokes.", name: "Joker");

// Convert the agent to an MCP tool
McpServerTool tool = McpServerTool.Create(agent.AsAIFunction());

// Set up the MCP server over stdio
HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(settings: null);
builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithTools([tool]);

await builder.Build().RunAsync();

必要な NuGet パッケージをインストールします。

dotnet add package Microsoft.Extensions.Hosting --prerelease
dotnet add package ModelContextProtocol --prerelease

エージェントの .as_mcp_server() を呼び出して、MCP サーバーとして公開します。

from agent_framework.openai import OpenAIResponsesClient
from typing import Annotated

def get_specials() -> Annotated[str, "Returns the specials from the menu."]:
    return "Special Soup: Clam Chowder, Special Salad: Cobb Salad"

# Create an agent with tools
agent = OpenAIResponsesClient().as_agent(
    name="RestaurantAgent",
    description="Answer questions about the menu.",
    tools=[get_specials],
)

# Expose the agent as an MCP server
server = agent.as_mcp_server()

標準の入力/出力をリッスンするように MCP サーバーを設定します。

import anyio
from mcp.server.stdio import stdio_server

async def run():
    async with stdio_server() as (read_stream, write_stream):
        await server.run(read_stream, write_stream, server.create_initialization_options())

if __name__ == "__main__":
    anyio.run(run)

次のステップ