using ModelContextProtocol.Protocol; using System.Diagnostics.CodeAnalysis; using System.Text.Json; using System.Text.Json.Nodes; namespace ModelContextProtocol; /// /// Represents an exception used to signal that a request's declared protocol version is not supported by the server. /// /// /// Introduced by the 2026-07-28 protocol revision (SEP-2575). Servers throw this exception when they cannot process /// a request because the per-request _meta/io.modelcontextprotocol/protocolVersion (or the equivalent /// transport-level header) names a version the server does not implement. The exception is converted to a /// JSON-RPC error response with code (-32022) and /// a payload. /// public sealed class UnsupportedProtocolVersionException : McpProtocolException { /// /// Initializes a new instance of the class. /// /// The protocol version the client requested. /// The protocol versions the server supports. /// A human-readable description of the error. If , a default message is used. public UnsupportedProtocolVersionException(string requested, IEnumerable supported, string? message = null) : base(message ?? $"Unsupported protocol version '{requested}'.", McpErrorCode.UnsupportedProtocolVersion) { Throw.IfNull(requested); Throw.IfNull(supported); Requested = requested; Supported = new List(supported); } /// Gets the protocol version the client requested. public string Requested { get; } /// Gets the protocol versions the server supports. public IReadOnlyList Supported { get; } internal JsonNode CreateErrorDataNode() { var payload = new UnsupportedProtocolVersionErrorData { Requested = Requested, Supported = (IList)Supported, }; return JsonSerializer.SerializeToNode(payload, McpJsonUtilities.JsonContext.Default.UnsupportedProtocolVersionErrorData)!; } internal static bool TryCreateFromError( string formattedMessage, JsonRpcErrorDetail detail, [NotNullWhen(true)] out UnsupportedProtocolVersionException? exception) { exception = null; if (detail.Data is not JsonElement dataElement || dataElement.ValueKind is not JsonValueKind.Object) { return false; } var payload = dataElement.Deserialize(McpJsonUtilities.JsonContext.Default.UnsupportedProtocolVersionErrorData); if (payload is null) { return false; } exception = new UnsupportedProtocolVersionException(payload.Requested, payload.Supported, formattedMessage); return true; } }