| 1 | using System.Text.Json; |
| 2 | using AgentForge.Abstractions; |
| 3 | using Microsoft.Extensions.DependencyInjection; |
| 4 | |
| 5 | namespace AgentForge.Mcp.Core; |
| 6 | |
| 7 | public static class ForgeMcpHttpTools |
| 8 | { |
| 9 | public static void Add( |
| 10 | ForgeMcpToolRegistry registry, |
| 11 | ForgeMcpToolDescriptor descriptor, |
| 12 | Func<ForgeApiClient, IReadOnlyDictionary<string, JsonElement>, CancellationToken, Task<ApiResult>> invoke) |
| 13 | { |
| 14 | registry.Add(descriptor, (context, args, cancellationToken) => |
| 15 | InvokeAsync(context, args, cancellationToken, invoke)); |
| 16 | } |
| 17 | |
| 18 | public static async Task<ForgeMcpInvokeResponse> InvokeAsync( |
| 19 | ForgeMcpToolInvocationContext context, |
| 20 | IReadOnlyDictionary<string, JsonElement> arguments, |
| 21 | CancellationToken cancellationToken, |
| 22 | Func<ForgeApiClient, IReadOnlyDictionary<string, JsonElement>, CancellationToken, Task<ApiResult>> invoke) |
| 23 | { |
| 24 | try |
| 25 | { |
| 26 | var clientSource = context.RequestServices.GetRequiredService<IForgeMcpHttpClientSource>(); |
| 27 | using var http = clientSource.CreateClient(context.HttpContext); |
| 28 | var apiClient = new ForgeApiClient(http); |
| 29 | var result = await invoke(apiClient, arguments, cancellationToken).ConfigureAwait(false); |
| 30 | return new ForgeMcpInvokeResponse { Success = result.IsSuccess, Body = result.Body }; |
| 31 | } |
| 32 | catch (ArgumentException ex) |
| 33 | { |
| 34 | return new ForgeMcpInvokeResponse { Success = false, Body = ex.Message }; |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |