c# .netcore webapi实现一个简单的mcp server

1.安装 ModelContextProtocol.AspNetCore 包

 

2.创建一个类文件

    [McpServerToolType]
    public class AddTool
    {
        //private readonly ILogger logger;

        public AddTool(/*ILogger logger*/)
        {
            //this.logger = logger;
        }
        [McpServerTool(Name = "add"), Description("Add two numbers.")]
        public  string Add(int a, int b ,  [FromServices]ILogger logger /*这个自动注入的参数在cursor中会导致失败,暂时方法内部用service locate来解决吧...*/) => $"The result of {a} + {b} is {a + b}";

        [McpServerTool(Name = "sub"), Description("Sub two numbers.")]
        public string Sub(int a, int b) => $"The result of {a} - {b} is {a - b}";

    }

 

3.注册mcp server

  public class Program
  {
      public static void Main(string[] args)
      {
          var builder = WebApplication.CreateBuilder(args);

          // Add services to the container.

          builder.Services.AddControllers();
          // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
          builder.Services.AddEndpointsApiExplorer();
          builder.Services.AddSwaggerGen();
          builder.Services.AddLogging();

          builder.Services.AddMcpServer() // 注册 McpServer 相关服务
          .WithTools<Tools.AddTool>();
         //.WithToolsFromAssembly(); // 从程序集中扫描添加 tools
    

          var app = builder.Build();

          // Configure the HTTP request pipeline.
          if (app.Environment.IsDevelopment())
          {
              app.UseSwagger();
              app.UseSwaggerUI();
          }

          //app.UseAuthorization();


          app.MapControllers();

          app.MapMcp();
          app.Run();
      }
  }

4.测试

cmd执行探查mcp服务命令

npx @modelcontextprotocol/inspector

浏览器 打开图中对应的地址打开mcp client界面

在url地址中输入webapi启动后的地址和端口/sse

点击connect 

点击右侧list选择add......

 

5.cursor中使用的效果:

   "MyMcp": {
      "url": "http://localhost:9999/sse"
    },

 

 

参考 https://zhuanlan.zhihu.com/p/1892256294318109400

 

--EOF--

 

 
 
posted @ 2025-05-28 10:13  Ace001  阅读(235)  评论(1)    收藏  举报