模型上下文協議是一種開放標準,定義了應用程序如何向大型語言模型 (LLM) 提供工具和上下文數據。 其可讓外部工具與模型工作流程整合一致且可調整。
Microsoft Agent Framework 支援與模型情境協定(MCP)伺服器整合,讓您的代理能存取外部工具與服務。 本指南說明如何連線到 MCP 伺服器,並在代理程式中使用其工具。
使用第三方 MCP 伺服器的考量
您使用模型情境協定伺服器時,須遵守您與服務提供者之間的條款。 當您連線到非Microsoft服務時,某些數據(例如提示內容)會傳遞至非Microsoft服務,或您的應用程式可能會從非Microsoft服務接收數據。 您必須負責使用非Microsoft服務和數據,以及與該使用相關聯的任何費用。
您決定搭配本文所述的 MCP 工具使用的遠端 MCP 伺服器是由第三方所建立,而不是Microsoft。 Microsoft尚未測試或驗證這些伺服器。 Microsoft 對您或其他人使用任何遠端 MCP 伺服器概不負責。
建議您仔細檢閱並追蹤您新增至代理程式架構型應用程式的 MCP 伺服器。 我們也建議您依賴由可信任的服務提供商本身所託管的伺服器,而不是代理伺服器。
MCP 工具可讓您傳遞遠端 MCP 伺服器可能需要的自定義標頭,例如驗證金鑰或架構。 建議您檢閱與遠端 MCP 伺服器共用的所有數據,並記錄數據以供稽核之用。 注意非Microsoft的資料保留和定位做法。
這很重要
你只能在每次執行時將標頭納入tool_resources中來指定標頭。 如此一來,您可以將 API 金鑰、OAuth 存取令牌或其他認證直接放在您的要求中。 您所傳遞的標頭僅適用於當前的運行,且不會被保存。
欲了解更多關於 MCP 安全性的資訊,請參見:
- 模型內容通訊協議網站上的安全性最佳做法。
- 在 Microsoft 安全性社群部落格中瞭解及降低 MCP 實作中的安全性風險。
.NET 版本的 Agent Framework 可搭配 官方的 MCP C# SDK 使用,讓您的代理程式呼叫 MCP 工具。
下列範例示範如何:
- 設定和 MCP 伺服器
- 從 MCP 伺服器擷取可用工具清單
- 將 MCP 工具
AIFunction轉換為 ,以便將它們新增至代理程式 - 使用函數呼叫從代理程式叫用工具
設定 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>()]);
警告
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?"));
代理人將:
- 分析使用者的要求
- 判斷需要哪些 MCP 工具
- 透過 MCP 伺服器呼叫適當的工具
- 將結果綜合成連貫的回應
環境設定
請務必設定必要的環境變數:
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 工具類型
代理程式架構支援三種類型的 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 透過 HTTP 連線至 MCP 伺服器,並 Server-Sent 事件:
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())
熱門 MCP 伺服器
您可以與 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)