|
| 1 | +using Microsoft.AspNetCore.Builder; |
| 2 | +using Microsoft.AspNetCore.Hosting; |
| 3 | +using Microsoft.AspNetCore.Http; |
| 4 | +using Microsoft.Extensions.Configuration; |
| 5 | +using Microsoft.Extensions.DependencyInjection; |
| 6 | +using Microsoft.Extensions.Hosting; |
| 7 | +using ModelContextProtocol.AspNetCore; |
| 8 | +using ModelContextProtocol.Server; |
| 9 | + |
| 10 | +namespace BlazorExpress.ChartJS.MCP; |
| 11 | + |
| 12 | +public static class McpApplication |
| 13 | +{ |
| 14 | + public const string DefaultHttpUrl = "http://localhost:5000"; |
| 15 | + public const string McpPath = "/mcp"; |
| 16 | + public const string HealthPath = "/health"; |
| 17 | + public const string TokenConfigurationKey = "CHARTJS_MCP_TOKEN"; |
| 18 | + |
| 19 | + public static Task RunAsync(string[] args, CancellationToken cancellationToken = default) |
| 20 | + { |
| 21 | + var options = ParseOptions(args); |
| 22 | + |
| 23 | + return options.Transport == McpTransportMode.Stdio |
| 24 | + ? RunStdioAsync(options.RemainingArgs, cancellationToken) |
| 25 | + : RunHttpAsync(options.RemainingArgs, cancellationToken); |
| 26 | + } |
| 27 | + |
| 28 | + public static McpHostOptions ParseOptions(IReadOnlyList<string> args) |
| 29 | + { |
| 30 | + var transport = McpTransportMode.Http; |
| 31 | + var remainingArgs = new List<string>(); |
| 32 | + |
| 33 | + for (var i = 0; i < args.Count; i++) |
| 34 | + { |
| 35 | + var arg = args[i]; |
| 36 | + |
| 37 | + if (string.Equals(arg, "--stdio", StringComparison.OrdinalIgnoreCase)) |
| 38 | + { |
| 39 | + transport = McpTransportMode.Stdio; |
| 40 | + continue; |
| 41 | + } |
| 42 | + |
| 43 | + if (string.Equals(arg, "--http", StringComparison.OrdinalIgnoreCase)) |
| 44 | + { |
| 45 | + transport = McpTransportMode.Http; |
| 46 | + continue; |
| 47 | + } |
| 48 | + |
| 49 | + if (string.Equals(arg, "--transport", StringComparison.OrdinalIgnoreCase)) |
| 50 | + { |
| 51 | + if (i + 1 >= args.Count) |
| 52 | + throw new ArgumentException("Missing value for --transport. Use 'http' or 'stdio'."); |
| 53 | + |
| 54 | + transport = ParseTransport(args[++i]); |
| 55 | + continue; |
| 56 | + } |
| 57 | + |
| 58 | + if (arg.StartsWith("--transport=", StringComparison.OrdinalIgnoreCase)) |
| 59 | + { |
| 60 | + transport = ParseTransport(arg["--transport=".Length..]); |
| 61 | + continue; |
| 62 | + } |
| 63 | + |
| 64 | + remainingArgs.Add(arg); |
| 65 | + } |
| 66 | + |
| 67 | + return new McpHostOptions(transport, remainingArgs.ToArray()); |
| 68 | + } |
| 69 | + |
| 70 | + public static WebApplication CreateHttpApp( |
| 71 | + string[] args, |
| 72 | + string? environmentName = null, |
| 73 | + Action<IWebHostBuilder>? configureWebHost = null, |
| 74 | + IEnumerable<KeyValuePair<string, string?>>? configuration = null) |
| 75 | + { |
| 76 | + var builder = WebApplication.CreateBuilder(new WebApplicationOptions |
| 77 | + { |
| 78 | + Args = args, |
| 79 | + EnvironmentName = environmentName, |
| 80 | + }); |
| 81 | + |
| 82 | + if (configuration is not null) |
| 83 | + builder.Configuration.AddInMemoryCollection(configuration); |
| 84 | + |
| 85 | + var useDefaultHttpUrl = !HasUrlOverride(args); |
| 86 | + |
| 87 | + configureWebHost?.Invoke(builder.WebHost); |
| 88 | + |
| 89 | + RegisterCoreServices(builder.Services); |
| 90 | + builder.Services |
| 91 | + .AddMcpServer() |
| 92 | + .WithHttpTransport(options => |
| 93 | + { |
| 94 | + options.Stateless = true; |
| 95 | + }) |
| 96 | + .AddAuthorizationFilters() |
| 97 | + .WithToolsFromAssembly(); |
| 98 | + |
| 99 | + var token = builder.Configuration[TokenConfigurationKey]; |
| 100 | + if (!builder.Environment.IsDevelopment() && string.IsNullOrWhiteSpace(token)) |
| 101 | + throw new InvalidOperationException($"{TokenConfigurationKey} must be configured when HTTP MCP is running outside Development."); |
| 102 | + |
| 103 | + var app = builder.Build(); |
| 104 | + |
| 105 | + if (useDefaultHttpUrl) |
| 106 | + app.Urls.Add(DefaultHttpUrl); |
| 107 | + |
| 108 | + app.MapGet(HealthPath, () => Results.Ok(new { status = "healthy" })); |
| 109 | + |
| 110 | + if (!app.Environment.IsDevelopment()) |
| 111 | + app.UseBearerTokenProtection(token!); |
| 112 | + |
| 113 | + app.MapMcp(McpPath); |
| 114 | + |
| 115 | + return app; |
| 116 | + } |
| 117 | + |
| 118 | + private static async Task RunHttpAsync(string[] args, CancellationToken cancellationToken) |
| 119 | + { |
| 120 | + var app = CreateHttpApp(args); |
| 121 | + await app.RunAsync(cancellationToken); |
| 122 | + } |
| 123 | + |
| 124 | + private static async Task RunStdioAsync(string[] args, CancellationToken cancellationToken) |
| 125 | + { |
| 126 | + var builder = Host.CreateEmptyApplicationBuilder(new HostApplicationBuilderSettings { Args = args }); |
| 127 | + |
| 128 | + RegisterCoreServices(builder.Services); |
| 129 | + builder.Services |
| 130 | + .AddMcpServer() |
| 131 | + .WithStdioServerTransport() |
| 132 | + .WithToolsFromAssembly(); |
| 133 | + |
| 134 | + await builder.Build().RunAsync(cancellationToken); |
| 135 | + } |
| 136 | + |
| 137 | + private static void RegisterCoreServices(IServiceCollection services) |
| 138 | + { |
| 139 | + services |
| 140 | + .AddSingleton<ChartExampleGenerator>() |
| 141 | + .AddSingleton<ProjectIntegrationService>(); |
| 142 | + } |
| 143 | + |
| 144 | + private static McpTransportMode ParseTransport(string value) => |
| 145 | + value.ToLowerInvariant() switch |
| 146 | + { |
| 147 | + "http" => McpTransportMode.Http, |
| 148 | + "stdio" => McpTransportMode.Stdio, |
| 149 | + _ => throw new ArgumentException($"Unsupported MCP transport '{value}'. Use 'http' or 'stdio'."), |
| 150 | + }; |
| 151 | + |
| 152 | + private static bool HasUrlOverride(IEnumerable<string> args) => |
| 153 | + args.Any(arg => |
| 154 | + string.Equals(arg, "--urls", StringComparison.OrdinalIgnoreCase) |
| 155 | + || arg.StartsWith("--urls=", StringComparison.OrdinalIgnoreCase)) |
| 156 | + || !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ASPNETCORE_URLS")); |
| 157 | +} |
| 158 | + |
| 159 | +internal static class McpApplicationBuilderExtensions |
| 160 | +{ |
| 161 | + public static IApplicationBuilder UseBearerTokenProtection(this IApplicationBuilder app, string token) => |
| 162 | + app.Use(async (context, next) => |
| 163 | + { |
| 164 | + if (!context.Request.Path.StartsWithSegments(McpApplication.McpPath)) |
| 165 | + { |
| 166 | + await next(context); |
| 167 | + return; |
| 168 | + } |
| 169 | + |
| 170 | + var expectedHeader = $"Bearer {token}"; |
| 171 | + var actualHeader = context.Request.Headers.Authorization.ToString(); |
| 172 | + |
| 173 | + if (!string.Equals(actualHeader, expectedHeader, StringComparison.Ordinal)) |
| 174 | + { |
| 175 | + context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
| 176 | + return; |
| 177 | + } |
| 178 | + |
| 179 | + await next(context); |
| 180 | + }); |
| 181 | +} |
| 182 | + |
| 183 | +public sealed record McpHostOptions(McpTransportMode Transport, string[] RemainingArgs); |
| 184 | + |
| 185 | +public enum McpTransportMode |
| 186 | +{ |
| 187 | + Http, |
| 188 | + Stdio, |
| 189 | +} |
0 commit comments