极简Server搭建

创建asp.net core项目,这里创建的是Restful API

引用mcp包

<PackageReference Include="ModelContextProtocol" Version="0.1.0-preview.8" />
<PackageReference Include="ModelContextProtocol.AspNetCore" Version="0.1.0-preview.8" />

注意,要勾选“包含预览版”


修改Program.cs


namespace TestWeb_MCPServer
{
    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();
            // 增加McpServer
            builder.Services.AddMcpServer().WithToolsFromAssembly();
            builder.Services.AddSwaggerGen();
            // 增加跨域
            builder.Services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyHeader()
                           .AllowAnyMethod();
                });
            });

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            // 增加跨域
            app.UseCors();
            //注意:要注释掉, 否则Inspector会提示Connection Error, is your MCP server running?
            //app.UseHttpsRedirection();

            app.UseAuthorization();


            app.MapControllers();
            //启动Mcp
            app.MapMcp();

            app.Run();
        }
    }
}


增加Tool

创建名为EchoTool.cs文件,内容如下:

using ModelContextProtocol.Server;
using System.ComponentModel;

namespace TestWeb_MCPServer.Tools;

[McpServerToolType]
public sealed class EchoTool
{
    [McpServerTool, Description("Echoes the input back to the client.")]
    public static string Echo(string message)
    {
        return "hello " + message;
    }
}

启动Server

可以查看  http://localhost:5294/sse 是否返回如下信息:

event: endpoint
data: /message?sessionId=SXjxZrig0-Zi3SwO3E_APA

Inspector使用

进入命令行,执行如下命令

npx @modelcontextprotocol/inspector

或者,先安装,再运行

npm install -g @modelcontextprotocol/inspector

mcp-inspector 

访问 启动的地址

http://127.0.0.1:6274/

选择 Transport Type 为 SSE,输入Server地址,点击连接