共用方式為


將 MCP 工具與代理程式搭配使用

Microsoft 代理程式架構支援與模型內容通訊協定 (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 工具類型

代理程式架構支援三種類型的 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 透過 HTTP 連線至 MCP 伺服器,並 Server-Sent 事件:

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 - 檔案系統作業
  • GitHubnpx @modelcontextprotocol/server-github - GitHub 存放庫存取
  • SQLiteuvx mcp-server-sqlite - 資料庫操作

每部伺服器都提供不同的工具和功能,可擴充代理程式的功能,同時維持「模型內容通訊協定」的安全性和標準化優勢。

後續步驟