initializeLegacy method
Handles the initialize request used by legacy MCP protocols.
Most servers should override initialize to register features. Override this method only to customize legacy protocol negotiation or its wire response.
Implementation
@mustCallSuper
/// Handles the initialize request used by legacy MCP protocols.
///
/// Most servers should override [initialize] to register features. Override
/// this method only to customize legacy protocol negotiation or its wire
/// response.
FutureOr<InitializeResult> initializeLegacy(InitializeRequest request) async {
// If we don't support or understand the version, set it to the latest one
// that we do support. If the client doesn't support that version they will
// terminate the connection.
final clientProtocolVersion = request.protocolVersion;
final negotiatedProtocolVersion =
clientProtocolVersion == null || !clientProtocolVersion.isLegacyVersion
? ProtocolVersion.lastLegacyVersion
: clientProtocolVersion;
late final ClientCapabilities clientCapabilities;
try {
clientCapabilities = request.capabilities;
// The getter validates what the client sent, so this error describes
// the request and not a bug on this side.
// ignore: avoid_catching_errors
} on ArgumentError {
throw RpcException.invalidParams(
'The initialize request has invalid capabilities',
);
}
assert(!_initialized.isCompleted);
await initialize(
MCPServerInitialization(
protocolVersion: negotiatedProtocolVersion,
clientCapabilities: clientCapabilities,
clientInfo: request.clientInfo,
),
);
return InitializeResult(
protocolVersion: negotiatedProtocolVersion,
serverCapabilities: capabilities,
serverInfo: implementation,
instructions: instructions,
);
}