Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/nuget.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,15 @@ jobs:
dotnet-version: "10.0.x"

- name: Test with dotnet
if: matrix.os == 'ubuntu-latest'
working-directory: ./src
run: dotnet test --configuration Release

- name: Test with dotnet (without SingleStepTest)
if: matrix.os != 'ubuntu-latest'
working-directory: ./src
run: dotnet test --configuration Release -- --filter-not-class '*SingleStepTest*'

- name: Package NuGet
working-directory: ./src
run: dotnet pack --include-symbols --include-source --configuration Release -p:NoWarn=NU5104
Expand Down
70 changes: 27 additions & 43 deletions src/Spice86.Core/Emulator/Mcp/McpHttpHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
Expand All @@ -11,20 +13,20 @@

using Spice86.Mcp;

using System.Linq;
using System.Reflection;
using System.Threading;

using ILogger = Microsoft.Extensions.Logging.ILogger;

internal sealed class McpHttpHost : IAsyncDisposable {
private static readonly TimeSpan ShutdownJoinTimeout = TimeSpan.FromSeconds(5);
private WebApplication? _app;
private Thread? _serverThread;
private readonly ILogger _loggerService;
private Logger? _mcpFileLogger;
private readonly ManualResetEvent _shutdownRequested = new(false);
private bool _disposed;

/// <summary>Gets the actual TCP port the server is listening on after startup.</summary>
public int Port { get; private set; }

public McpHttpHost(ILogger loggerService) {
_loggerService = loggerService;
}
Expand Down Expand Up @@ -72,7 +74,7 @@
}
}

builder.WebHost.UseUrls($"http://localhost:{port}");
builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
_app = builder.Build();
_app.MapGet("/health", () => Results.Json(new {
status = "ok",
Expand All @@ -91,49 +93,37 @@
await context.Response.Body.FlushAsync();
});

_serverThread = new Thread(RunServerLoop) {
Name = "McpHttpHost",
IsBackground = true
};
_serverThread.Start();
_loggerService.LogInformation("MCP HTTP server started on http://localhost:{Port}/mcp", port);
}

private void RunServerLoop() {
if (_app == null) {
return;
}

try {
_app.StartAsync().GetAwaiter().GetResult();
_loggerService.LogInformation("MCP HTTP server is now listening");
} catch (ObjectDisposedException) {
// Host disposed while thread was exiting.
return;
} catch (Exception ex) {
_loggerService.LogError(ex, "MCP HTTP server crashed");
return;
} catch {
_app.DisposeAsync().AsTask().GetAwaiter().GetResult();
_app = null;
throw;
}

IServerAddressesFeature? addressesFeature = _app.Services
.GetService<IServer>()
?.Features.Get<IServerAddressesFeature>();
string? boundAddress = addressesFeature?.Addresses.FirstOrDefault();
if (boundAddress is not null && Uri.TryCreate(boundAddress, UriKind.Absolute, out Uri? uri)) {
Port = uri.Port;
} else {
Port = port;
}

Check notice

Code scanning / CodeQL

Missed ternary opportunity Note

Both branches of this 'if' statement write to the same variable - consider using '?' to express intent better.

// Keep this thread alive until the host is asked to stop. Using _app.Run()
// here caused premature shutdown on background threads because
// ConsoleLifetime has no console to watch on a non-main thread.
_shutdownRequested.WaitOne();
_loggerService.LogInformation("MCP HTTP server started on http://127.0.0.1:{Port}/mcp", Port);
}

public void Stop() {
if (_disposed) {
return;
}
_disposed = true;
_shutdownRequested.Set();
_app?.Lifetime.StopApplication();
if (_serverThread is { IsAlive: true }) {
_serverThread.Join(ShutdownJoinTimeout);
if (_app != null) {
_app.StopAsync().GetAwaiter().GetResult();
_app.DisposeAsync().AsTask().GetAwaiter().GetResult();
_app = null;
}
_app = null;
_serverThread = null;
_shutdownRequested.Dispose();
_mcpFileLogger?.Dispose();
_mcpFileLogger = null;
}
Expand All @@ -143,17 +133,11 @@
return;
}
_disposed = true;
_shutdownRequested.Set();
if (_app != null) {
_app.Lifetime.StopApplication();
if (_serverThread is { IsAlive: true }) {
_serverThread.Join(ShutdownJoinTimeout);
}
await _app.StopAsync();
await _app.DisposeAsync();
_app = null;
_serverThread = null;
}
_shutdownRequested.Dispose();
_mcpFileLogger?.Dispose();
_mcpFileLogger = null;
GC.SuppressFinalize(this);
Expand Down
4 changes: 2 additions & 2 deletions src/Spice86/Spice86DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -794,9 +794,9 @@ internal Spice86DependencyInjection(Configuration configuration, MainWindow? mai
try {
mcpHttpTransport.Start(emulatorMcpServices, configuration.McpHttpPort, additionalToolAssemblies, additionalMcpServices);
if (loggerService.IsEnabled(LogLevel.Information)) {
loggerService.LogInformation("MCP HTTP transport started on port {Port}", configuration.McpHttpPort);
loggerService.LogInformation("MCP HTTP transport started on port {Port}", mcpHttpTransport.Port);
}
} catch (InvalidOperationException ex) {
} catch (Exception ex) when (ex is InvalidOperationException or IOException) {
loggerService.LogWarning(ex, "Failed to configure MCP HTTP transport on port {Port}; MCP HTTP will be unavailable", configuration.McpHttpPort);
mcpHttpTransport.Stop();
mcpHttpTransport = null;
Expand Down
29 changes: 29 additions & 0 deletions tests/Spice86.Tests/McpHttpHostTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
namespace Spice86.Tests;

using FluentAssertions;

using Spice86.Core.Emulator.Mcp;

using System.IO;
using System.Net;
using System.Net.Sockets;

using Xunit;

public class McpHttpHostTest {
[Fact]
public void Start_ThrowsIOException_WhenPortIsOccupied() {
using Spice86Creator creator = new("add");
using Spice86DependencyInjection spice86 = creator.Create();
EmulatorMcpServices services = spice86.McpServices;
using TcpListener listener = new(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;

McpHttpHost host = new(services.LoggerService);
Action act = () => host.Start(services, port);

act.Should().Throw<IOException>();
host.Stop();
}
}
43 changes: 6 additions & 37 deletions tests/Spice86.Tests/McpIntegrationContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ namespace Spice86.Tests;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Threading;
Expand Down Expand Up @@ -90,7 +89,7 @@ public static async Task<McpIntegrationContext> CreateAsync(
return await CreateAsync(testProgramName, enableXms, enableEms, initializeDos, SbType.None, OplMode.None);
}

public static async Task<McpIntegrationContext> CreateAsync(
public static Task<McpIntegrationContext> CreateAsync(
string testProgramName,
bool enableXms,
bool enableEms,
Expand Down Expand Up @@ -147,18 +146,15 @@ public static async Task<McpIntegrationContext> CreateAsync(
services.BiosKeyboardBuffer = spice86.McpServices.BiosKeyboardBuffer;
services.Dos = spice86.McpServices.Dos;

int port = GetFreeTcpPort();
McpHttpHost host = new(services.LoggerService);
host.Start(services, port);
host.Start(services, 0);
int port = host.Port;

HttpClient httpClient = new();
Uri baseEndpoint = new($"http://localhost:{port}/");
Uri endpoint = new($"http://localhost:{port}/mcp");

McpIntegrationContext context = new(creator, spice86, services, host, httpClient, baseEndpoint, endpoint);
Uri baseEndpoint = new($"http://127.0.0.1:{port}/");
Uri endpoint = new($"http://127.0.0.1:{port}/mcp");

await WaitForPortAsync(port);
return context;
return Task.FromResult(new McpIntegrationContext(creator, spice86, services, host, httpClient, baseEndpoint, endpoint));
}

public async Task<JsonDocument> InitializeAsync() {
Expand Down Expand Up @@ -345,31 +341,4 @@ private static string ExtractLastSseJsonPayload(string body) {

return jsonCandidates[jsonCandidates.Count - 1];
}

private static int GetFreeTcpPort() {
using TcpListener listener = new(System.Net.IPAddress.Loopback, 0);
listener.Start();
try {
System.Net.IPEndPoint localEndpoint = (System.Net.IPEndPoint)listener.LocalEndpoint;
return localEndpoint.Port;
} finally {
listener.Stop();
}
}

private static async Task WaitForPortAsync(int port) {
const int maxAttempts = 40;

for (int attempt = 0; attempt < maxAttempts; attempt++) {
using TcpClient client = new();
try {
await client.ConnectAsync("127.0.0.1", port);
return;
} catch (SocketException) {
await Task.Delay(10);
}
}

throw new InvalidOperationException($"MCP host did not open port {port} in time.");
}
}
Loading