webaccess-mcp/src/WebAccess.MCP.TestRig/InteractionTestServer.cs

363 lines
11 KiB
C#

using System.Net;
using System.Net.Sockets;
using System.Text;
internal sealed class InteractionTestServer : IAsyncDisposable
{
private const string ExampleDomainPage =
"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Deterministic Example Domain page for browser validation.">
<meta property="og:site_name" content="WebAccess.MCP TestRig">
<title>Example Domain</title>
</head>
<body>
<main>
<h1>Example Domain</h1>
<p>This page is for use in documentation examples without needing permission.</p>
<a href="/example-target">More information</a>
</main>
</body>
</html>
""";
private const string ExampleTargetPage =
"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example Target</title>
</head>
<body>
<main>
<h1>Example Target</h1>
</main>
</body>
</html>
""";
private const string InteractionPage =
"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebAccess MCP Interaction Test</title>
</head>
<body>
<main>
<h1>Interaction Test</h1>
<label for="name">Name</label>
<input id="name" name="name" placeholder="Type your name">
<button type="button" id="apply">Apply</button>
<p id="status">Ready</p>
</main>
<script>
const nameInput = document.getElementById('name');
const status = document.getElementById('status');
nameInput.addEventListener('keydown', event => {
if (event.key === 'Enter') {
status.textContent = `Submitted: ${nameInput.value}`;
}
});
document.getElementById('apply').addEventListener('click', () => {
status.textContent = `Clicked: ${nameInput.value}`;
});
</script>
</body>
</html>
""";
private const string HistoryAPage =
"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebAccess MCP History A</title>
</head>
<body>
<main>
<h1>History A</h1>
</main>
</body>
</html>
""";
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<Task>();
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) =>
$$"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebAccess MCP History B</title>
</head>
<body>
<main>
<h1>History B</h1>
<p>History B Load: {{loadCount}}</p>
</main>
</body>
</html>
""";
private static string CreateLongTextPage() =>
$"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebAccess MCP Long Text</title>
</head>
<body>{new string('A', 60_000)}</body>
</html>
""";
private static string CreateSearchablePage(int loadCount) =>
$"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebAccess MCP Searchable Page</title>
</head>
<body>
<span>{CreateSearchableText(loadCount)}</span>
</body>
</html>
""";
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;
}
}