initialize method
Initialize the connection to the server
Implementation
Future<void> initialize() async {
if (_initialized) {
throw McpError('Client is already initialized');
}
if (!isConnected) {
throw McpError('Client is not connected to a transport');
}
final response = await _sendRequest('initialize', {
'protocolVersion': protocolVersion,
// Optional `Implementation` fields are emitted only when set, so older
// peers see the shape they know.
'clientInfo': _clientInfo,
'capabilities': capabilities.toJson(),
});
if (response == null) {
throw McpError('Failed to initialize: No response from server');
}
final serverProtoVersion = response['protocolVersion'];
if (serverProtoVersion != protocolVersion) {
_validateProtocolVersion(serverProtoVersion);
}
// Lifecycle, version negotiation: a version this client does not
// support ends the connection.
if (serverProtoVersion is! String ||
!McpProtocol.supportedVersions.contains(serverProtoVersion)) {
disconnect();
throw McpError(
'Server chose protocol version $serverProtoVersion, which this client '
'does not support (${McpProtocol.supportedVersions.join(", ")})',
);
}
_serverInfo = response['serverInfo'];
final capabilitiesData = response['capabilities'];
_serverCapabilities = ServerCapabilities.fromJson(
capabilitiesData != null
? Map<String, dynamic>.from(capabilitiesData as Map)
: {},
);
// Capture the negotiated revision and inform the transport so HTTP
// implementations can stamp `MCP-Protocol-Version: <version>` on
// every post-handshake request (spec 2025-06-18+).
_negotiatedProtocolVersion = serverProtoVersion;
// HTTP transports attach `MCP-Protocol-Version` to subsequent
// requests when the negotiated revision is 2025-06-18+. Other
// transports (stdio / SSE) ignore the header so we only forward
// when the concrete transport exposes the setter.
final tx = _transport;
if (tx is StreamableHttpClientTransport) {
tx.setProtocolVersion(serverProtoVersion);
}
// Send initialized notification
_sendNotification('notifications/initialized', {});
_initialized = true;
_logger.debug('Initialization complete');
}