|
| 1 | +using AspNetCoreMcpClient; |
| 2 | +using ModelContextProtocol; |
| 3 | +using ModelContextProtocol.Client; |
| 4 | +using ModelContextProtocol.Protocol; |
| 5 | +using System.Text.Json; |
| 6 | + |
| 7 | +var builder = WebApplication.CreateBuilder(args); |
| 8 | + |
| 9 | +var endpoint = new Uri(builder.Configuration["McpServer:Endpoint"] ?? "http://localhost:3001"); |
| 10 | +var idleTimeout = TimeSpan.FromMinutes(builder.Configuration.GetValue("McpServer:IdleTimeoutMinutes", 20)); |
| 11 | + |
| 12 | +builder.Services.AddHttpClient("mcp-server"); |
| 13 | +builder.Services.AddSingleton<ElicitationBroker>(); |
| 14 | +builder.Services.AddSingleton(serviceProvider => |
| 15 | +{ |
| 16 | + var httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>(); |
| 17 | + var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>(); |
| 18 | + var elicitationBroker = serviceProvider.GetRequiredService<ElicitationBroker>(); |
| 19 | + |
| 20 | + return new SessionClientRegistry<McpClientConnection>( |
| 21 | + async (sessionId, cancellationToken) => |
| 22 | + { |
| 23 | + var httpClient = httpClientFactory.CreateClient("mcp-server"); |
| 24 | + var transport = new HttpClientTransport( |
| 25 | + new() |
| 26 | + { |
| 27 | + Endpoint = endpoint, |
| 28 | + Name = $"ASP.NET Core session {sessionId}", |
| 29 | + TransportMode = HttpTransportMode.StreamableHttp, |
| 30 | + }, |
| 31 | + httpClient, |
| 32 | + loggerFactory, |
| 33 | + ownsHttpClient: true); |
| 34 | + |
| 35 | + try |
| 36 | + { |
| 37 | + var client = await McpClient.CreateAsync( |
| 38 | + transport, |
| 39 | + new() |
| 40 | + { |
| 41 | + ClientInfo = new() { Name = "AspNetCoreMcpClient", Version = "1.0.0" }, |
| 42 | + Handlers = new() |
| 43 | + { |
| 44 | + ElicitationHandler = (request, token) => |
| 45 | + elicitationBroker.RequestAsync(sessionId, request, token), |
| 46 | + }, |
| 47 | + }, |
| 48 | + loggerFactory, |
| 49 | + cancellationToken); |
| 50 | + |
| 51 | + return new McpClientConnection(client, transport); |
| 52 | + } |
| 53 | + catch |
| 54 | + { |
| 55 | + await transport.DisposeAsync(); |
| 56 | + throw; |
| 57 | + } |
| 58 | + }, |
| 59 | + TimeProvider.System, |
| 60 | + idleTimeout); |
| 61 | +}); |
| 62 | +builder.Services.AddHostedService<McpClientCleanupService>(); |
| 63 | + |
| 64 | +var app = builder.Build(); |
| 65 | + |
| 66 | +app.MapGet("/tools", async ( |
| 67 | + HttpContext context, |
| 68 | + SessionClientRegistry<McpClientConnection> registry, |
| 69 | + CancellationToken cancellationToken) => |
| 70 | +{ |
| 71 | + var sessionId = GetDemoSessionId(context); |
| 72 | + var tools = await registry.ExecuteAsync( |
| 73 | + sessionId, |
| 74 | + async (connection, token) => await connection.Client.ListToolsAsync(cancellationToken: token), |
| 75 | + cancellationToken); |
| 76 | + |
| 77 | + return tools.Select(tool => new { tool.Name, tool.Description }); |
| 78 | +}); |
| 79 | + |
| 80 | +app.MapPost("/tools/{toolName}", async ( |
| 81 | + string toolName, |
| 82 | + JsonElement? arguments, |
| 83 | + HttpContext context, |
| 84 | + SessionClientRegistry<McpClientConnection> registry, |
| 85 | + CancellationToken cancellationToken) => |
| 86 | +{ |
| 87 | + var sessionId = GetDemoSessionId(context); |
| 88 | + var toolArguments = arguments is { ValueKind: JsonValueKind.Object } |
| 89 | + ? arguments.Value.Deserialize<Dictionary<string, object?>>() |
| 90 | + : null; |
| 91 | + |
| 92 | + var progressUpdates = new List<ProgressNotificationValue>(); |
| 93 | + var progress = new InlineProgress<ProgressNotificationValue>(value => progressUpdates.Add(value)); |
| 94 | + var result = await registry.ExecuteAsync( |
| 95 | + sessionId, |
| 96 | + async (connection, token) => await connection.Client.CallToolAsync( |
| 97 | + toolName, |
| 98 | + toolArguments, |
| 99 | + progress, |
| 100 | + cancellationToken: token), |
| 101 | + cancellationToken); |
| 102 | + |
| 103 | + return Results.Ok(new { Result = result, Progress = progressUpdates }); |
| 104 | +}); |
| 105 | + |
| 106 | +app.MapGet("/elicitation", (HttpContext context, ElicitationBroker broker) => |
| 107 | +{ |
| 108 | + var pending = broker.GetPending(GetDemoSessionId(context)); |
| 109 | + return pending is null ? Results.NoContent() : Results.Ok(pending); |
| 110 | +}); |
| 111 | + |
| 112 | +app.MapPost("/elicitation/{requestId:guid}", ( |
| 113 | + Guid requestId, |
| 114 | + ElicitResult response, |
| 115 | + HttpContext context, |
| 116 | + ElicitationBroker broker) => |
| 117 | +{ |
| 118 | + return broker.TryRespond(GetDemoSessionId(context), requestId, response) |
| 119 | + ? Results.Accepted() |
| 120 | + : Results.NotFound(); |
| 121 | +}); |
| 122 | + |
| 123 | +app.MapDelete("/session", async ( |
| 124 | + HttpContext context, |
| 125 | + SessionClientRegistry<McpClientConnection> registry, |
| 126 | + ElicitationBroker broker) => |
| 127 | +{ |
| 128 | + var sessionId = GetDemoSessionId(context); |
| 129 | + broker.Cancel(sessionId); |
| 130 | + return await registry.RemoveAsync(sessionId) ? Results.NoContent() : Results.NotFound(); |
| 131 | +}); |
| 132 | + |
| 133 | +app.Run(); |
| 134 | + |
| 135 | +static string GetDemoSessionId(HttpContext context) |
| 136 | +{ |
| 137 | + const string HeaderName = "X-Demo-User"; |
| 138 | + var sessionId = context.Request.Headers[HeaderName].ToString(); |
| 139 | + if (string.IsNullOrWhiteSpace(sessionId) || sessionId.Length > 128) |
| 140 | + { |
| 141 | + throw new BadHttpRequestException($"Provide a non-empty {HeaderName} header of at most 128 characters."); |
| 142 | + } |
| 143 | + |
| 144 | + // A production application should derive this key from authenticated server-side identity/session state. |
| 145 | + return sessionId; |
| 146 | +} |
0 commit comments