Agent MCP。演示
演示 微软代理框架(MAF) 与...集成 MCP(模型上下文协议)服务器 使用。网8。
📋 概述
此解决方案展示了如何使用Microsoft Agent Framework构建智能代理,该框架可以通过MCP服务器端点调用外部工具。它展示了从代理推理到工具执行和结果处理的完整流程。
🏗️ 项目结构
AgentMCP.Demo/
├── AgentMCP.App/ # Main console application
│ ├── Framework/ # MAF core abstractions
│ │ ├── Agent.cs # Base agent class
│ │ ├── AgentBuilder.cs # Fluent API for agent configuration
│ │ ├── AgentResult.cs # Agent execution results
│ │ ├── ITool.cs # Tool interface
│ │ └── ToolResult.cs # Tool execution results
│ ├── Agents/
│ │ └── WeatherAgent.cs # Weather-specialized agent
│ ├── Tools/
│ │ └── WeatherTool.cs # MCP weather tool implementation
│ ├── Services/
│ │ ├── IMcpClient.cs # MCP client interface
│ │ └── McpClient.cs # HTTP client for MCP Server
│ ├── Models/
│ │ ├── McpServerOptions.cs # Configuration model
│ │ └── WeatherResponse.cs # Weather data model
│ ├── Program.cs # Application entry point
│ ├── MockMcpServer.cs # Mock MCP Server for testing
│ └── appsettings.json # Configuration file
│
└── AgentMCP.Tests/ # xUnit test project
└── UnitTest1.cs # Integration tests
🔑 主要特点
Microsoft代理框架集成
- 代理基类:具有推理能力的可扩展代理基础
- AgentBuilder API:代理和工具的流畅配置
- 工具系统:代理可以调用的可插入工具
- 依赖注入:使用完全DI支持
Microsoft.Extensions.DependencyInjection
MCP服务器集成
- HttpClientFactory模式:正确的HTTP连接管理
- 异步/等待:完全异步工具执行
- 基于配置的URL:可通过以下方式配置MCP端点
appsettings.json - 错误处理:全面的错误处理和记录
代理执行流程
- 输入:用户提供自然语言查询
- 推理:代理分析输入以确定操作
- 工具选择:代理选择合适的工具(例如天气工具)
- MCP调用:工具调用MCP服务器端点
- 结果处理:代理格式化并返回结果
🚀 入门指南
先决条件
- .NET 8 SDK
- Visual Studio 2022/VS代码/附加程序(可选)
安装
- 克隆或导航到解决方案:
cd AgentMCP.Demo- 恢复依赖关系:
dotnet restore- 构建解决方案:
dotnet build🎮 运行演示
选项1:使用模拟MCP服务器运行
步骤1:启动模拟MCP服务器 (1号航站楼):
cd AgentMCP.App
dotnet run --server或者使用PowerShell脚本:
.\run-mock-server.ps1模拟服务器将启动 http://localhost:5001 并记录传入的请求。
步骤2:运行代理应用程序 (在2号航站楼):
cd AgentMCP.App
dotnet run代理将执行示例天气查询并显示结果。
选项2:指向真正的MCP服务器
更新 appsettings.json:
{
"McpServer": {
"BaseUrl": "https://your-mcp-server.com",
"WeatherEndpoint": "/api/weather"
}
}然后运行:
dotnet run --project AgentMCP.App🧪 运行测试
执行xUnit测试以验证MCP集成:
dotnet test或运行特定测试:
dotnet test --filter "WeatherAgent_Should_Invoke_MCPServer_Successfully"测试覆盖率
测试套件包括:
- ✅ MCP服务器调用成功:验证端到端代理→ tool → MCP流量
- ✅ 错误处理:在MCP服务器不可用时测试代理行为
- ✅ 位置提取:验证自然语言解析
- ✅ HTTP请求验证:确保使用正确的参数进行正确的MCP端点调用
📝 配置
应用程序参数
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
}
},
"McpServer": {
"BaseUrl": "http://localhost:5001",
"WeatherEndpoint": "/mcp/weather"
}
}- BaseUrl:MCP服务器基址
- WeatherEndpoint:天气API终结点的相对路径
🔧 建筑
代理框架组件
1. 代理 (基本类)
public abstract class Agent
{
public abstract Task ExecuteAsync(string input, CancellationToken cancellationToken);
protected virtual Task ReasonAsync(string input, CancellationToken cancellationToken);
}2. 这个。 (工具界面)
public interface ITool
{
string Name { get; }
string Description { get; }
Task ExecuteAsync(Dictionary parameters, CancellationToken cancellationToken);
}3. AgentBuilder 的 (配置)
var agentBuilder = new AgentBuilder(services);
agentBuilder.AddTool();
agentBuilder.AddAgent();依赖注入设置
services.Configure(configuration.GetSection("McpServer"));
services.AddHttpClient((sp, client) =>
{
var options = sp.GetRequiredService>().Value;
client.BaseAddress = new Uri(options.BaseUrl);
});
var agentBuilder = new AgentBuilder(services);
agentBuilder.AddTool();
agentBuilder.AddAgent();📊 输出示例
============================================================
Query: What's the weather in Seattle?
============================================================
✓ Agent execution successful!
Result:
Weather in Seattle:
Temperature: 65.5°F
Condition: Partly Cloudy
Humidity: 72%
Last Updated: 2025-10-30 02:00:00 UTC
Metadata:
location: Seattle
tool_used: get_weather
timestamp: 10/30/2025 2:00:05 AM🛠️ 扩展演示
添加新工具
- 创建工具类:
public class MyCustomTool : ITool
{
public string Name => "my_tool";
public string Description => "Description of what the tool does";
public async Task ExecuteAsync(Dictionary parameters, CancellationToken cancellationToken)
{
// Implementation
}
}- 在Program.cs中注册:
agentBuilder.AddTool();创建新代理
- 继承自Agent:
public class MyAgent : Agent
{
public MyAgent(ILogger logger, IServiceProvider serviceProvider, IEnumerable tools)
: base(logger, serviceProvider) { }
public override async Task ExecuteAsync(string input, CancellationToken cancellationToken)
{
// Agent logic
}
}- 注册代理人:
agentBuilder.AddAgent();📚 使用的技术
- .NET 8:最新。net框架
- 微软。扩展。托管:DI和配置的通用主机
- 微软。扩展。超文本传输协议:用于弹性HTTP调用的HttpClientFactory
- x单位:单元测试框架
- 最小订货量:模拟测试库
- 系统。文本。JSON:JSON序列化
🤝 贡献
这是一个示范项目。请随意为您自己的用例进行分叉和扩展。
📄 许可证
本项目按原样提供,用于教育和示范目的。
🔗 相关资源
______________________________________________________________________
内置❤️ 使用。NET 8与微软代理框架
