十分钟入门MCPServer,创建您自己的MCPServer工具

360影视 国产动漫 2025-04-02 09:41 2

摘要:public staticclassMcpEndpointrouteBuilderExtensions{public static IEndpointConventionBuilderMapMcpSse(this IEndpointRouteBuilder e

如果您需要深入交流了解请加入我们一块交流:

https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=b7co0430-daed-441b-8b6f-99c423d91221

ProjectSdk="Microsoft.NET.Sdk.Web">

PropertyGroup
TargetFramework>net8.0TargetFramework
able>enableable
ImplicitUsings>enableImplicitUsings
PropertyGroup

ItemGroup
PackageReferenceInclude="Microsoft.AspNetCore.OpenApi"Version="8.0.14"/>
PackageReferenceInclude="ModelContextProtocol"Version="0.1.0-preview.2" />
PackageReferenceInclude="Swashbuckle.AspNetCore"Version="6.6.2"/>
ItemGroup

Project

创建McpEndpointRouteBuilderExtensions代码实现

public staticclassMcpEndpointrouteBuilderExtensions
{
public static IEndpointConventionBuilderMapMcpSse(this IEndpointRouteBuilder endpoints)
{
IMcpServer? server = ;
SseResponseStreamTransport? transport = ;
var loggerFactory = endpoints.ServiceProvider.GetRequiredService;
var mcpServerOptions = endpoints.ServiceProvider.GetRequiredService>;

var routeGroup = endpoints.MapGroup("");

routeGroup.MapGet("/sse", async (HttpResponse response, CancellationToken requestAborted) =>
{
awaitusingvar localTransport = transport = new SseResponseStreamTransport(response.Body);
awaitusingvar localServer = server = McpServerFactory.Create(transport, mcpServerOptions.Value, loggerFactory, endpoints.ServiceProvider);

await localServer.StartAsync(RequestAborted);

response.Headers.ContentType = "text/event-stream";
response.Headers.cacheControl = "no-cache";

try
{
await transport.RunAsync(requestAborted);
}
catch (OperationCanceledException) when (requestAborted.IsCancellationRequested)
{
// RequestAborted always triggers when the client disconnects before a complete response body is written,
// but this is how SSE connections are typically closed.
}
});

routeGroup.MapPost("/message", async context =>
{
if (transport is)
{
await Results.BadRequest("Connect to the /sse endpoint before sending messages.").ExecuteAsync(context);
return;
}

var message = await context.Request.ReadFromJsonAsync(McpJsonUtilities.DefaultOptions, context.RequestAborted);
if (message is)
{
await Results.BadRequest("No message in request body.").ExecuteAsync(context);
return;
}

await transport.OnMessageReceivedAsync(message, context.RequestAborted);
context.Response.StatusCode = StatusCodes.Status202Accepted;
await context.Response.WriteAsync("Accepted");
});

return routeGroup;
}
}
/Tools/CalculateTool.cs
using System.ComponentModel;
using ModelContextProtocol.Server;

namespace MCPServer.Tools;

[McpServerToolType]
public static class CalculateTool
{
///
/// 计算加法
///
[McpServerTool("add"), Description("计算俩个数的和")]
public static async Task Add(
IMcpServer thisServer,
[Description("第一个数字")] int a,
[Description("第二个数字")] int b)
{
// 计算加法
int result = a + b;
return$"计算结果: {result}";
}
}
/Tools/SampleLlmTool.cs
///
/// This tool uses dependency injection and async method
///
[McpServerToolType]
public static class SampleLlmTool
{
[McpServerTool("sampleLLM"), Description("Samples from an LLM using MCP's sampling feature")]
public static async Task SampleLLM(

[Description("The prompt to send to the LLM")]
string prompt,
[Description("Maximum number of tokens to generate")]
int maxTokens,
CancellationToken cancellationToken)
{
ChatMessage messages =
[
new(ChatRole.System, "You are a helpful test server."),
new(ChatRole.User, prompt),
];

ChatOptions options =new
{
MaxOutputTokens = maxTokens,
Temperature = 0.7f,
};

var samplingResponse =
await thisServer.AsSamplingChatClient.GetResponseAsync(messages, options, cancellationToken);

return$"LLM sampling result: {samplingResponse}";
}
}
using MCPServer;
using ModelContextProtocol;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer;
builder.Services.AddSwaggerGen;

builder.Services.AddMcpServer.WithToolsFromAssembly;

var app = builder.Build;

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

app.MapMcpSse;

app.Run;

启动服务,然后打开您的cursor,添加你的sse服务的信息

{
"mcpServers": {
"token": {
"url": "http://localhost:5000/sse"
}
}
}

然后我们需要使用Agent模式执行函数,先通过提示词告诉它您需要通过tool帮我们计算,然后就会如图的效果,那么您的MCPServer就完成了。

来源:opendotnet

相关推荐