< Summary

Information
Class: ToolCore.McpHost.McpHostSupervisor
Assembly: ToolCore
File(s): /home/runner/work/InvAit/InvAit/ToolCore/McpHost/McpHostSupervisor.cs
Tag: 194_44631168438
Line coverage
79%
Covered lines: 290
Uncovered lines: 77
Coverable lines: 367
Total lines: 636
Line coverage: 79%
Branch coverage
66%
Covered branches: 108
Total branches: 162
Branch coverage: 66.6%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)50%8891.66%
get_IsConnected()75%44100%
EnsureStartedAsync()68.18%252281.81%
SendRequestAsync(...)50%12860%
SendRequestAsync()100%66100%
PingAsync()37.5%8883.33%
DisposeAsync()83.33%171267.74%
EnsureProtocolVersion(...)100%22100%
SendRequestCoreAsync()50%2283.33%
StartProcessCore()56.25%201675.36%
ConnectPipeAsync()50%2270.83%
ReadLoopAsync()75%281663.63%
StartWatchdog()100%11100%
StopWatchdog()100%22100%
WatchdogTickAsync()40%191054.54%
OnContactLost(...)68.75%171684%
OnProcessExited()75%4480%
ScheduleRestart()50%6696.96%
CleanupConnectionAsync()100%8884.61%
KillProcess(...)100%4476.92%
FailAllPending(...)50%6450%
Log(...)100%11100%
ThrowIfDisposed()50%2266.66%

File(s)

/home/runner/work/InvAit/InvAit/ToolCore/McpHost/McpHostSupervisor.cs

#LineLine coverage
 1using System.Collections.Concurrent;
 2using System.Diagnostics;
 3using System.IO;
 4using System.IO.Pipes;
 5using System.Text;
 6using System.Text.Json;
 7using Shared.Contracts.McpHost;
 8using Shared.Ipc;
 9
 10namespace ToolCore.McpHost;
 11
 12public enum McpHostConnectionState
 13{
 14    Idle,
 15    Connecting,
 16    Connected,
 17    Recovering,
 18    Disposed,
 19}
 20
 21public sealed class McpHostSupervisor : IAsyncDisposable
 22{
 123    private static readonly JsonSerializerOptions JsonOptions = new()
 124    {
 125        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
 126        PropertyNameCaseInsensitive = true,
 127    };
 28
 29    private readonly ILogger _logger;
 30    private readonly McpHostSupervisorOptions _options;
 31    private readonly string _pipeName;
 32
 1033    private readonly SemaphoreSlim _stateLock = new(1, 1);
 1034    private readonly SemaphoreSlim _writeLock = new(1, 1);
 1035    private readonly ConcurrentDictionary<long, TaskCompletionSource<McpHostResponse>> _pending = new();
 36
 37    private Timer? _watchdogTimer;
 38    private CancellationTokenSource? _connectionCts;
 39    private CancellationTokenSource? _restartCts;
 40    private Process? _process;
 41    private NamedPipeClientStream? _pipe;
 42
 43    private long _nextId;
 44    private int _pingFailures;
 45    private int _restartAttempts;
 46    private volatile McpHostConnectionState _state = McpHostConnectionState.Idle;
 47    private volatile bool _everConnected;
 48    private volatile bool _disposed;
 49
 1050    public McpHostSupervisor(McpHostSupervisorOptions options, ILogger logger)
 51    {
 1052        _options = options ?? throw new ArgumentNullException(nameof(options));
 1053        if (string.IsNullOrWhiteSpace(_options.HostExecutablePath))
 054            throw new ArgumentException("HostExecutablePath is required.", nameof(options));
 1055        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
 1056        _pipeName = string.IsNullOrWhiteSpace(_options.PipeName)
 1057            ? $"invait.mcp.{Guid.NewGuid():N}"
 1058            : _options.PipeName!;
 1059    }
 60
 61    public event Action<string>? ConnectionLost;
 62
 2563    public bool IsConnected => _state == McpHostConnectionState.Connected && _pipe is { IsConnected: true };
 64
 65    public async Task EnsureStartedAsync(CancellationToken cancellationToken = default)
 66    {
 1267        ThrowIfDisposed();
 68
 1269        await _stateLock.WaitAsync(cancellationToken).ConfigureAwait(false);
 70        try
 71        {
 1272            ThrowIfDisposed();
 1273            if (_state == McpHostConnectionState.Connected)
 074                return;
 75
 1276            _state = McpHostConnectionState.Connecting;
 1277            await CleanupConnectionAsync().ConfigureAwait(false);
 78
 1279            _restartCts?.Cancel();
 1280            _restartCts?.Dispose();
 1281            _restartCts = null;
 82
 1283            StartProcessCore();
 84
 1085            var pipe = await ConnectPipeAsync(cancellationToken).ConfigureAwait(false);
 1086            _pipe = pipe;
 87
 1088            _connectionCts = new CancellationTokenSource();
 1089            _ = Task.Run(() => ReadLoopAsync(pipe, _connectionCts.Token), CancellationToken.None);
 90
 1091            StartWatchdog();
 92
 1093            if (_disposed)
 094                throw new ObjectDisposedException(nameof(McpHostSupervisor));
 95
 96            try
 97            {
 1098                var ping = await SendRequestCoreAsync(McpHostMethods.Ping, null, TimeSpan.FromSeconds(10), cancellationT
 1099                if (!ping.Success)
 0100                    throw new McpHostStartupException($"MCP host handshake failed: {ping.Error}");
 10101                var info = JsonUtils.GetObject<McpHostPingResult>(ping.Result!.Value)
 10102                           ?? throw new McpHostStartupException("MCP host handshake returned an unexpected payload.");
 10103                EnsureProtocolVersion(info.Version);
 10104                Log($"MCP host connected (pid {info.Pid}, protocol {info.Version}).");
 10105            }
 0106            catch (McpHostStartupException)
 107            {
 0108                throw;
 109            }
 0110            catch (Exception ex)
 111            {
 0112                throw new McpHostStartupException("MCP host failed to start or did not respond within the start timeout.
 113            }
 114
 10115            _restartAttempts = 0;
 10116            Interlocked.Exchange(ref _pingFailures, 0);
 10117            _everConnected = true;
 10118            _state = McpHostConnectionState.Connected;
 10119        }
 2120        catch
 121        {
 2122            var wasEverConnected = _everConnected;
 2123            _state = wasEverConnected ? McpHostConnectionState.Recovering : McpHostConnectionState.Idle;
 2124            await CleanupConnectionAsync().ConfigureAwait(false);
 2125            if (wasEverConnected && !_disposed)
 0126                ScheduleRestart();
 2127            throw;
 128        }
 129        finally
 130        {
 12131            _stateLock.Release();
 132        }
 10133    }
 134
 135    public Task<McpHostResponse> SendRequestAsync(string method, object? parameters, TimeSpan timeout, CancellationToken
 136    {
 1137        if (_disposed)
 0138            throw new ObjectDisposedException(nameof(McpHostSupervisor));
 1139        if (_state != McpHostConnectionState.Connected || _pipe is not { IsConnected: true })
 0140            throw new InvalidOperationException("MCP host is not connected. Call EnsureStartedAsync first.");
 141
 1142        return SendRequestCoreAsync(method, parameters, timeout, cancellationToken);
 143    }
 144
 145    public async Task<McpHostResponse> SendRequestAsync(string method, object? parameters = null, CancellationToken canc
 146    {
 13147        if (_state != McpHostConnectionState.Connected || _pipe is not { IsConnected: true })
 2148            throw new InvalidOperationException("MCP host is not connected. Call EnsureStartedAsync first.");
 149
 11150        return await SendRequestCoreAsync(method, parameters, _options.RequestTimeout, cancellationToken).ConfigureAwait
 11151    }
 152
 153    public async Task<McpHostPingResult> PingAsync(CancellationToken cancellationToken = default)
 154    {
 10155        var response = await SendRequestAsync(McpHostMethods.Ping, null, cancellationToken);
 8156        if (!response.Success || response.Result is not { } result)
 0157            throw new IOException($"Ping failed: {response.Error ?? "empty result"}.");
 8158        return JsonUtils.GetObject<McpHostPingResult>(result)
 8159               ?? throw new IOException("Ping returned an unexpected payload.");
 8160    }
 161
 162    public async ValueTask DisposeAsync()
 163    {
 10164        var lockTaken = false;
 165        try
 166        {
 10167            lockTaken = await _stateLock.WaitAsync(TimeSpan.FromSeconds(20), CancellationToken.None).ConfigureAwait(fals
 10168        }
 0169        catch (ObjectDisposedException)
 170        {
 0171        }
 172
 10173        if (!lockTaken)
 174        {
 0175            _disposed = true;
 0176            StopWatchdog();
 0177            FailAllPending(new ObjectDisposedException(nameof(McpHostSupervisor)));
 0178            KillProcess("dispose (lock timeout)");
 0179            return;
 180        }
 181
 182        try
 183        {
 10184            if (_disposed)
 0185                return;
 186
 10187            StopWatchdog();
 188
 10189            if (IsConnected)
 190            {
 191                try
 192                {
 7193                    await SendRequestCoreAsync(McpHostMethods.Shutdown, null, TimeSpan.FromSeconds(2), CancellationToken
 7194                    Log("MCP host acknowledged shutdown.");
 7195                }
 0196                catch
 197                {
 0198                }
 199            }
 200
 10201            _disposed = true;
 10202            _state = McpHostConnectionState.Disposed;
 10203            _restartCts?.Cancel();
 10204            _restartCts?.Dispose();
 10205            _restartCts = null;
 206
 10207            await CleanupConnectionAsync().ConfigureAwait(false);
 10208            FailAllPending(new ObjectDisposedException(nameof(McpHostSupervisor)));
 209
 10210            GC.SuppressFinalize(this);
 10211        }
 212        finally
 213        {
 10214            _stateLock.Release();
 215        }
 10216    }
 217
 218    internal static void EnsureProtocolVersion(string actual)
 219    {
 14220        if (!string.Equals(actual, McpHostProtocol.Version, StringComparison.Ordinal))
 2221            throw new McpHostStartupException($"MCP host protocol mismatch: host '{actual}', client '{McpHostProtocol.Ve
 12222    }
 223
 224    private async Task<McpHostResponse> SendRequestCoreAsync(string method, object? parameters, TimeSpan timeout, Cancel
 225    {
 30226        if (_disposed)
 0227            throw new ObjectDisposedException(nameof(McpHostSupervisor));
 228
 30229        var id = Interlocked.Increment(ref _nextId);
 30230        var tcs = new TaskCompletionSource<McpHostResponse>(TaskCreationOptions.RunContinuationsAsynchronously);
 30231        _pending[id] = tcs;
 232
 30233        using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
 30234        timeoutCts.CancelAfter(timeout);
 30235        using var registration = timeoutCts.Token.Register(
 30236            state => ((TaskCompletionSource<McpHostResponse>)state!).TrySetCanceled(timeoutCts.Token),
 30237            tcs);
 238
 239        try
 240        {
 30241            var request = new McpHostRequest { Id = id, Method = method, Params = parameters };
 30242            var bytes = Encoding.UTF8.GetBytes(JsonUtils.SerializeCompact(request));
 243
 30244            await _writeLock.WaitAsync(timeoutCts.Token).ConfigureAwait(false);
 245            try
 246            {
 30247                await FrameCodec.WriteFrameAsync(_pipe!, bytes, cancellationToken).ConfigureAwait(false);
 30248            }
 249            finally
 250            {
 30251                _writeLock.Release();
 252            }
 253
 30254            return await tcs.Task.ConfigureAwait(false);
 255        }
 1256        catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
 257        {
 1258            throw new TimeoutException($"MCP host request '{method}' timed out after {timeout.TotalMilliseconds} ms.");
 259        }
 0260        catch (Exception ex) when (ex is IOException or ObjectDisposedException)
 261        {
 0262            OnContactLost($"request '{method}' failed: {ex.Message}");
 0263            throw new IOException($"MCP host connection lost while sending '{method}'.", ex);
 264        }
 265        finally
 266        {
 30267            _pending.TryRemove(id, out _);
 268        }
 29269    }
 270
 271    private void StartProcessCore()
 272    {
 12273        var hostPath = Path.GetFullPath(_options.HostExecutablePath!);
 12274        if (!File.Exists(hostPath))
 2275            throw new McpHostStartupException($"MCP host executable was not found: '{hostPath}'.");
 276
 10277        if (!_options.SkipRuntimeCheck && !DotNetRuntimeLocator.IsRuntimeInstalled())
 278        {
 0279            Log("ERROR: " + DotNetRuntimeLocator.InstallHint);
 0280            throw new McpHostStartupException(DotNetRuntimeLocator.InstallHint);
 281        }
 282
 10283        var psi = new ProcessStartInfo
 10284        {
 10285            UseShellExecute = false,
 10286            CreateNoWindow = true,
 10287            RedirectStandardOutput = true,
 10288            RedirectStandardError = true,
 10289            StandardOutputEncoding = Encoding.UTF8,
 10290            StandardErrorEncoding = Encoding.UTF8,
 10291            WorkingDirectory = Path.GetDirectoryName(hostPath) ?? Environment.CurrentDirectory,
 10292        };
 293
 10294        var arguments = $"--pipe-name \"{_pipeName}\" --idle-exit-ms {_options.HostIdleExitMs}";
 295
 10296        if (hostPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
 297        {
 10298            if (!DotNetRuntimeLocator.TryGetDotNetExecutable(out var dotnetExe))
 0299                throw new McpHostStartupException(DotNetRuntimeLocator.InstallHint);
 10300            psi.FileName = dotnetExe;
 10301            psi.Arguments = $"\"{hostPath}\" {arguments}";
 302        }
 303        else
 304        {
 0305            psi.FileName = hostPath;
 0306            psi.Arguments = arguments;
 307        }
 308
 10309        var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
 10310        process.OutputDataReceived += (_, e) =>
 10311        {
 10312            if (!string.IsNullOrWhiteSpace(e.Data))
 10313                Log($"host: {e.Data}");
 10314        };
 10315        process.ErrorDataReceived += (_, e) =>
 10316        {
 10317            if (!string.IsNullOrWhiteSpace(e.Data))
 10318                Log($"host(err): {e.Data}");
 10319        };
 10320        process.Exited += (_, _) =>
 10321        {
 10322            try
 10323            {
 10324                var exitCode = process.HasExited ? process.ExitCode : -1;
 10325                Log($"MCP host process exited (code {exitCode}).");
 10326            }
 10327            catch (Exception)
 10328            {
 10329                Log("MCP host process exited.");
 10330            }
 10331
 10332            OnProcessExited();
 10333        };
 334
 335        try
 336        {
 10337            if (!process.Start())
 338            {
 0339                process.Dispose();
 0340                throw new McpHostStartupException($"Failed to start MCP host process '{psi.FileName}'.");
 341            }
 10342        }
 0343        catch (Exception ex) when (ex is not McpHostStartupException)
 344        {
 0345            process.Dispose();
 0346            throw new McpHostStartupException($"Failed to start MCP host process '{psi.FileName}': {ex.Message}", ex);
 347        }
 348
 10349        _process = process;
 10350        if (_disposed)
 351        {
 352            try
 353            {
 0354                process.Kill();
 0355                process.WaitForExit(2000);
 0356            }
 0357            catch
 358            {
 0359            }
 360
 0361            process.Dispose();
 0362            throw new ObjectDisposedException(nameof(McpHostSupervisor));
 363        }
 364
 10365        process.BeginOutputReadLine();
 10366        process.BeginErrorReadLine();
 10367        Log($"MCP host process started (pid {process.Id}): {psi.FileName} {arguments}");
 10368    }
 369
 370    private async Task<NamedPipeClientStream> ConnectPipeAsync(CancellationToken cancellationToken)
 371    {
 10372        var deadline = DateTime.UtcNow + _options.StartTimeout;
 8373        while (true)
 374        {
 18375            ThrowIfDisposed();
 18376            cancellationToken.ThrowIfCancellationRequested();
 377
 18378            var pipe = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
 379            try
 380            {
 18381                var remaining = deadline - DateTime.UtcNow;
 18382                if (remaining <= TimeSpan.Zero)
 0383                    throw new TimeoutException("Timed out waiting for MCP host pipe.");
 384
 18385                var sliceMs = (int)Math.Min(remaining.TotalMilliseconds, 250);
 18386                var connectTask = Task.Run(() => pipe.Connect(sliceMs), cancellationToken);
 18387                await connectTask.ConfigureAwait(false);
 10388                return pipe;
 389            }
 8390            catch (TimeoutException) when (DateTime.UtcNow < deadline)
 391            {
 8392                pipe.Dispose();
 8393                await Task.Delay(50, cancellationToken).ConfigureAwait(false);
 8394            }
 0395            catch (Exception ex) when ((ex is IOException or System.ComponentModel.Win32Exception) && DateTime.UtcNow < 
 396            {
 0397                pipe.Dispose();
 0398                await Task.Delay(50, cancellationToken).ConfigureAwait(false);
 399            }
 0400            catch
 401            {
 0402                pipe.Dispose();
 0403                throw;
 404            }
 8405        }
 10406    }
 407
 408    private async Task ReadLoopAsync(NamedPipeClientStream pipe, CancellationToken cancellationToken)
 409    {
 410        try
 411        {
 39412            while (!cancellationToken.IsCancellationRequested)
 413            {
 39414                var payload = await FrameCodec.ReadFrameAsync(pipe, McpHostProtocol.MaxFrameBytes, cancellationToken).Co
 37415                if (payload == null)
 416                    break;
 417
 418                McpHostResponse? response;
 419                try
 420                {
 29421                    response = JsonSerializer.Deserialize<McpHostResponse>(payload, JsonOptions);
 29422                }
 0423                catch (JsonException ex)
 424                {
 0425                    Log($"ERROR: Failed to deserialize MCP host frame: {ex.Message}");
 0426                    continue;
 427                }
 428
 29429                if (response == null)
 430                    continue;
 431
 29432                if (_pending.TryRemove(response.Id, out var tcs))
 29433                    tcs.TrySetResult(response);
 434            }
 8435        }
 2436        catch (OperationCanceledException)
 437        {
 2438        }
 0439        catch (Exception ex) when (!_disposed)
 440        {
 0441            Log($"MCP host read loop terminated: {ex.Message}");
 0442            if (!_disposed && _state == McpHostConnectionState.Connected)
 0443                OnContactLost($"read loop failed: {ex.Message}");
 0444        }
 445
 10446        if (!_disposed && _state == McpHostConnectionState.Connected)
 8447            OnContactLost("host closed the connection stream.");
 10448    }
 449
 450    private void StartWatchdog()
 451    {
 10452        StopWatchdog();
 10453        var interval = _options.PingInterval;
 10454        var dueMs = (int)(interval.TotalMilliseconds * 1.5);
 10455        var periodMs = (int)interval.TotalMilliseconds;
 10456        _watchdogTimer = new Timer(_ => { _ = WatchdogTickAsync(); }, null, dueMs, periodMs);
 10457    }
 458
 459    private void StopWatchdog()
 460    {
 47461        _watchdogTimer?.Dispose();
 47462        _watchdogTimer = null;
 47463    }
 464
 465    private async Task WatchdogTickAsync()
 466    {
 2467        if (_disposed || _state != McpHostConnectionState.Connected)
 1468            return;
 469
 470        try
 471        {
 1472            await SendRequestCoreAsync(McpHostMethods.Ping, null, _options.PingTimeout, CancellationToken.None).Configur
 1473            Interlocked.Exchange(ref _pingFailures, 0);
 1474        }
 0475        catch (Exception)
 476        {
 0477            var failures = Interlocked.Increment(ref _pingFailures);
 0478            if (failures >= Math.Max(1, _options.PingFailureThreshold) && !_disposed && _state == McpHostConnectionState
 0479                OnContactLost($"{failures} consecutive pings failed.");
 0480        }
 2481    }
 482
 483    private void OnContactLost(string reason)
 484    {
 8485        if (_disposed || _state != McpHostConnectionState.Connected)
 1486            return;
 487
 7488        var lockTaken = false;
 7489        string? fireReason = null;
 490        try
 491        {
 7492            lockTaken = _stateLock.Wait(0, _connectionCts?.Token ?? CancellationToken.None);
 7493        }
 0494        catch (ObjectDisposedException)
 495        {
 0496            return;
 497        }
 498
 7499        if (!lockTaken)
 4500            return;
 501
 502        try
 503        {
 3504            if (_disposed || _state != McpHostConnectionState.Connected)
 0505                return;
 506
 3507            Log($"MCP host contact lost: {reason}");
 508
 3509            _state = McpHostConnectionState.Recovering;
 3510            StopWatchdog();
 511
 3512            FailAllPending(new IOException("Connection to MCP host lost."));
 3513            _connectionCts?.Cancel();
 514
 3515            KillProcess("contact lost");
 3516            ScheduleRestart();
 3517            fireReason = reason;
 3518        }
 519        finally
 520        {
 3521            _stateLock.Release();
 3522        }
 523
 3524        ConnectionLost?.Invoke(fireReason);
 0525    }
 526
 527    private void OnProcessExited()
 528    {
 10529        if (_disposed)
 7530            return;
 531
 3532        if (_state == McpHostConnectionState.Connected)
 0533            OnContactLost("host process exited unexpectedly.");
 3534    }
 535
 536    private void ScheduleRestart()
 537    {
 3538        if (_disposed || !_everConnected)
 0539            return;
 540
 3541        var attempts = ++_restartAttempts;
 3542        var delay = TimeSpan.FromMilliseconds(Math.Min(
 3543            _options.RestartBaseDelay.TotalMilliseconds * Math.Pow(2, attempts - 1),
 3544            _options.RestartMaxDelay.TotalMilliseconds));
 545
 3546        _restartCts?.Dispose();
 3547        _restartCts = new CancellationTokenSource();
 3548        var token = _restartCts.Token;
 549
 3550        Log($"Scheduling MCP host restart in {delay.TotalMilliseconds} ms (attempt {attempts}).");
 3551        _ = Task.Run(async () =>
 3552        {
 3553            try
 3554            {
 3555                await Task.Delay(delay, token).ConfigureAwait(false);
 3556                if (_disposed)
 3557                    return;
 3558                Log("Restarting MCP host...");
 3559                await EnsureStartedAsync(CancellationToken.None).ConfigureAwait(false);
 3560            }
 3561            catch (OperationCanceledException)
 3562            {
 3563            }
 3564            catch (McpHostStartupException ex)
 3565            {
 3566                Log("ERROR: MCP host restart failed: " + ex.UserMessage);
 3567            }
 3568            catch (Exception ex)
 3569            {
 3570                Log($"ERROR: MCP host restart failed: {ex.Message}");
 3571            }
 3572        }, CancellationToken.None);
 3573    }
 574
 575    private async Task CleanupConnectionAsync()
 576    {
 24577        StopWatchdog();
 578
 24579        _connectionCts?.Cancel();
 24580        _connectionCts?.Dispose();
 24581        _connectionCts = null;
 582
 583        try
 584        {
 24585            _pipe?.Dispose();
 24586        }
 0587        catch
 588        {
 0589        }
 24590        _pipe = null;
 591
 24592        KillProcess("cleanup");
 593
 24594        _process?.Dispose();
 24595        _process = null;
 24596    }
 597
 598    private void KillProcess(string reason)
 599    {
 27600        var process = _process;
 27601        if (process == null)
 14602            return;
 603
 604        try
 605        {
 13606            process.Refresh();
 13607            if (!process.HasExited)
 608            {
 10609                process.Kill();
 10610                process.WaitForExit(3000);
 10611                Log($"MCP host process killed ({reason}).");
 612            }
 13613        }
 0614        catch (Exception ex)
 615        {
 0616            Log($"WARN: Failed to kill MCP host process ({reason}): {ex.Message}");
 0617        }
 13618    }
 619
 620    private void FailAllPending(Exception exception)
 621    {
 26622        foreach (var pair in _pending)
 623        {
 0624            if (_pending.TryRemove(pair.Key, out var tcs))
 0625                tcs.TrySetException(exception);
 626        }
 13627    }
 628
 89629    private void Log(string message) => _logger.Log("[McpHost] " + message);
 630
 631    private void ThrowIfDisposed()
 632    {
 42633        if (_disposed)
 0634            throw new ObjectDisposedException(nameof(McpHostSupervisor));
 42635    }
 636}