| 1 | using System.Text.Json; |
| 2 | using AgentForge.Abstractions; |
| 3 | using AgentForge.Services; |
| 4 | |
| 5 | namespace AgentForge.Endpoints; |
| 6 | |
| 7 | public static class ForgeMcpEndpoints |
| 8 | { |
| 9 | public static RouteGroupBuilder MapMcpEndpoints(this RouteGroupBuilder api) |
| 10 | { |
| 11 | api.MapPost("/mcp/invoke", InvokeTool); |
| 12 | return api; |
| 13 | } |
| 14 | |
| 15 | private static async Task<IResult> InvokeTool( |
| 16 | ForgeMcpInvokeRequest request, |
| 17 | ForgeMcpToolExecutor executor, |
| 18 | HttpContext context, |
| 19 | CancellationToken cancellationToken) |
| 20 | { |
| 21 | if (string.IsNullOrWhiteSpace(request.Tool)) |
| 22 | return Results.BadRequest(new { detail = "tool is required." }); |
| 23 | |
| 24 | var arguments = request.Arguments is null |
| 25 | ? new Dictionary<string, JsonElement>() |
| 26 | : new Dictionary<string, JsonElement>(request.Arguments, StringComparer.Ordinal); |
| 27 | |
| 28 | try |
| 29 | { |
| 30 | var response = await executor.InvokeAsync(request.Tool, arguments, context, cancellationToken) |
| 31 | .ConfigureAwait(false); |
| 32 | return Results.Json(response, statusCode: response.Success ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest); |
| 33 | } |
| 34 | catch (ArgumentException ex) |
| 35 | { |
| 36 | return Results.BadRequest(new ForgeMcpInvokeResponse { Success = false, Body = JsonSerializer.Serialize(new { detail = ex.Message }) }); |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |