using System.Net; using System.Net.Sockets; using System.Text; internal sealed class InteractionTestServer : IAsyncDisposable { private const string ExampleDomainPage = """ Example Domain

Example Domain

This page is for use in documentation examples without needing permission.

More information
"""; private const string ExampleTargetPage = """ Example Target

Example Target

"""; private const string InteractionPage = """ WebAccess MCP Interaction Test

Interaction Test

Ready

"""; private const string HistoryAPage = """ WebAccess MCP History A

History A

"""; private readonly TcpListener listener; private readonly CancellationTokenSource shutdown; private readonly Task serverTask; private int disposed; private int historyBLoadCount; private int searchablePageLoadCount; private InteractionTestServer(TcpListener listener, CancellationToken cancellationToken) { this.listener = listener; shutdown = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var endpoint = (IPEndPoint)listener.LocalEndpoint; var baseUrl = $"http://127.0.0.1:{endpoint.Port}"; InteractionUrl = new Uri($"{baseUrl}/"); ExampleDomainUrl = new Uri($"{baseUrl}/example-domain"); RedirectToExampleDomainUrl = new Uri($"{baseUrl}/redirect-example-domain"); ExampleTargetUrl = new Uri($"{baseUrl}/example-target"); LongTextUrl = new Uri($"{baseUrl}/long-text"); SearchablePageUrl = new Uri($"{baseUrl}/searchable-page"); HistoryAUrl = new Uri($"{baseUrl}/history-a"); HistoryBUrl = new Uri($"{baseUrl}/history-b"); serverTask = RunAsync(shutdown.Token); } public Uri InteractionUrl { get; } public Uri ExampleDomainUrl { get; } public Uri RedirectToExampleDomainUrl { get; } public Uri ExampleTargetUrl { get; } public Uri LongTextUrl { get; } public Uri SearchablePageUrl { get; } public int SearchablePageLoadCount => Volatile.Read(ref searchablePageLoadCount); public Uri HistoryAUrl { get; } public Uri HistoryBUrl { get; } public static InteractionTestServer Start(CancellationToken cancellationToken) { var listener = new TcpListener(IPAddress.Loopback, 0); try { listener.Start(); return new InteractionTestServer(listener, cancellationToken); } catch { listener.Stop(); throw; } } public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref disposed, 1) != 0) { return; } shutdown.Cancel(); listener.Stop(); try { await serverTask; } catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { } catch (SocketException) when (shutdown.IsCancellationRequested) { } finally { shutdown.Dispose(); } } private async Task RunAsync(CancellationToken cancellationToken) { var clientTasks = new List(); try { while (!cancellationToken.IsCancellationRequested) { var client = await listener.AcceptTcpClientAsync(cancellationToken); clientTasks.Add(HandleClientSafelyAsync(client, cancellationToken)); } } finally { await Task.WhenAll(clientTasks); } } private async Task HandleClientSafelyAsync( TcpClient client, CancellationToken cancellationToken) { using (client) { try { await HandleClientAsync(client, cancellationToken); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { } catch (IOException exception) { if (!cancellationToken.IsCancellationRequested) { Console.Error.WriteLine( $"[Interaction fixture] Client connection ended before the response completed: {exception.Message}"); } } catch (SocketException exception) { if (!cancellationToken.IsCancellationRequested) { Console.Error.WriteLine( $"[Interaction fixture] Client connection failed: {exception.Message}"); } } } } private async Task HandleClientAsync( TcpClient client, CancellationToken cancellationToken) { await using var stream = client.GetStream(); using var reader = new StreamReader( stream, Encoding.ASCII, detectEncodingFromByteOrderMarks: false, leaveOpen: true); var requestLine = await reader.ReadLineAsync(cancellationToken); if (requestLine is null) { return; } string? headerLine; do { headerLine = await reader.ReadLineAsync(cancellationToken); } while (!string.IsNullOrEmpty(headerLine)); var requestParts = requestLine.Split(' ', StringSplitOptions.RemoveEmptyEntries); var method = requestParts.ElementAtOrDefault(0); var path = requestParts.ElementAtOrDefault(1); var supportedMethod = method == "GET" || method == "HEAD"; if (supportedMethod && path == "/redirect-example-domain") { var redirectHeaders = Encoding.ASCII.GetBytes( "HTTP/1.1 302 Found\r\n" + "Location: /example-domain\r\n" + "Content-Length: 0\r\n" + "Cache-Control: no-store\r\n" + "Connection: close\r\n" + "\r\n"); await stream.WriteAsync(redirectHeaders, cancellationToken); return; } string? page = supportedMethod ? path switch { "/" => InteractionPage, "/example-domain" => ExampleDomainPage, "/example-target" => ExampleTargetPage, "/long-text" => CreateLongTextPage(), "/searchable-page" => CreateSearchablePage( method == "GET" ? Interlocked.Increment(ref searchablePageLoadCount) : Volatile.Read(ref searchablePageLoadCount)), "/history-a" => HistoryAPage, "/history-b" => CreateHistoryBPage( method == "GET" ? Interlocked.Increment(ref historyBLoadCount) : Volatile.Read(ref historyBLoadCount)), _ => null } : null; var status = page is not null ? "200 OK" : "404 Not Found"; var entity = page is not null ? Encoding.UTF8.GetBytes(page) : []; var body = method == "HEAD" ? [] : entity; var headers = Encoding.ASCII.GetBytes( $"HTTP/1.1 {status}\r\n" + "Content-Type: text/html; charset=utf-8\r\n" + $"Content-Length: {entity.Length}\r\n" + "Cache-Control: no-store\r\n" + "Connection: close\r\n" + "\r\n"); await stream.WriteAsync(headers, cancellationToken); if (body.Length > 0) { await stream.WriteAsync(body, cancellationToken); } } private static string CreateHistoryBPage(int loadCount) => $$""" WebAccess MCP History B

History B

History B Load: {{loadCount}}

"""; private static string CreateLongTextPage() => $""" WebAccess MCP Long Text {new string('A', 60_000)} """; private static string CreateSearchablePage(int loadCount) => $""" WebAccess MCP Searchable Page {CreateSearchableText(loadCount)} """; private static string CreateSearchableText(int loadCount) { const string firstHalf = "request throttling "; var prefix = new string('x', 4_000 - firstHalf.Length); var usefulText = $"behavior continues across the storage boundary. " + "Rate limiting enforces a request quota and a concurrency limit. " + $"Searchable Page Load: {loadCount}."; var suffix = new string('y', 4_000 - usefulText.Length); return prefix + firstHalf + usefulText + suffix; } }