Microsoft Agent Framework 支持与模型上下文协议 (MCP) 服务器集成,使代理可以访问外部工具和服务。 本指南演示如何连接到 MCP 服务器,并在代理中使用其工具。
代理框架的 .Net 版本可与 官方 MCP C# SDK 一起使用,以允许代理调用 MCP 工具。
以下示例演示如何:
- 设置和 MCP 服务器
- 从 MCP 服务器检索可用工具的列表
- 将 MCP 工具转换为
AIFunction's,以便可以将其添加到代理 - 使用函数调用从代理调用工具
设置 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?"));
代理将:
- 分析用户的请求
- 确定需要哪些 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 数据库访问
每个服务器提供扩展代理功能的不同工具和功能。 通过此集成,代理可以无缝访问外部数据和服务,同时维护模型上下文协议的安全性和标准化优势。
此处提供了运行此示例的完整源代码和说明。
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://free.blessedness.top/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())
常用 MCP 服务器
可与 Python 代理框架一起使用的常见 MCP 服务器:
-
计算器:
uvx mcp-server-calculator- 数学计算 -
文件系统:
uvx mcp-server-filesystem- 文件系统作 -
GitHub:
npx @modelcontextprotocol/server-github- GitHub 存储库访问权限 -
SQLite:
uvx mcp-server-sqlite- 数据库作
每个服务器提供不同的工具和功能,用于扩展代理的功能,同时维护模型上下文协议的安全性和标准化优势。