|
| 1 | +using System.Net; |
| 2 | +using System.Security.Cryptography; |
| 3 | +using System.Text; |
| 4 | +using Microsoft.AspNetCore.Builder; |
| 5 | +using Microsoft.AspNetCore.Http; |
| 6 | +using Microsoft.Extensions.DependencyInjection; |
| 7 | +using Microsoft.Extensions.Hosting; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using Motus.Mcp; |
| 10 | + |
| 11 | +namespace Motus.Mcp.Http; |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// Hosts the Motus MCP server over Streamable HTTP for concurrent remote clients. Each connected |
| 15 | +/// client (MCP session) gets its own isolated browser, contexts, and tabs; the tool set is the same |
| 16 | +/// one the stdio host serves. |
| 17 | +/// </summary> |
| 18 | +public static class McpHttpServerHost |
| 19 | +{ |
| 20 | + /// <summary> |
| 21 | + /// Builds and runs the HTTP host until the token is cancelled or the process is stopped. |
| 22 | + /// </summary> |
| 23 | + public static async Task StartAsync(McpHttpServerOptions options, CancellationToken cancellationToken = default) |
| 24 | + { |
| 25 | + ArgumentNullException.ThrowIfNull(options); |
| 26 | + |
| 27 | + var (app, registry) = Build(options); |
| 28 | + try |
| 29 | + { |
| 30 | + await app.RunAsync(cancellationToken).ConfigureAwait(false); |
| 31 | + } |
| 32 | + finally |
| 33 | + { |
| 34 | + await registry.DisposeAsync().ConfigureAwait(false); |
| 35 | + await app.DisposeAsync().ConfigureAwait(false); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + /// <summary> |
| 40 | + /// Builds the web application and its session registry without running it. The registry is |
| 41 | + /// returned so the caller can dispose it on shutdown (the host registers it as an external |
| 42 | + /// instance, which the DI container does not own). Exposed for tests that drive the host on a |
| 43 | + /// chosen port and read back the bound address. |
| 44 | + /// </summary> |
| 45 | + internal static (WebApplication App, McpSessionRegistry Registry) Build(McpHttpServerOptions options) |
| 46 | + { |
| 47 | + ArgumentNullException.ThrowIfNull(options); |
| 48 | + |
| 49 | + if (!IsLoopback(options.Host) && string.IsNullOrEmpty(options.Token)) |
| 50 | + { |
| 51 | + throw new InvalidOperationException( |
| 52 | + $"Refusing to bind non-loopback host '{options.Host}' without an authentication token. " |
| 53 | + + "Pass a token or bind a loopback address (127.0.0.1)."); |
| 54 | + } |
| 55 | + |
| 56 | + var builder = WebApplication.CreateBuilder(); |
| 57 | + |
| 58 | + // Keep the web host quiet on stdout; only warnings and errors surface unless the operator |
| 59 | + // raises the level. There is no JSON-RPC-over-stdout concern here (that is the stdio host), |
| 60 | + // but a chatty server is noise in a CLI session. |
| 61 | + builder.Logging.ClearProviders(); |
| 62 | + builder.Logging.AddConsole(); |
| 63 | + builder.Logging.SetMinimumLevel(LogLevel.Warning); |
| 64 | + |
| 65 | + builder.WebHost.UseUrls($"http://{options.Host}:{options.Port}"); |
| 66 | + |
| 67 | + // The registry is created here so the per-session handler (a closure) and the per-session |
| 68 | + // tool service factories can share it. It is registered as an external instance and disposed |
| 69 | + // by the host, not the container. |
| 70 | + var registry = new McpSessionRegistry(); |
| 71 | + builder.Services.AddSingleton(registry); |
| 72 | + |
| 73 | + // The tools resolve these four services by type. Each call returns the bundle for the |
| 74 | + // session the call belongs to, so concurrent clients never see each other's browser. The |
| 75 | + // bundle owns the instances' lifetimes, so none of these is disposed by the per-call scope. |
| 76 | + builder.Services.AddTransient(_ => registry.RequireCurrent().Pages); |
| 77 | + builder.Services.AddTransient(_ => registry.RequireCurrent().Dialogs); |
| 78 | + builder.Services.AddTransient(_ => registry.RequireCurrent().Console); |
| 79 | + builder.Services.AddTransient(_ => registry.RequireCurrent().Network); |
| 80 | + |
| 81 | + var launchOptions = options.LaunchOptions; |
| 82 | + |
| 83 | + var mcpBuilder = builder.Services |
| 84 | + .AddMcpServer(McpServerConfiguration.ConfigureServerOptions) |
| 85 | + .WithHttpTransport(transport => |
| 86 | + { |
| 87 | + transport.IdleTimeout = options.IdleTimeout; |
| 88 | + |
| 89 | + // Run every tool call of a session on the session's execution context, so the |
| 90 | + // ambient bundle set below flows into the tool service factories. |
| 91 | + transport.PerSessionExecutionContext = true; |
| 92 | + |
| 93 | + // One bundle per session: created when the session starts, made current on this |
| 94 | + // execution context, and disposed (browser torn down) when the session ends. |
| 95 | + transport.RunSessionHandler = async (httpContext, server, sessionToken) => |
| 96 | + { |
| 97 | + var sessionId = server.SessionId |
| 98 | + ?? throw new InvalidOperationException("A stateful HTTP session has no session id."); |
| 99 | + var loggerFactory = httpContext.RequestServices.GetService<ILoggerFactory>(); |
| 100 | + var bundle = new McpSessionBundle(launchOptions, loggerFactory); |
| 101 | + registry.Register(sessionId, bundle); |
| 102 | + try |
| 103 | + { |
| 104 | + await server.RunAsync(sessionToken).ConfigureAwait(false); |
| 105 | + } |
| 106 | + finally |
| 107 | + { |
| 108 | + await registry.RemoveAsync(sessionId).ConfigureAwait(false); |
| 109 | + } |
| 110 | + }; |
| 111 | + }); |
| 112 | + mcpBuilder.AddMotusTools(); |
| 113 | + |
| 114 | + var app = builder.Build(); |
| 115 | + |
| 116 | + // Gate the endpoint on the bearer token when one is configured. Done as terminal middleware |
| 117 | + // rather than a full authentication scheme to keep the dependency surface minimal for v1. |
| 118 | + if (!string.IsNullOrEmpty(options.Token)) |
| 119 | + { |
| 120 | + var expected = Encoding.UTF8.GetBytes($"Bearer {options.Token}"); |
| 121 | + app.Use(async (context, next) => |
| 122 | + { |
| 123 | + var presented = Encoding.UTF8.GetBytes(context.Request.Headers.Authorization.ToString()); |
| 124 | + if (!CryptographicOperations.FixedTimeEquals(presented, expected)) |
| 125 | + { |
| 126 | + context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
| 127 | + context.Response.Headers.WWWAuthenticate = "Bearer"; |
| 128 | + return; |
| 129 | + } |
| 130 | + |
| 131 | + await next().ConfigureAwait(false); |
| 132 | + }); |
| 133 | + } |
| 134 | + |
| 135 | + app.MapMcp(); |
| 136 | + |
| 137 | + return (app, registry); |
| 138 | + } |
| 139 | + |
| 140 | + /// <summary> |
| 141 | + /// Starts the host on its configured (or OS-assigned, when the port is 0) address and returns a |
| 142 | + /// handle exposing the bound base address and the session registry. For tests that drive the |
| 143 | + /// running server with a real MCP client. |
| 144 | + /// </summary> |
| 145 | + internal static async Task<RunningServer> StartForTestingAsync( |
| 146 | + McpHttpServerOptions options, |
| 147 | + CancellationToken cancellationToken = default) |
| 148 | + { |
| 149 | + var (app, registry) = Build(options); |
| 150 | + await app.StartAsync(cancellationToken).ConfigureAwait(false); |
| 151 | + var baseAddress = new Uri(app.Urls.First(), UriKind.Absolute); |
| 152 | + return new RunningServer(app, registry, baseAddress); |
| 153 | + } |
| 154 | + |
| 155 | + /// <summary>A running HTTP host handle for tests: the bound address, the registry, and teardown.</summary> |
| 156 | + internal sealed class RunningServer : IAsyncDisposable |
| 157 | + { |
| 158 | + private readonly WebApplication _app; |
| 159 | + |
| 160 | + internal RunningServer(WebApplication app, McpSessionRegistry registry, Uri baseAddress) |
| 161 | + { |
| 162 | + _app = app; |
| 163 | + Registry = registry; |
| 164 | + BaseAddress = baseAddress; |
| 165 | + } |
| 166 | + |
| 167 | + /// <summary>The base address the server is listening on.</summary> |
| 168 | + public Uri BaseAddress { get; } |
| 169 | + |
| 170 | + /// <summary>The live session registry, so tests can assert per-session lifecycle.</summary> |
| 171 | + public McpSessionRegistry Registry { get; } |
| 172 | + |
| 173 | + public async ValueTask DisposeAsync() |
| 174 | + { |
| 175 | + await _app.StopAsync().ConfigureAwait(false); |
| 176 | + await Registry.DisposeAsync().ConfigureAwait(false); |
| 177 | + await _app.DisposeAsync().ConfigureAwait(false); |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + private static bool IsLoopback(string host) |
| 182 | + { |
| 183 | + if (string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase)) |
| 184 | + { |
| 185 | + return true; |
| 186 | + } |
| 187 | + |
| 188 | + return IPAddress.TryParse(host, out var address) && IPAddress.IsLoopback(address); |
| 189 | + } |
| 190 | +} |
0 commit comments