智能代理框架演示

展示如何利用Microsoft Agent Framework与MCP服务器集成构建智能代理,实现从自然语言查询到工具调用的完整流程。

  • by GenAiGenius
  • C#
  • 本地部署
  • 更新于
在 GitHub 查看 GenAiGenius/AgentMCP.Demo

使用说明

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
  • 错误处理:全面的错误处理和记录

代理执行流程

  1. 输入:用户提供自然语言查询
  2. 推理:代理分析输入以确定操作
  3. 工具选择:代理选择合适的工具(例如天气工具)
  4. MCP调用:工具调用MCP服务器端点
  5. 结果处理:代理格式化并返回结果

🚀 入门指南

先决条件

  • .NET 8 SDK
  • Visual Studio 2022/VS代码/附加程序(可选)

安装

  1. 克隆或导航到解决方案:

    cd AgentMCP.Demo
    
  2. 恢复依赖关系:

    dotnet restore
    
  3. 构建解决方案:

    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<AgentResult> ExecuteAsync(string input, CancellationToken cancellationToken);
    protected virtual Task<string> ReasonAsync(string input, CancellationToken cancellationToken);
}

2. 这个。 (工具界面)

public interface ITool
{
    string Name { get; }
    string Description { get; }
    Task<ToolResult> ExecuteAsync(Dictionary<string, object> parameters, CancellationToken cancellationToken);
}

3. AgentBuilder 的 (配置)

var agentBuilder = new AgentBuilder(services);
agentBuilder.AddTool<WeatherTool>();
agentBuilder.AddAgent<WeatherAgent>();

依赖注入设置

services.Configure<McpServerOptions>(configuration.GetSection("McpServer"));

services.AddHttpClient<IMcpClient, McpClient>((sp, client) =>
{
    var options = sp.GetRequiredService<IOptions<McpServerOptions>>().Value;
    client.BaseAddress = new Uri(options.BaseUrl);
});

var agentBuilder = new AgentBuilder(services);
agentBuilder.AddTool<WeatherTool>();
agentBuilder.AddAgent<WeatherAgent>();

📊 输出示例

============================================================
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

🛠️ 扩展演示

添加新工具

  1. 创建工具类:
public class MyCustomTool : ITool
{
    public string Name => "my_tool";
    public string Description => "Description of what the tool does";
    
    public async Task<ToolResult> ExecuteAsync(Dictionary<string, object> parameters, CancellationToken cancellationToken)
    {
        // Implementation
    }
}
  1. 在Program.cs中注册:
agentBuilder.AddTool<MyCustomTool>();

创建新代理

  1. 继承自Agent:
public class MyAgent : Agent
{
    public MyAgent(ILogger<MyAgent> logger, IServiceProvider serviceProvider, IEnumerable<ITool> tools)
        : base(logger, serviceProvider) { }
    
    public override async Task<AgentResult> ExecuteAsync(string input, CancellationToken cancellationToken)
    {
        // Agent logic
    }
}
  1. 注册代理人:
agentBuilder.AddAgent<MyAgent>();

📚 使用的技术

  • .NET 8:最新。net框架
  • 微软。扩展。托管:DI和配置的通用主机
  • 微软。扩展。超文本传输协议:用于弹性HTTP调用的HttpClientFactory
  • x单位:单元测试框架
  • 最小订货量:模拟测试库
  • 系统。文本。JSON:JSON序列化

🤝 贡献

这是一个示范项目。请随意为您自己的用例进行分叉和扩展。

📄 许可证

本项目按原样提供,用于教育和示范目的。

🔗 相关资源


内置❤️ 使用。NET 8与微软代理框架