using System.Diagnostics; using System.Text; using System.Text.Json; using System.Threading.Channels; namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Stdio; internal sealed class McpProcess : IAsyncDisposable { public const string ServerName = "GAJ3T.MusicGen.RiffGrooveBuilder.Server"; public static string ServerDirectory => Path.Combine(AppContext.BaseDirectory, "Server"); private readonly Process _process; private readonly CancellationTokenSource _timeout = new(TimeSpan.FromSeconds(15)); private readonly Channel _responses = Channel.CreateUnbounded(); private readonly Task _stdout; private readonly Task _stderr; public McpProcess(bool independentWorkingDirectory = false, string? executablePath = null, IReadOnlyDictionary? environment = null) { var executable = executablePath ?? Path.Combine(ServerDirectory, ServerName + (OperatingSystem.IsWindows() ? ".exe" : "")); Assert.True(Path.IsPathFullyQualified(executable)); var workingDirectory = independentWorkingDirectory ? OperatingSystem.IsWindows() ? Environment.SystemDirectory : Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) : AppContext.BaseDirectory; Assert.True(File.Exists(executable), $"Server apphost was not built/copied: {executable}"); Assert.True(Directory.Exists(workingDirectory)); if (independentWorkingDirectory) { Assert.False(Path.GetFullPath(workingDirectory).StartsWith( Path.GetFullPath(AppContext.BaseDirectory), StringComparison.OrdinalIgnoreCase)); } _process = new Process { StartInfo = new ProcessStartInfo { FileName = executable, WorkingDirectory = workingDirectory, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, StandardInputEncoding = new UTF8Encoding(false), StandardOutputEncoding = new UTF8Encoding(false, true), StandardErrorEncoding = new UTF8Encoding(false, true), CreateNoWindow = true } }; if (environment is not null) foreach (var (name, value) in environment) _process.StartInfo.Environment[name] = value; Assert.True(_process.Start()); _stdout = DrainStdoutAsync(); _stderr = _process.StandardError.ReadToEndAsync(); } private async Task DrainStdoutAsync() { try { while (await _process.StandardOutput.ReadLineAsync(_timeout.Token) is { } line) { using var message = JsonDocument.Parse(line); var root = message.RootElement; Assert.Equal(JsonValueKind.Object, root.ValueKind); Assert.Equal("2.0", root.GetProperty("jsonrpc").GetString()); Assert.True(root.TryGetProperty("id", out _)); Assert.NotEqual(root.TryGetProperty("result", out _), root.TryGetProperty("error", out _)); await _responses.Writer.WriteAsync(root.Clone(), _timeout.Token); } _responses.Writer.TryComplete(); } catch (Exception exception) { _responses.Writer.TryComplete(exception); throw; } } public async Task SendAsync(string json, string delimiter = "\n") => await SendBytesAsync(Encoding.UTF8.GetBytes(json + delimiter)); public async Task SendBytesAsync(byte[] bytes) { await _process.StandardInput.BaseStream.WriteAsync(bytes, _timeout.Token); await _process.StandardInput.BaseStream.FlushAsync(_timeout.Token); } public async Task ReadAsync() => await _responses.Reader.ReadAsync(_timeout.Token); public async Task InitializeAsync() { await SendAsync(""" {"jsonrpc":"2.0","id":"init","method":"initialize","params":{"protocolVersion":"2025-11-25", "capabilities":{},"clientInfo":{"name":"generation-integration","version":"1"}}} """.ReplaceLineEndings("")); Assert.Equal("init", (await ReadAsync()).GetProperty("id").GetString()); await SendAsync("""{"jsonrpc":"2.0","method":"notifications/initialized"}"""); } public async Task CallToolAsync(string name, object arguments, int id = 1) { await SendAsync(JsonSerializer.Serialize(new { jsonrpc = "2.0", id, method = "tools/call", @params = new { name, arguments } })); var response = await ReadAsync(); Assert.Equal(id, response.GetProperty("id").GetInt32()); return response; } public async Task FinishAsync() { _process.StandardInput.Close(); await _process.WaitForExitAsync(_timeout.Token); await Task.WhenAll(_stdout, _stderr).WaitAsync(_timeout.Token); Assert.Equal(0, _process.ExitCode); return await _stderr; } public void AssertNoMoreResponses() => Assert.False(_responses.Reader.TryRead(out _), "Unexpected extra protocol response."); public async ValueTask DisposeAsync() { try { if (!_process.HasExited) { _process.Kill(entireProcessTree: true); await _process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5)); } await Task.WhenAll(_stdout, _stderr).WaitAsync(TimeSpan.FromSeconds(5)); } finally { _process.Dispose(); _timeout.Dispose(); } } }