MCP Tool vs Swagger–part 3–creation and usage

Now the idea is to generate from each MCP tool a swagger function.

First, we should let the user to choose what MCP to convert to Swagger. This can be done with an Attribute, MCP2OpenAPI.AddMCP2OpenApi

[McpServerToolType]
[MCP2OpenAPI.AddMCP2OpenApi]
public partial class WeatherTool
{
    [McpServerTool, Description("echoes the UTC date time in sortable format")]
    public string CurrentISODateTime()
    {
        return DateTime.UtcNow.ToString("s");
    }

Then the problem is what to generate – I decide to generate POST api in an url /api/mcp/{class}/{function}

public static void Add_CurrentISODateTime (Microsoft.AspNetCore.Routing.IEndpointRouteBuilder builder){
builder.MapPost("/api/mcp/WeatherTool/CurrentISODateTime",([Microsoft.AspNetCore.Mvc.FromServices]OA2MCP_TestMe.WeatherTool toolClass)=>
        toolClass.CurrentISODateTime()
        );
}


And a general static function to register all API :

public static void AddAll_WeatherTool(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder builder){
Add_CurrentISODateTime(builder);
Add_EchoBack(builder);
Add_Add2Numbers(builder);
Add_MyGetWeatherForCity(builder);
}


Also, this means that in the program.cs you should register the OpenAPI:

builder.Services.AddOpenApi();

builder.Services.AddMcpServer()
    .WithToolsFromAssembly()
    .WithStdioServerTransport()
    .WithHttpTransport()
    ;
//this is necessary
builder.Services.AddTransient<WeatherTool>(); 

var app = builder.Build();

    app.MapOpenApi();
    app.UseOpenAPISwaggerUI();
    app.MapMcp();
app.MapGet("/", () => "todo");
app.MapControllers();
//this is necessary
app.AddAll_WeatherTool();


You can find the code at https://github.com/ignatandrei/RSCG_OpenApi2MCP/tree/main/src/RSCG_MCP2OpenAPI and the nuget at  https://www.nuget.org/packages/RSCG_MCP2OpenAPI 


Posted

in

, , ,

by

Tags: