dispose method

  1. @override
Future<void> dispose()

Releases every resource held by this object.

Must be idempotent, must not throw for an already-disposed object, and should complete even if an underlying resource fails to close: a partial teardown that gives up halfway leaks the remainder.

Implementation

@override
Future<void> dispose() async {
  if (_disposed) return;
  _disposed = true;

  await _stdoutSubscription?.cancel();
  await _stderrSubscription?.cancel();
  await _incoming.close();
  await _stderr.close();

  // Closing stdin is how a well-behaved MCP server is asked to shut down; the
  // kill is the backstop for one that ignores it. Killing first would lose
  // any work the server was flushing.
  try {
    await _process.stdin.close();
  } on Object {
    // The pipe may already be gone; nothing to do about it during teardown.
  }
  unawaited(
    _process.exitCode
        .timeout(
          const Duration(seconds: 5),
          onTimeout: () {
            _process.kill();
            return -1;
          },
        )
        .catchError((_) => -1),
  );
}