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--
作者:xuejianxiyang
出处:http://xuejianxiyang.cnblogs.com
关于作者:Heaven helps those who help themselves.
本文版权归原作者和博客园共有,欢迎转载,但未经原作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号