initializeAcrossVersions method

Future<InitializedServer> initializeAcrossVersions(
  1. MCPServerInitialization initialization, {
  2. Duration discoverTimeout = const Duration(seconds: 10),
})

Initializes this connection through discovery or legacy initialization, following https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning#backward-compatibility-with-initialization-based-versions.

If the proposed version has server/discover, this probes with discover first and falls back to initialize after discoverTimeout or an unrecognized RpcException. Rethrows 2026-07-28 refusals as RpcExceptions.

Throws an ArgumentError without MCPServerInitialization.clientInfo, since the legacy fallback needs it, and a StateError if the discover result omits the proposed version or the legacy answer names a version this client does not support. If setLogLevel fails, the handshake is already complete and the fields stay set.

The fallback needs a channel that also carries legacy requests, such as stdioChannel. Later 2026-07-28 requests need their own envelope.

Implementation

Future<InitializedServer> initializeAcrossVersions(
  MCPServerInitialization initialization, {
  // Leaves room for a slow server start while bounding how long a silent
  // legacy server delays the fallback.
  Duration discoverTimeout = const Duration(seconds: 10),
}) async {
  final clientInfo = ArgumentError.checkNotNull(
    initialization.clientInfo,
    'clientInfo',
  );
  final proposed = initialization.protocolVersion;
  if (proposed.methodIsValid(DiscoverRequest.methodName)) {
    try {
      final result = await discover(
        protocolVersion: proposed,
        capabilities: initialization.clientCapabilities,
        clientInfo: clientInfo,
        logLevel: initialization.logLevel,
      ).timeout(
        discoverTimeout,
        onTimeout:
            () =>
                throw TimeoutException(
                  'No answer to the discover probe within $discoverTimeout',
                ),
      );
      if (!result.supportedVersions.contains(proposed.versionString)) {
        throw StateError(
          'A server answered discover on ${proposed.versionString} but '
          'listed ${result.supportedVersions} instead.',
        );
      }
      final rawServerInfo = result.meta?[Keys.serverInfoMeta];
      protocolVersion = proposed;
      serverCapabilities = result.capabilities;
      serverInfo =
          rawServerInfo is Map<String, Object?>
              ? Implementation.fromMap(rawServerInfo)
              : null;
      return InitializedServer(
        protocolVersion: proposed,
        capabilities: result.capabilities,
        serverInfo: serverInfo,
        instructions: result.instructions,
      );
    } on TimeoutException {
      // A legacy server may never answer a method it does not know. A
      // silent probe falls back too, and a late answer to it is ignored.
    } on RpcException catch (error) {
      // These codes come from a server that understood the probe and
      // refused it. The compatibility procedure stops on these errors. For an
      // unsupported version, a caller can retry with one the error lists.
      // The spec falls back on any other error.
      if (error.code == McpErrorCodes.unsupportedProtocolVersion ||
          error.code == McpErrorCodes.missingRequiredClientCapability ||
          error.code == McpErrorCodes.headerMismatch) {
        rethrow;
      }
    }
  }

  final legacyVersion =
      proposed.isLegacyVersion ? proposed : ProtocolVersion.lastLegacyVersion;
  final result = await _initialize(
    InitializeRequest(
      protocolVersion: legacyVersion,
      capabilities: initialization.clientCapabilities,
      clientInfo: clientInfo,
    ),
  );
  final serverVersion = result.protocolVersion;
  if (serverVersion == null || !serverVersion.isLegacyVersion) {
    throw StateError(
      'The server answered initialize with the unsupported protocol version '
      '"${(result as Map<String, Object?>)[Keys.protocolVersion]}", and '
      'initialize has shut the connection down.',
    );
  }
  notifyInitialized();
  final logLevel = initialization.logLevel;
  if (logLevel != null && result.capabilities.logging != null) {
    await setLogLevel(SetLevelRequest(level: logLevel));
  }
  return InitializedServer(
    protocolVersion: serverVersion,
    capabilities: result.capabilities,
    serverInfo: result.serverInfo,
    instructions: result.instructions,
  );
}