diff --git a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs index 75281aa96..f0b0b1a12 100644 --- a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs +++ b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs @@ -55,13 +55,6 @@ internal sealed class StreamableHttpHandler( public async Task HandlePostRequestAsync(HttpContext context) { - var configuredSupportedProtocolVersions = GetConfiguredSupportedProtocolVersions(mcpServerOptionsSnapshot.Value.ProtocolVersion); - if (!ValidateProtocolVersionHeader(context, configuredSupportedProtocolVersions, out var protocolVersionError)) - { - await WriteJsonRpcErrorDetailAsync(context, protocolVersionError, StatusCodes.Status400BadRequest); - return; - } - // The Streamable HTTP spec mandates the client MUST accept both application/json and text/event-stream. // ASP.NET Core Minimal APIs mostly try to stay out of the business of response content negotiation, // so we have to do this manually. The spec doesn't mandate that servers MUST reject these requests, @@ -104,6 +97,15 @@ await WriteJsonRpcErrorAsync(context, // Notifications carry no id, so this stays default (null), which is correct. var requestId = message is JsonRpcRequest jsonRpcRequest ? jsonRpcRequest.Id : default; + // Validated after the body parse (rather than first) so the rejection can echo the request's + // JSON-RPC id: every error response for a parseable request MUST carry its id. + var configuredSupportedProtocolVersions = GetConfiguredSupportedProtocolVersions(mcpServerOptionsSnapshot.Value.ProtocolVersion); + if (!ValidateProtocolVersionHeader(context, configuredSupportedProtocolVersions, HttpServerTransportOptions.Stateless, out var protocolVersionError)) + { + await WriteJsonRpcErrorDetailAsync(context, protocolVersionError, StatusCodes.Status400BadRequest, requestId); + return; + } + if (!ValidateProtocolVersionEnvelope(context, message, out var protocolVersionEnvelopeError)) { await WriteJsonRpcErrorDetailAsync(context, protocolVersionEnvelopeError, StatusCodes.Status400BadRequest, requestId); @@ -116,6 +118,33 @@ await WriteJsonRpcErrorAsync(context, return; } + if (!ValidateRequiredPerRequestMeta(context, message, out var requiredMetaError)) + { + await WriteJsonRpcErrorDetailAsync(context, requiredMetaError, StatusCodes.Status400BadRequest, requestId); + return; + } + + // SEP-2575 removed these RPCs from the per-request-metadata HTTP surface (initialize and + // ping in favor of server/discover, logging/setLevel in favor of _meta logLevel, and the + // resource subscription pair in favor of subscriptions/listen). A request for a method the + // server does not implement is rejected with 404 Not Found and Method not found. Rejecting + // here gives HTTP the required status; the server protocol boundary enforces the same method + // set for other transports. +#pragma warning disable MCP9005 // logging/setLevel is deprecated (SEP-2577); referenced here only to reject it as removed. + if (RequiresPerRequestMetadataProtocol(context) && + message is JsonRpcRequest + { + Method: RequestMethods.Initialize or RequestMethods.Ping or RequestMethods.LoggingSetLevel + or RequestMethods.ResourcesSubscribe or RequestMethods.ResourcesUnsubscribe, + } removedMethodRequest) +#pragma warning restore MCP9005 + { + await WriteJsonRpcErrorAsync(context, + $"Method '{removedMethodRequest.Method}' is not available on protocol version '{context.Request.Headers[McpProtocolVersionHeaderName]}'.", + StatusCodes.Status404NotFound, (int)McpErrorCode.MethodNotFound, requestId); + return; + } + var session = await GetOrCreateSessionAsync(context, message, requestId); if (session is null) { @@ -124,8 +153,33 @@ await WriteJsonRpcErrorAsync(context, await using var _ = await session.AcquireReferenceAsync(context.RequestAborted); + Func? onResponseStarting = null; + if (RequiresPerRequestMetadataProtocol(context)) + { + // SEP-2575 maps some JSON-RPC error codes onto HTTP statuses (404 for a method the server + // does not implement, 400 for missing-capability and unsupported-version rejections). The + // status line can only be chosen before the first response byte, so the transport defers + // its eager header flush and reports the first response message here. + onResponseStarting = firstMessage => + { + if (firstMessage is JsonRpcError { Error: { } errorDetail } && !context.Response.HasStarted) + { + context.Response.StatusCode = (McpErrorCode)errorDetail.Code switch + { + McpErrorCode.MethodNotFound => StatusCodes.Status404NotFound, + McpErrorCode.MissingRequiredClientCapability => StatusCodes.Status400BadRequest, + McpErrorCode.UnsupportedProtocolVersion => StatusCodes.Status400BadRequest, + McpErrorCode.HeaderMismatch => StatusCodes.Status400BadRequest, + _ => context.Response.StatusCode, + }; + } + + return default; + }; + } + InitializeSseResponse(context); - var wroteResponse = await session.Transport.HandlePostRequestAsync(message, context.Response.Body, context.RequestAborted); + var wroteResponse = await session.Transport.HandlePostRequestAsync(message, context.Response.Body, onResponseStarting, context.RequestAborted); if (!wroteResponse) { // We wound up writing nothing, so there should be no Content-Type response header. @@ -137,7 +191,7 @@ await WriteJsonRpcErrorAsync(context, public async Task HandleGetRequestAsync(HttpContext context) { var configuredSupportedProtocolVersions = GetConfiguredSupportedProtocolVersions(mcpServerOptionsSnapshot.Value.ProtocolVersion); - if (!ValidateProtocolVersionHeader(context, configuredSupportedProtocolVersions, out var protocolVersionError)) + if (!ValidateProtocolVersionHeader(context, configuredSupportedProtocolVersions, HttpServerTransportOptions.Stateless, out var protocolVersionError)) { await WriteJsonRpcErrorDetailAsync(context, protocolVersionError, StatusCodes.Status400BadRequest); return; @@ -256,7 +310,7 @@ private static async Task HandleResumePostResponseStreamAsync(HttpContext contex public async Task HandleDeleteRequestAsync(HttpContext context) { var configuredSupportedProtocolVersions = GetConfiguredSupportedProtocolVersions(mcpServerOptionsSnapshot.Value.ProtocolVersion); - if (!ValidateProtocolVersionHeader(context, configuredSupportedProtocolVersions, out var protocolVersionError)) + if (!ValidateProtocolVersionHeader(context, configuredSupportedProtocolVersions, HttpServerTransportOptions.Stateless, out var protocolVersionError)) { await WriteJsonRpcErrorDetailAsync(context, protocolVersionError, StatusCodes.Status400BadRequest); return; @@ -652,6 +706,39 @@ internal static Task RunSessionAsync(HttpContext httpContext, McpServer session, internal static JsonTypeInfo GetRequiredJsonTypeInfo() => (JsonTypeInfo)McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(T)); + /// + /// Validates that a request riding a per-request-metadata protocol revision carries the required + /// _meta fields beyond the protocol version (which + /// already checked): io.modelcontextprotocol/clientCapabilities, which must be present and a + /// JSON object. Performed at the HTTP layer so the rejection can use 400 Bad Request as SEP-2575 + /// requires; a malformed (non-object) value would otherwise fail later during deserialization as a + /// generic internal error on a 200 response. clientInfo is optional, so its absence is not + /// rejected. + /// + private static bool ValidateRequiredPerRequestMeta( + HttpContext context, + JsonRpcMessage message, + [NotNullWhen(false)] out JsonRpcErrorDetail? errorDetail) + { + var protocolVersionHeader = context.Request.Headers[McpProtocolVersionHeaderName].ToString(); + if (message is JsonRpcRequest { Params: var requestParams } && + McpProtocolVersions.RequiresPerRequestMetadata(protocolVersionHeader) && + (requestParams is not JsonObject paramsObj || + paramsObj["_meta"] is not JsonObject metaObj || + metaObj[MetaKeys.ClientCapabilities] is not JsonObject)) + { + errorDetail = new JsonRpcErrorDetail + { + Code = (int)McpErrorCode.InvalidParams, + Message = $"Requests using protocol version '{protocolVersionHeader}' must include '_meta/{MetaKeys.ClientCapabilities}' as a JSON object.", + }; + return false; + } + + errorDetail = null; + return true; + } + /// /// Validates the MCP-Protocol-Version header if present. A missing header is allowed for backwards compatibility, /// but an invalid or unsupported value must be rejected with 400 Bad Request per the MCP spec. Per SEP-2575, the @@ -661,12 +748,30 @@ internal static Task RunSessionAsync(HttpContext httpContext, McpServer session, private static bool ValidateProtocolVersionHeader( HttpContext context, IReadOnlyList supportedProtocolVersions, + bool stateless, [NotNullWhen(false)] out JsonRpcErrorDetail? errorDetail) { var protocolVersionHeader = context.Request.Headers[McpProtocolVersionHeaderName].ToString(); if (!string.IsNullOrEmpty(protocolVersionHeader) && !supportedProtocolVersions.Contains(protocolVersionHeader)) { + // On a stateless server, restrict the advertised list to the per-request-metadata + // revisions: those are what server/discover advertises, and SEP-2575 clients use this + // list to pick a retry version for server/discover, so the two must agree. Requests for + // the older initialize-handshake revisions are still accepted above; only the error + // payload for unknown versions narrows. Stateful servers keep the full configured list + // (their 2026-07-28 refusal advertises the session-supporting versions separately in + // WriteUnsupportedProtocolVersionErrorAsync). + IReadOnlyList advertisedVersions = supportedProtocolVersions; + if (stateless) + { + var metadataVersions = supportedProtocolVersions.Where(McpProtocolVersions.RequiresPerRequestMetadata).ToArray(); + if (metadataVersions.Length > 0) + { + advertisedVersions = metadataVersions; + } + } + errorDetail = new JsonRpcErrorDetail { Code = (int)McpErrorCode.UnsupportedProtocolVersion, @@ -674,7 +779,7 @@ private static bool ValidateProtocolVersionHeader( Data = JsonSerializer.SerializeToNode( new UnsupportedProtocolVersionErrorData { - Supported = [.. supportedProtocolVersions], + Supported = [.. advertisedVersions], Requested = protocolVersionHeader, }, GetRequiredJsonTypeInfo()), @@ -749,8 +854,23 @@ private static bool ValidateProtocolVersionEnvelope( if (!hasProtocolVersionMeta) { - errorDetail = CreateHeaderMismatchError( - $"Bad Request: The body _meta/{MetaKeys.ProtocolVersion} field is required when the {McpProtocolVersionHeaderName} header declares a per-request metadata protocol version."); + // Notifications are exempt from the required-_meta rejection: they are fire-and-forget + // (a JSON-RPC error response has no recipient), and rejecting them silently drops + // client signals like notifications/cancelled, leaving server-side work running. + if (message is not JsonRpcRequest) + { + errorDetail = null; + return true; + } + + // A missing (rather than mismatched) per-request metadata field is an Invalid params + // rejection per SEP-2575; HeaderMismatch (-32020) is reserved for values that are + // present on both sides but disagree. + errorDetail = new JsonRpcErrorDetail + { + Code = (int)McpErrorCode.InvalidParams, + Message = $"Requests using protocol version '{protocolVersionHeader}' must include '_meta/{MetaKeys.ProtocolVersion}'.", + }; return false; } diff --git a/src/ModelContextProtocol.Core/Client/McpClient.Methods.cs b/src/ModelContextProtocol.Core/Client/McpClient.Methods.cs index a96ba5ae0..bccdd7a2e 100644 --- a/src/ModelContextProtocol.Core/Client/McpClient.Methods.cs +++ b/src/ModelContextProtocol.Core/Client/McpClient.Methods.cs @@ -733,6 +733,12 @@ public Task SubscribeToResourceAsync(string uri, RequestOptions? options = null, /// For a simpler API that handles both subscription and notification registration in a single call, /// use . /// + /// + /// The 2026-07-28 protocol revision (SEP-2575) removed resources/subscribe in favor of + /// with resourceSubscriptions. On a session that + /// negotiated that revision or later, this method throws an with + /// . + /// /// public Task SubscribeToResourceAsync( SubscribeRequestParams requestParams, @@ -931,6 +937,12 @@ public Task UnsubscribeFromResourceAsync(string uri, RequestOptions? options = n /// The result of the request. /// is . /// The request failed or the server returned an error response. + /// + /// The 2026-07-28 protocol revision (SEP-2575) removed resources/unsubscribe in favor of + /// with resourceSubscriptions. On a session that + /// negotiated that revision or later, this method throws an with + /// . + /// public Task UnsubscribeFromResourceAsync( UnsubscribeRequestParams requestParams, CancellationToken cancellationToken = default) diff --git a/src/ModelContextProtocol.Core/Client/McpClient.cs b/src/ModelContextProtocol.Core/Client/McpClient.cs index 6107201f2..67bb21a8d 100644 --- a/src/ModelContextProtocol.Core/Client/McpClient.cs +++ b/src/ModelContextProtocol.Core/Client/McpClient.cs @@ -29,14 +29,16 @@ protected McpClient() /// /// /// This property provides identification details about the connected server, including its name and version. - /// It is populated during the initialization handshake and is available after a successful connection. + /// It is populated during the initialization handshake or from server/discover result metadata. /// /// /// This information can be useful for logging, debugging, compatibility checks, and displaying server /// information to users. /// /// - /// The client is not connected. + /// + /// The client is not connected, or the server omitted the optional server identity metadata. + /// public abstract Implementation ServerInfo { get; } /// diff --git a/src/ModelContextProtocol.Core/Client/McpClientImpl.cs b/src/ModelContextProtocol.Core/Client/McpClientImpl.cs index 07a9f2ea3..07dc0d551 100644 --- a/src/ModelContextProtocol.Core/Client/McpClientImpl.cs +++ b/src/ModelContextProtocol.Core/Client/McpClientImpl.cs @@ -170,7 +170,8 @@ private void RegisterHandlers(McpClientOptions options, NotificationHandlers not public override ServerCapabilities ServerCapabilities => _serverCapabilities ?? throw new InvalidOperationException("The client is not connected."); /// - public override Implementation ServerInfo => _serverInfo ?? throw new InvalidOperationException("The client is not connected."); + public override Implementation ServerInfo => _serverInfo ?? throw new InvalidOperationException( + "The client is not connected, or the connected server did not provide optional server identity metadata."); /// public override string? ServerInstructions => _serverInstructions; @@ -432,15 +433,19 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default) } else { + var discoveredServerInfo = GetServerInfoFromDiscover(discoverResult!); + if (_logger.IsEnabled(LogLevel.Information)) { LogServerCapabilitiesReceived(_endpointName, capabilities: JsonSerializer.Serialize(discoverResult!.Capabilities, McpJsonUtilities.JsonContext.Default.ServerCapabilities), - serverInfo: JsonSerializer.Serialize(discoverResult.ServerInfo, McpJsonUtilities.JsonContext.Default.Implementation)); + serverInfo: discoveredServerInfo is null + ? "(none)" + : JsonSerializer.Serialize(discoveredServerInfo, McpJsonUtilities.JsonContext.Default.Implementation)); } _serverCapabilities = discoverResult!.Capabilities; - _serverInfo = discoverResult.ServerInfo; + _serverInfo = discoveredServerInfo; _serverInstructions = discoverResult.Instructions; } @@ -484,6 +489,30 @@ async Task SendDiscoverAsync(string protocolVersion, Cancellatio LogClientConnected(_endpointName); } + /// + /// Resolves the server identity from a server/discover result. The 2026-07-28 revision carries + /// serverInfo in the result's _meta/io.modelcontextprotocol/serverInfo field rather than + /// the result body. Identity is optional, so a server that omits it yields . + /// + private static Implementation? GetServerInfoFromDiscover(DiscoverResult discoverResult) + { + if (discoverResult.Meta is { } meta && + meta.TryGetPropertyValue(MetaKeys.ServerInfo, out JsonNode? serverInfoNode)) + { + if (serverInfoNode is null) + { + throw new JsonException( + $"Discover result metadata '{MetaKeys.ServerInfo}' must contain a server implementation."); + } + + return JsonSerializer.Deserialize(serverInfoNode, McpJsonUtilities.JsonContext.Default.Implementation) + ?? throw new JsonException( + $"Discover result metadata '{MetaKeys.ServerInfo}' must contain a server implementation."); + } + + return null; + } + /// /// Performs the initialize handshake (initialize request + initialized notification), /// records the negotiated protocol version, and stores the server capabilities/info/instructions. diff --git a/src/ModelContextProtocol.Core/Client/McpClientTool.cs b/src/ModelContextProtocol.Core/Client/McpClientTool.cs index 6a378caa9..f9d353e8c 100644 --- a/src/ModelContextProtocol.Core/Client/McpClientTool.cs +++ b/src/ModelContextProtocol.Core/Client/McpClientTool.cs @@ -135,7 +135,7 @@ internal McpClientTool( // would lose that information. So, we only do the translation if there is no additional information to preserve. if (result.IsError is not true && result.StructuredContent is null && - result.Meta is not { Count: > 0 }) + !HasApplicationResultMetadata(result.Meta)) { switch (result.Content.Count) { @@ -150,6 +150,26 @@ result.StructuredContent is null && return JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult); } + private static bool HasApplicationResultMetadata(JsonObject? meta) + { + if (meta is null) + { + return false; + } + + foreach (var property in meta) + { + // Server identity is protocol metadata already exposed through McpClient.ServerInfo. + // It should not force an otherwise simple tool result into its JSON envelope. + if (!string.Equals(property.Key, MetaKeys.ServerInfo, StringComparison.Ordinal)) + { + return true; + } + } + + return false; + } + /// /// Invokes the tool on the server. /// diff --git a/src/ModelContextProtocol.Core/Protocol/DiscoverResult.cs b/src/ModelContextProtocol.Core/Protocol/DiscoverResult.cs index 6ab6cedf6..b178a3a98 100644 --- a/src/ModelContextProtocol.Core/Protocol/DiscoverResult.cs +++ b/src/ModelContextProtocol.Core/Protocol/DiscoverResult.cs @@ -31,12 +31,6 @@ public sealed class DiscoverResult : Result, ICacheableResult [JsonPropertyName("capabilities")] public required ServerCapabilities Capabilities { get; set; } - /// - /// Gets or sets information about the server implementation. - /// - [JsonPropertyName("serverInfo")] - public required Implementation ServerInfo { get; set; } - /// /// Gets or sets optional instructions describing how to use the server and its features. /// diff --git a/src/ModelContextProtocol.Core/Protocol/MetaKeys.cs b/src/ModelContextProtocol.Core/Protocol/MetaKeys.cs index 29db6f5ae..9605bab6b 100644 --- a/src/ModelContextProtocol.Core/Protocol/MetaKeys.cs +++ b/src/ModelContextProtocol.Core/Protocol/MetaKeys.cs @@ -24,6 +24,16 @@ public static class MetaKeys /// public const string ClientInfo = "io.modelcontextprotocol/clientInfo"; + /// + /// The metadata key used to identify the server software in a response's _meta field. + /// + /// + /// Introduced by the 2026-07-28 protocol revision. Servers SHOULD identify themselves by + /// carrying an under this key in every result's + /// _meta. + /// + public const string ServerInfo = "io.modelcontextprotocol/serverInfo"; + /// /// The metadata key used to declare client capabilities in a request's _meta field. /// diff --git a/src/ModelContextProtocol.Core/Server/McpServerImpl.cs b/src/ModelContextProtocol.Core/Server/McpServerImpl.cs index 0827ceb9f..f68aacdff 100644 --- a/src/ModelContextProtocol.Core/Server/McpServerImpl.cs +++ b/src/ModelContextProtocol.Core/Server/McpServerImpl.cs @@ -146,10 +146,12 @@ void Register(McpServerPrimitiveCollection? collection, ServerCapabilities.Resources.ListChanged = null; } - // And initialize the session. The built-in meta-reading filter runs ahead of any - // user-supplied incoming filters; see PrependMetaReadingFilter for what it records and why. + // And initialize the session. The built-in protocol metadata filters run ahead of any + // user-supplied message filters. var incomingMessageFilter = PrependMetaReadingFilter(BuildMessageFilterPipeline(options.Filters.Message.IncomingFilters)); - var outgoingMessageFilter = BuildMessageFilterPipeline(options.Filters.Message.OutgoingFilters); + var outgoingMessageFilter = PrependServerInfoFilter( + BuildMessageFilterPipeline(options.Filters.Message.OutgoingFilters), + options.ServerInfo ?? DefaultImplementation); _sessionHandler = new McpSessionHandler( isServer: true, @@ -169,12 +171,13 @@ void Register(McpServerPrimitiveCollection? collection, /// validates the per-request protocol version, before delegating to the user-supplied incoming filters. /// /// - /// Under the 2026-07-28 protocol revision (SEP-2575) there is no initialize handshake, so these values - /// MUST be populated per-request. Per-request client capabilities and client info are consumed request-scoped - /// by and are not read from server-wide state by request handlers. The - /// shared write below is best-effort and used only to derive the session endpoint - /// name for logging/telemetry. For initialize-handshake clients the per-request values are absent and the built-in - /// filter is a no-op (the values were captured during the initialize handler). + /// Under the 2026-07-28 protocol revision (SEP-2575) there is no initialize handshake, so the protocol + /// version and client capabilities MUST be populated per-request. Client info is optional. Per-request client + /// capabilities and client info are consumed request-scoped by and are + /// not read from server-wide state by request handlers. The shared write below is + /// best-effort and used only to derive the session endpoint name for logging/telemetry. For initialize-handshake + /// clients the per-request values are absent and the built-in filter is a no-op (the values were captured during + /// the initialize handler). /// private JsonRpcMessageFilter PrependMetaReadingFilter(JsonRpcMessageFilter inner) { @@ -204,9 +207,14 @@ private JsonRpcMessageFilter PrependMetaReadingFilter(JsonRpcMessageFilter inner // with an UnsupportedProtocolVersionError (-32022) carrying the supported list. if (!_supportedProtocolVersions.Contains(protocolVersion)) { + var supportedVersions = + hasProtocolVersionMeta && _perRequestMetadataProtocolVersions.Length > 0 ? + _perRequestMetadataProtocolVersions : + _supportedProtocolVersions; + throw new UnsupportedProtocolVersionException( requested: protocolVersion, - supported: _supportedProtocolVersions); + supported: supportedVersions); } if (McpProtocolVersions.RequiresPerRequestMetadata(protocolVersion)) @@ -214,7 +222,6 @@ private JsonRpcMessageFilter PrependMetaReadingFilter(JsonRpcMessageFilter inner ValidateRequiredPerRequestMetadata( protocolVersion, hasProtocolVersionMeta, - context.ClientInfo is not null, context.ClientCapabilities is not null); } else if (McpProtocolVersions.SupportsInitializeHandshake(protocolVersion)) @@ -293,7 +300,6 @@ private JsonRpcMessageFilter PrependMetaReadingFilter(JsonRpcMessageFilter inner private static void ValidateRequiredPerRequestMetadata( string protocolVersion, bool hasProtocolVersionMeta, - bool hasClientInfoMeta, bool hasClientCapabilitiesMeta) { if (!hasProtocolVersionMeta) @@ -301,10 +307,7 @@ private static void ValidateRequiredPerRequestMetadata( ThrowMissingPerRequestMetadata(protocolVersion, MetaKeys.ProtocolVersion); } - if (!hasClientInfoMeta) - { - ThrowMissingPerRequestMetadata(protocolVersion, MetaKeys.ClientInfo); - } + // clientInfo is optional: requests whose _meta omits it are served, not rejected. if (!hasClientCapabilitiesMeta) { @@ -344,8 +347,46 @@ request.Params is JsonObject paramsObj && paramsObj["_meta"] is JsonObject metaObj && metaObj.ContainsKey(key); + /// + /// Adds the server identity to every successful result on per-request-metadata protocol revisions. + /// The filter runs before application filters so they can inspect or intentionally remove the metadata. + /// + private JsonRpcMessageFilter PrependServerInfoFilter(JsonRpcMessageFilter inner, Implementation serverInfo) + { + JsonRpcMessageFilter serverInfoFilter = next => async (message, cancellationToken) => + { + if (message is JsonRpcResponse { Result: JsonObject result } && + McpProtocolVersions.RequiresPerRequestMetadata( + message.Context?.ProtocolVersion ?? _negotiatedProtocolVersion)) + { + if (result["_meta"] is not JsonObject meta) + { + meta = new JsonObject(); + result["_meta"] = meta; + } + + meta[MetaKeys.ServerInfo] = JsonSerializer.SerializeToNode( + serverInfo, + McpJsonUtilities.JsonContext.Default.Implementation); + } + + await next(message, cancellationToken).ConfigureAwait(false); + }; + + return next => serverInfoFilter(inner(next)); + } + private void ValidateInitializeRequestBoundary(JsonRpcRequest request) { + // Per-request-metadata revisions (SEP-2575) removed the initialize handshake entirely: + // the request is for a method the server does not implement on that revision. + if (McpProtocolVersions.RequiresPerRequestMetadata(request.Context?.ProtocolVersion)) + { + throw new McpProtocolException( + $"Method '{RequestMethods.Initialize}' is not available on protocol version '{request.Context?.ProtocolVersion}'. Use '{RequestMethods.ServerDiscover}' and per-request metadata instead.", + McpErrorCode.MethodNotFound); + } + if (request.Context?.ProtocolVersion is { } protocolVersion && !McpProtocolVersions.SupportsInitializeHandshake(protocolVersion)) { @@ -415,14 +456,32 @@ request.Method is RequestMethods.SubscriptionsListen McpErrorCode.MethodNotFound); } - if (usesPerRequestMetadata && request.Method == RequestMethods.LoggingSetLevel) + if (usesPerRequestMetadata && + request.Method is RequestMethods.Ping or RequestMethods.LoggingSetLevel + or RequestMethods.ResourcesSubscribe or RequestMethods.ResourcesUnsubscribe) { + var replacement = GetRemovedMethodReplacementHint(request.Method); throw new McpProtocolException( - $"The method '{RequestMethods.LoggingSetLevel}' is not available on protocol version '{request.Context?.ProtocolVersion ?? NegotiatedProtocolVersion}'. Use per-request _meta/{MetaKeys.LogLevel} instead.", + $"The method '{request.Method}' is not available on protocol version '{request.Context?.ProtocolVersion ?? NegotiatedProtocolVersion}'." + + (replacement is null ? "" : $" {replacement}"), McpErrorCode.MethodNotFound); } } + /// + /// Returns guidance on the per-request-metadata replacement for a method that SEP-2575 removed, + /// or when the method has no direct replacement. Surfaced in the + /// error so a client that still calls the legacy RPC + /// (for example resources/subscribe) learns how to migrate. + /// + private static string? GetRemovedMethodReplacementHint(string method) => method switch + { + RequestMethods.LoggingSetLevel => $"Use the per-request '_meta/{MetaKeys.LogLevel}' field instead.", + RequestMethods.ResourcesSubscribe or RequestMethods.ResourcesUnsubscribe => + $"Use '{RequestMethods.SubscriptionsListen}' with 'resourceSubscriptions' instead.", + _ => null, + }; + /// public override string? SessionId => _sessionTransport.SessionId; @@ -636,7 +695,6 @@ private void ConfigureDiscover(McpServerOptions options) { SupportedVersions = [.. _perRequestMetadataProtocolVersions], Capabilities = ServerCapabilities ?? new(), - ServerInfo = options.ServerInfo ?? DefaultImplementation, Instructions = options.ServerInstructions, // Spec PR #2855 makes ttlMs and cacheScope required on DiscoverResult. Default to // the safest values (immediately stale, not shareable) so existing servers keep diff --git a/src/ModelContextProtocol.Core/Server/McpServerOptions.cs b/src/ModelContextProtocol.Core/Server/McpServerOptions.cs index f3d9b5f74..2a26868a1 100644 --- a/src/ModelContextProtocol.Core/Server/McpServerOptions.cs +++ b/src/ModelContextProtocol.Core/Server/McpServerOptions.cs @@ -14,7 +14,8 @@ public sealed class McpServerOptions /// Gets or sets information about this server implementation, including its name and version. /// /// - /// This information is sent to the client during initialization or discovery to identify the server. + /// This information is sent in the initialization result on handshake-based protocol revisions and in + /// every successful result's metadata on per-request-metadata revisions. /// It's displayed in client logs and can be used for debugging and compatibility checks. /// public Implementation? ServerInfo { get; set; } diff --git a/src/ModelContextProtocol.Core/Server/StreamableHttpPostTransport.cs b/src/ModelContextProtocol.Core/Server/StreamableHttpPostTransport.cs index ed8c3293a..95411f7e2 100644 --- a/src/ModelContextProtocol.Core/Server/StreamableHttpPostTransport.cs +++ b/src/ModelContextProtocol.Core/Server/StreamableHttpPostTransport.cs @@ -15,7 +15,8 @@ internal sealed partial class StreamableHttpPostTransport( StreamableHttpServerTransport parentTransport, Stream responseStream, CancellationToken sessionCancellationToken, - ILogger logger) : ITransport + ILogger logger, + Func? onResponseStarting = null) : ITransport { private readonly SemaphoreSlim _messageLock = new(1, 1); private readonly TaskCompletionSource _httpResponseTcs = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -29,6 +30,7 @@ internal sealed partial class StreamableHttpPostTransport( private RequestId _pendingRequest; private bool _finalResponseMessageSent; private bool _httpResponseCompleted; + private bool _httpResponseStarted; public ChannelReader MessageReader => throw new NotSupportedException("JsonRpcMessage.Context.RelatedTransport should only be used for sending messages."); @@ -50,8 +52,13 @@ public async ValueTask HandlePostAsync(JsonRpcMessage message, Cancellatio _pendingRequest = request.Id; message.Context.RelatedTransport = this; - // Invoke the initialize request handler if applicable. - if (request.Method == RequestMethods.Initialize) + // Invoke the initialize request handler if applicable. On a per-request-metadata + // protocol revision (2026-07-28+) initialize is a removed method: skip the eager + // params deserialization (whose required properties would throw on an arbitrary + // payload) and let the session's protocol boundary reject the request with + // Method not found. + if (request.Method == RequestMethods.Initialize && + !McpProtocolVersions.RequiresPerRequestMetadata(message.Context.ProtocolVersion)) { var initializeRequest = JsonSerializer.Deserialize(request.Params, McpJsonUtilities.JsonContext.Default.InitializeRequestParams); await parentTransport.HandleInitializeRequestAsync(initializeRequest).ConfigureAwait(false); @@ -69,32 +76,117 @@ public async ValueTask HandlePostAsync(JsonRpcMessage message, Cancellatio return false; } + CancellationTokenSource? deferredFlushCts = null; + Task? deferredFlushTask = null; + bool deferHeaderFlush = false; using (await _messageLock.LockAsync(cancellationToken).ConfigureAwait(false)) { var primingItem = await TryStartSseEventStreamAsync(_pendingRequest).ConfigureAwait(false); if (primingItem.HasValue) { + await NotifyResponseStartingAsync(firstMessage: null).ConfigureAwait(false); await _httpSseWriter.WriteAsync(primingItem.Value, cancellationToken).ConfigureAwait(false); } - else + else if (onResponseStarting is null) { // If there's no priming write, flush the stream to ensure HTTP response headers are // sent to the client now that the server is ready to process the request. // This prevents HttpClient timeout for long-running requests. await responseStream.FlushAsync(cancellationToken).ConfigureAwait(false); } + else + { + deferHeaderFlush = true; + } // Ensure that we've sent the priming event before processing the incoming request. await parentTransport.MessageWriter.WriteAsync(message, cancellationToken).ConfigureAwait(false); } - // Wait for the response to be written before returning from the handler. - // This keeps the HTTP response open until the final response message is sent. - await _httpResponseTcs.Task.WaitAsync(cancellationToken).ConfigureAwait(false); + if (deferHeaderFlush) + { + // Defer the flush (and the header commit it implies) so the callback can still choose + // the HTTP status line for an immediate JSON-RPC error. Start the bounded grace period + // only after the request has been queued for dispatch. + deferredFlushCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deferredFlushTask = DeferredHeaderFlushAsync(deferredFlushCts.Token); + } + + try + { + // Wait for the response to be written before returning from the handler. + // This keeps the HTTP response open until the final response message is sent. + await _httpResponseTcs.Task.WaitAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + if (deferredFlushCts is not null) + { + deferredFlushCts.Cancel(); + await deferredFlushTask!.ConfigureAwait(false); + deferredFlushCts.Dispose(); + } + } return true; } + /// + /// Bounds the deferred header flush: after a short grace window, flushes the response headers + /// if no response message has been written yet. Immediate rejections land well inside the + /// window, so the response-starting callback can still map their JSON-RPC error codes onto the + /// HTTP status line; a handler that runs longer commits the headers here so clients see them + /// promptly (long-running tool calls must not trip HttpClient's response timeout). + /// + private async Task DeferredHeaderFlushAsync(CancellationToken cancellationToken) + { + try + { + await Task.Delay(DeferredHeaderFlushGrace, cancellationToken).ConfigureAwait(false); + using var _ = await _messageLock.LockAsync(cancellationToken).ConfigureAwait(false); + if (!_httpResponseStarted && !_httpResponseCompleted) + { + await NotifyResponseStartingAsync(firstMessage: null).ConfigureAwait(false); + await responseStream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // The response was written or the request ended before the grace window elapsed. + } + catch (Exception ex) + { + // Surface the failure to the awaiting HandlePostAsync when possible. If the response + // future has already been resolved (the response started or completed on another path), + // TrySetException is a no-op, so log here to keep the deferred-flush failure diagnosable. + if (!_httpResponseTcs.TrySetException(ex)) + { + LogDeferredHeaderFlushFailed(ex); + } + } + } + + /// How long the response-header flush may be deferred waiting for the first response message. + internal static readonly TimeSpan DeferredHeaderFlushGrace = TimeSpan.FromMilliseconds(250); + + /// + /// Invokes the response-starting callback exactly once, immediately before the first write to + /// the HTTP response stream, so the HTTP application can still set the response status line. + /// + private async ValueTask NotifyResponseStartingAsync(JsonRpcMessage? firstMessage) + { + if (_httpResponseStarted) + { + return; + } + + _httpResponseStarted = true; + if (onResponseStarting is not null) + { + await onResponseStarting(firstMessage).ConfigureAwait(false); + } + } + public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default) { Throw.IfNull(message); @@ -130,6 +222,7 @@ public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken can try { + await NotifyResponseStartingAsync(message).ConfigureAwait(false); await _httpSseWriter.WriteAsync(item, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (!cancellationToken.IsCancellationRequested) @@ -173,6 +266,7 @@ public async ValueTask EnablePollingAsync(TimeSpan retryInterval, CancellationTo // Write to the response stream if it still exists. if (!_httpResponseCompleted) { + await NotifyResponseStartingAsync(firstMessage: null).ConfigureAwait(false); await _httpSseWriter.WriteAsync(primingItem, cancellationToken).ConfigureAwait(false); } @@ -248,4 +342,7 @@ public async ValueTask DisposeAsync() [LoggerMessage(Level = LogLevel.Warning, Message = "Failed to dispose SSE event stream writer.")] private partial void LogStoreStreamDisposalFailed(Exception exception); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Failed to flush deferred Streamable HTTP response headers.")] + private partial void LogDeferredHeaderFlushFailed(Exception exception); } diff --git a/src/ModelContextProtocol.Core/Server/StreamableHttpServerTransport.cs b/src/ModelContextProtocol.Core/Server/StreamableHttpServerTransport.cs index 131c836dc..f143eaaa7 100644 --- a/src/ModelContextProtocol.Core/Server/StreamableHttpServerTransport.cs +++ b/src/ModelContextProtocol.Core/Server/StreamableHttpServerTransport.cs @@ -125,7 +125,7 @@ public async ValueTask HandleInitializeRequestAsync(InitializeRequestParams? ini /// to the SSE response stream until cancellation is requested or the transport is disposed. /// /// The response stream to write MCP JSON-RPC messages as SSE events to. - /// The to monitor for cancellation requests. The default is . + /// The to monitor for cancellation requests. /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream. /// is . /// @@ -207,12 +207,39 @@ public async Task HandleGetRequestAsync(Stream sseResponseStream, CancellationTo /// If an authenticated sent the message, that can be included in the . /// No other part of the context should be set. /// - public async Task HandlePostRequestAsync(JsonRpcMessage message, Stream responseStream, CancellationToken cancellationToken = default) + public Task HandlePostRequestAsync(JsonRpcMessage message, Stream responseStream, CancellationToken cancellationToken = default) + => HandlePostRequestAsync(message, responseStream, onResponseStarting: null, cancellationToken); + + /// + /// Handles a Streamable HTTP POST request, processing the JSON-RPC message and writing any + /// JSON-RPC responses to the response stream. + /// This overload additionally reports the first JSON-RPC message written to the response via + /// , before any response bytes are written, so the HTTP + /// application can still choose the response status line (SEP-2575 maps some JSON-RPC error + /// codes to HTTP statuses). When is provided, the eager + /// response-header flush that normally precedes request processing is deferred until that first + /// message; the callback receives when the first write is not a JSON-RPC + /// message (e.g. a resumability priming event). + /// The status line can only be influenced by the FIRST write: when a handler streams a + /// notification (e.g. progress) before failing, or runs past the transport's bounded + /// header-flush grace window, the status is already committed and a later JSON-RPC error + /// rides the committed status. + /// + /// The JSON-RPC message to process. + /// The response stream to write any JSON-RPC responses to. + /// Callback invoked once, immediately before the first write to . + /// The to monitor for cancellation requests. The default is . + /// + /// if data was written to the response body. + /// if nothing was written because the request body did not contain any messages to respond to. + /// + /// or is . + public async Task HandlePostRequestAsync(JsonRpcMessage message, Stream responseStream, Func? onResponseStarting, CancellationToken cancellationToken) { Throw.IfNull(message); Throw.IfNull(responseStream); - var postTransport = new StreamableHttpPostTransport(this, responseStream, _transportDisposedCts.Token, _logger); + var postTransport = new StreamableHttpPostTransport(this, responseStream, _transportDisposedCts.Token, _logger, onResponseStarting); using var postCts = CancellationTokenSource.CreateLinkedTokenSource(_transportDisposedCts.Token, cancellationToken); await using (postTransport.ConfigureAwait(false)) { diff --git a/tests/ModelContextProtocol.AspNetCore.Tests/July2026ProtocolHttpFallbackTests.cs b/tests/ModelContextProtocol.AspNetCore.Tests/July2026ProtocolHttpFallbackTests.cs index 12bae02bb..599bdd9a8 100644 --- a/tests/ModelContextProtocol.AspNetCore.Tests/July2026ProtocolHttpFallbackTests.cs +++ b/tests/ModelContextProtocol.AspNetCore.Tests/July2026ProtocolHttpFallbackTests.cs @@ -324,7 +324,10 @@ await StartServerAsync(async context => { SupportedVersions = [McpProtocolVersions.July2026ProtocolVersion], Capabilities = new ServerCapabilities(), - ServerInfo = new Implementation { Name = "bad-per-request-metadata-server", Version = "1.0" }, + Meta = new JsonObject + { + [MetaKeys.ServerInfo] = JsonSerializer.SerializeToNode(new Implementation { Name = "bad-per-request-metadata-server", Version = "1.0" }, McpJsonUtilities.DefaultOptions), + }, TimeToLive = TimeSpan.Zero, CacheScope = CacheScope.Private, }, McpJsonUtilities.DefaultOptions), @@ -394,7 +397,10 @@ await StartServerAsync(async context => { SupportedVersions = [McpProtocolVersions.July2026ProtocolVersion], Capabilities = new ServerCapabilities(), - ServerInfo = new Implementation { Name = "per-request-metadata-server", Version = "1.0" }, + Meta = new JsonObject + { + [MetaKeys.ServerInfo] = JsonSerializer.SerializeToNode(new Implementation { Name = "per-request-metadata-server", Version = "1.0" }, McpJsonUtilities.DefaultOptions), + }, TimeToLive = TimeSpan.Zero, CacheScope = CacheScope.Private, }, McpJsonUtilities.DefaultOptions), diff --git a/tests/ModelContextProtocol.AspNetCore.Tests/RawHttpConformanceTests.cs b/tests/ModelContextProtocol.AspNetCore.Tests/RawHttpConformanceTests.cs index f5f848e06..8520f929c 100644 --- a/tests/ModelContextProtocol.AspNetCore.Tests/RawHttpConformanceTests.cs +++ b/tests/ModelContextProtocol.AspNetCore.Tests/RawHttpConformanceTests.cs @@ -32,7 +32,8 @@ private async Task StartAsync(string? protocolVersion = null) options.ProtocolVersion = protocolVersion; }) .WithHttpTransport() - .WithTools([McpServerTool.Create((string text) => $"echo:{text}", new() { Name = "echo" })]); + .WithTools([McpServerTool.Create((string text) => $"echo:{text}", new() { Name = "echo" })]) + .WithTools(); _app = Builder.Build(); _app.MapMcp(); @@ -106,6 +107,9 @@ public async Task July2026ToolsCall_WithFullMeta_Succeeds_200() Assert.Equal(HttpStatusCode.OK, response.StatusCode); var json = await ReadJsonResponseAsync(response, TestContext.Current.CancellationToken); Assert.Equal("echo:hi", json["result"]!["content"]![0]!["text"]!.GetValue()); + Assert.Equal( + nameof(RawHttpConformanceTests), + json["result"]!["_meta"]![MetaKeys.ServerInfo]!["name"]!.GetValue()); // Per SEP-2567, starting with the 2026-07-28 protocol revision Streamable HTTP no longer // supports sessions: the server MUST NOT issue a Mcp-Session-Id. @@ -134,6 +138,73 @@ public async Task ServerDiscover_RawPost_ReturnsDiscoverResult() Assert.Equal(JsonValueKind.Number, json["result"]!["ttlMs"]!.GetValueKind()); Assert.Equal(0, json["result"]!["ttlMs"]!.GetValue()); Assert.Equal("private", json["result"]!["cacheScope"]!.GetValue()); + Assert.Null(json["result"]!["serverInfo"]); + Assert.Equal( + nameof(RawHttpConformanceTests), + json["result"]!["_meta"]![MetaKeys.ServerInfo]!["name"]!.GetValue()); + } + + [Fact] + public async Task July2026Post_UnknownMethod_Returns404_WithMethodNotFound() + { + await StartAsync(); + + var body = @"{""jsonrpc"":""2.0"",""id"":17,""method"":""unknown/method"",""params"":{" + July2026ProtocolMetaFragment() + "}}"; + + using var request = new HttpRequestMessage(HttpMethod.Post, "") { Content = JsonContent(body) }; + request.Headers.Add(ProtocolVersionHeader, McpProtocolVersions.July2026ProtocolVersion); + request.Headers.Add("Mcp-Method", "unknown/method"); + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + var json = await ReadJsonResponseAsync(response, TestContext.Current.CancellationToken); + Assert.Equal(17, json["id"]!.GetValue()); + Assert.Equal((int)McpErrorCode.MethodNotFound, json["error"]!["code"]!.GetValue()); + } + + [Theory] + [InlineData("initialize")] + [InlineData("ping")] + [InlineData("logging/setLevel")] + [InlineData("resources/subscribe")] + [InlineData("resources/unsubscribe")] + public async Task July2026Post_RemovedMethod_Returns404_WithMethodNotFound(string method) + { + await StartAsync(); + + var body = @"{""jsonrpc"":""2.0"",""id"":18,""method"":""" + method + + @""",""params"":{" + July2026ProtocolMetaFragment() + "}}"; + + using var request = new HttpRequestMessage(HttpMethod.Post, "") { Content = JsonContent(body) }; + request.Headers.Add(ProtocolVersionHeader, McpProtocolVersions.July2026ProtocolVersion); + request.Headers.Add("Mcp-Method", method); + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + var json = await ReadJsonResponseAsync(response, TestContext.Current.CancellationToken); + Assert.Equal(18, json["id"]!.GetValue()); + Assert.Equal((int)McpErrorCode.MethodNotFound, json["error"]!["code"]!.GetValue()); + } + + [Fact] + public async Task July2026Post_MissingRequiredCapability_Returns400() + { + await StartAsync(); + + var body = + @"{""jsonrpc"":""2.0"",""id"":19,""method"":""tools/call"",""params"":{""name"":""requires_sampling"",""arguments"":{}," + + July2026ProtocolMetaFragment() + "}}"; + + using var request = new HttpRequestMessage(HttpMethod.Post, "") { Content = JsonContent(body) }; + request.Headers.Add(ProtocolVersionHeader, McpProtocolVersions.July2026ProtocolVersion); + request.Headers.Add("Mcp-Method", "tools/call"); + request.Headers.Add("Mcp-Name", "requires_sampling"); + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + var json = await ReadJsonResponseAsync(response, TestContext.Current.CancellationToken); + Assert.Equal(19, json["id"]!.GetValue()); + Assert.Equal((int)McpErrorCode.MissingRequiredClientCapability, json["error"]!["code"]!.GetValue()); } [Fact] @@ -179,7 +250,7 @@ public async Task July2026Post_WithUnsupportedProtocolVersionHeader_Returns400_W Assert.NotNull(data); Assert.Equal("9999-99-99", data!["requested"]!.GetValue()); var supported = data["supported"]!.AsArray().Select(n => n!.GetValue()).ToList(); - Assert.Contains(McpProtocolVersions.July2026ProtocolVersion, supported); + Assert.Equal([McpProtocolVersions.July2026ProtocolVersion], supported); } [Fact] @@ -258,7 +329,7 @@ public async Task July2026Post_WithServerPinnedToInitializeHandshakeVersion_Retu } [Fact] - public async Task July2026Post_MissingBodyProtocolVersion_ReturnsHeaderMismatch_Minus32020() + public async Task July2026Post_MissingBodyProtocolVersion_ReturnsInvalidParams_Minus32602() { await StartAsync(); @@ -269,9 +340,12 @@ public async Task July2026Post_MissingBodyProtocolVersion_ReturnsHeaderMismatch_ request.Headers.Add("Mcp-Method", "server/discover"); using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + // A missing (rather than mismatched) _meta protocol version is an Invalid params rejection + // per SEP-2575; -32020 HeaderMismatch is reserved for values present on both sides that + // disagree. Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); var json = await ReadJsonResponseAsync(response, TestContext.Current.CancellationToken); - Assert.Equal((int)McpErrorCode.HeaderMismatch, json["error"]!["code"]!.GetValue()); + Assert.Equal((int)McpErrorCode.InvalidParams, json["error"]!["code"]!.GetValue()); Assert.Contains(MetaKeys.ProtocolVersion, json["error"]!["message"]!.GetValue(), StringComparison.Ordinal); } @@ -372,4 +446,64 @@ public async Task GetEndpoint_NotMapped_UnderDefaultStatelessConfiguration_Retur // McpEndpointRouteBuilderExtensions only maps GET when Stateless == false. Assert.Equal(HttpStatusCode.MethodNotAllowed, response.StatusCode); } + + [Fact] + public async Task July2026Post_MissingClientCapabilities_Returns400_WithInvalidParams() + { + await StartAsync(); + + var body = + @"{""jsonrpc"":""2.0"",""id"":20,""method"":""server/discover"",""params"":{""_meta"":{" + + @"""io.modelcontextprotocol/protocolVersion"":""" + McpProtocolVersions.July2026ProtocolVersion + @"""}}}"; + + using var request = new HttpRequestMessage(HttpMethod.Post, "") { Content = JsonContent(body) }; + request.Headers.Add(ProtocolVersionHeader, McpProtocolVersions.July2026ProtocolVersion); + request.Headers.Add("Mcp-Method", "server/discover"); + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + var json = await ReadJsonResponseAsync(response, TestContext.Current.CancellationToken); + Assert.Equal(20, json["id"]!.GetValue()); + Assert.Equal((int)McpErrorCode.InvalidParams, json["error"]!["code"]!.GetValue()); + Assert.Contains(MetaKeys.ClientCapabilities, json["error"]!["message"]!.GetValue(), StringComparison.Ordinal); + } + + [Theory] + [InlineData("5")] + [InlineData("\"caps\"")] + [InlineData("[]")] + [InlineData("true")] + public async Task July2026Post_MalformedClientCapabilities_Returns400_WithInvalidParams(string clientCapabilitiesJson) + { + await StartAsync(); + + var body = + @"{""jsonrpc"":""2.0"",""id"":21,""method"":""server/discover"",""params"":{""_meta"":{" + + @"""io.modelcontextprotocol/protocolVersion"":""" + McpProtocolVersions.July2026ProtocolVersion + @"""," + + @"""io.modelcontextprotocol/clientInfo"":{""name"":""raw"",""version"":""1.0""}," + + @"""io.modelcontextprotocol/clientCapabilities"":" + clientCapabilitiesJson + "}}}"; + + using var request = new HttpRequestMessage(HttpMethod.Post, "") { Content = JsonContent(body) }; + request.Headers.Add(ProtocolVersionHeader, McpProtocolVersions.July2026ProtocolVersion); + request.Headers.Add("Mcp-Method", "server/discover"); + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + + // A present-but-wrong-shape clientCapabilities must be rejected up front with -32602 / 400, + // not surface later as a generic internal error on a 200 response. + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + var json = await ReadJsonResponseAsync(response, TestContext.Current.CancellationToken); + Assert.Equal(21, json["id"]!.GetValue()); + Assert.Equal((int)McpErrorCode.InvalidParams, json["error"]!["code"]!.GetValue()); + Assert.Contains(MetaKeys.ClientCapabilities, json["error"]!["message"]!.GetValue(), StringComparison.Ordinal); + } + + [McpServerToolType] + private sealed class CapabilityTools + { + [McpServerTool(Name = "requires_sampling")] + public static string RequiresSampling() => + throw new MissingRequiredClientCapabilityException( + new ClientCapabilities { Sampling = new() }, + "sampling capability required but not declared by client"); + } } diff --git a/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpClientConformanceTests.cs b/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpClientConformanceTests.cs index 366053fcd..649286b09 100644 --- a/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpClientConformanceTests.cs +++ b/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpClientConformanceTests.cs @@ -766,7 +766,10 @@ private async Task StartHeaderCapturingServer( ["io.modelcontextprotocol/tasks"] = new JsonObject(), }, }, - ServerInfo = new Implementation { Name = "header-capture", Version = "1.0" }, + Meta = new JsonObject + { + [MetaKeys.ServerInfo] = JsonSerializer.SerializeToNode(new Implementation { Name = "header-capture", Version = "1.0" }, McpJsonUtilities.DefaultOptions), + }, TimeToLive = TimeSpan.Zero, CacheScope = CacheScope.Private, ResultType = "complete", diff --git a/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpServerConformanceTests.cs b/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpServerConformanceTests.cs index 3422405a6..dd051e4d3 100644 --- a/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpServerConformanceTests.cs +++ b/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpServerConformanceTests.cs @@ -1158,8 +1158,14 @@ private static InitializeResult AssertServerInfo(JsonRpcResponse rpcResponse) private static DiscoverResult AssertDiscoverServerInfo(JsonRpcResponse rpcResponse) { var discoverResult = AssertType(rpcResponse.Result); - Assert.Equal(nameof(StreamableHttpServerConformanceTests), discoverResult.ServerInfo.Name); - Assert.Equal("73", discoverResult.ServerInfo.Version); + + // Server identity is carried in the result _meta, not the discover body. + var serverInfoNode = discoverResult.Meta?[MetaKeys.ServerInfo]; + Assert.NotNull(serverInfoNode); + var serverInfo = JsonSerializer.Deserialize(serverInfoNode, McpJsonUtilities.DefaultOptions); + Assert.NotNull(serverInfo); + Assert.Equal(nameof(StreamableHttpServerConformanceTests), serverInfo.Name); + Assert.Equal("73", serverInfo.Version); return discoverResult; } diff --git a/tests/ModelContextProtocol.ConformanceClient/Program.cs b/tests/ModelContextProtocol.ConformanceClient/Program.cs index f9beea94a..82d720af7 100644 --- a/tests/ModelContextProtocol.ConformanceClient/Program.cs +++ b/tests/ModelContextProtocol.ConformanceClient/Program.cs @@ -321,6 +321,27 @@ } break; } + case "json-schema-ref-no-deref": + { + // SEP-2106: listing tools must not dereference network $refs in a tool's + // inputSchema — the scenario's canary endpoint observes any such fetch. + await mcpClient.ListToolsAsync(); + break; + } + case "sep-2322-client-request-state": + { + // SEP-2322 (MRTR): drive the client's input-required auto-loop. The mock + // inspects the raw tools/call params: requestState echoed byte-exact (and + // omitted when the server sent none), a fresh JSON-RPC id per retry, no + // MRTR params bleeding into the unrelated call, and a missing resultType + // parsing as a terminal (complete) result. + await mcpClient.ListToolsAsync(); + await mcpClient.CallToolAsync(toolName: "test_mrtr_echo_state", arguments: new Dictionary()); + await mcpClient.CallToolAsync(toolName: "test_mrtr_unrelated", arguments: new Dictionary()); + await mcpClient.CallToolAsync(toolName: "test_mrtr_no_state", arguments: new Dictionary()); + await mcpClient.CallToolAsync(toolName: "test_mrtr_no_result_type", arguments: new Dictionary()); + break; + } default: // No extra processing for other scenarios break; diff --git a/tests/ModelContextProtocol.ConformanceServer/Program.cs b/tests/ModelContextProtocol.ConformanceServer/Program.cs index 4c6c54f11..73f63821e 100644 --- a/tests/ModelContextProtocol.ConformanceServer/Program.cs +++ b/tests/ModelContextProtocol.ConformanceServer/Program.cs @@ -73,6 +73,7 @@ private static void ConfigureConformanceMcpServer( .WithTools() .WithTools() .WithTools() + .WithTools() .WithTools([ConformanceTools.CreateJsonSchema202012Tool()]) .WithRequestFilters(filters => filters.AddCallToolFilter(next => async (request, cancellationToken) => { diff --git a/tests/ModelContextProtocol.ConformanceServer/Tools/Sep2575DiagnosticTools.cs b/tests/ModelContextProtocol.ConformanceServer/Tools/Sep2575DiagnosticTools.cs new file mode 100644 index 000000000..b95ecdd24 --- /dev/null +++ b/tests/ModelContextProtocol.ConformanceServer/Tools/Sep2575DiagnosticTools.cs @@ -0,0 +1,62 @@ +using ModelContextProtocol; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using System.ComponentModel; + +namespace ConformanceServer.Tools; + +/// +/// Diagnostic tools exercised by the SEP-2575 server-stateless conformance scenario. Each +/// tool exists so the harness can observe a framework behavior (capability enforcement, response +/// stream discipline, per-request log gating) that plain application tools never trigger. +/// +[McpServerToolType] +public class Sep2575DiagnosticTools +{ + /// + /// Requires the client to have declared the sampling capability in the per-request + /// _meta/io.modelcontextprotocol/clientCapabilities. Used to verify the server rejects + /// undeclared-capability calls with MissingRequiredClientCapabilityError (-32021). + /// + [McpServerTool(Name = "test_missing_capability")] + [Description("Requires the sampling client capability; used to verify MissingRequiredClientCapabilityError (-32021) (SEP-2575)")] + public static string MissingCapability(RequestContext context) + { + if (context.Server.ClientCapabilities?.Sampling is not null) + { + return "Client declared the sampling capability; tool executed."; + } + + throw new MissingRequiredClientCapabilityException( + new ClientCapabilities { Sampling = new() }, + "sampling capability required but not declared by client"); + } + + /// + /// Returns a plain result. Per SEP-2575 the response stream must carry no independent top-level + /// JSON-RPC requests; a plain response trivially satisfies this. The scenario declares no + /// elicitation capability, so this tool must not initiate an elicitation. + /// + [McpServerTool(Name = "test_streaming_elicitation")] + [Description("Streams only result frames; used to verify response streams carry no independent JSON-RPC requests (SEP-2575)")] + public static string StreamingElicitation() + { + return "stream observed: result frames only, no top-level requests"; + } + + /// + /// Attempts to emit a log message through the client-logger pipeline, which gates on the + /// per-request _meta/io.modelcontextprotocol/logLevel. When the client did not opt in, + /// no notifications/message may be sent for the request. + /// + [McpServerTool(Name = "test_logging_tool")] + [Description("Attempts to emit a log message; the framework must drop it when the client did not set _meta.../logLevel (SEP-2575)")] + public static string LoggingTool(RequestContext context) + { +#pragma warning disable MCP9004 // AsClientLoggerProvider is deprecated with the legacy logging/setLevel flow but remains the gated client-log pipeline. + ILogger logger = context.Server.AsClientLoggerProvider().CreateLogger(nameof(Sep2575DiagnosticTools)); +#pragma warning restore MCP9004 + logger.LogInformation("test_logging_tool executed"); + return "Log attempted; framework gates on _meta.../logLevel."; + } +} diff --git a/tests/ModelContextProtocol.Tests/Client/July2026ProtocolConnectionTests.cs b/tests/ModelContextProtocol.Tests/Client/July2026ProtocolConnectionTests.cs index e5ae0474d..e6817574e 100644 --- a/tests/ModelContextProtocol.Tests/Client/July2026ProtocolConnectionTests.cs +++ b/tests/ModelContextProtocol.Tests/Client/July2026ProtocolConnectionTests.cs @@ -3,6 +3,7 @@ using ModelContextProtocol.Protocol; using ModelContextProtocol.Server; using System.Text.Json; +using System.Text.Json.Nodes; namespace ModelContextProtocol.Tests.Client; @@ -52,6 +53,39 @@ public async Task Client_RequestingInitializeHandshakeVersion_NegotiatesIt() Assert.NotEqual(McpProtocolVersions.July2026ProtocolVersion, client.NegotiatedProtocolVersion); } + [Fact] + public async Task Client_AllowsDiscoverResultWithoutServerInfo() + { + ConfigureDiscoverServerInfo(meta => meta.Remove(MetaKeys.ServerInfo)); + StartServer(); + + var options = new McpClientOptions { ProtocolVersion = McpProtocolVersions.July2026ProtocolVersion }; + await using var client = await CreateMcpClientForServer(options); + + Assert.Equal(McpProtocolVersions.July2026ProtocolVersion, client.NegotiatedProtocolVersion); + Assert.Throws(() => _ = client.ServerInfo); + } + + [Fact] + public async Task Client_RejectsMalformedDiscoverServerInfo() + { + ConfigureDiscoverServerInfo(meta => meta[MetaKeys.ServerInfo] = "invalid"); + StartServer(); + + var options = new McpClientOptions { ProtocolVersion = McpProtocolVersions.July2026ProtocolVersion }; + await Assert.ThrowsAsync(() => CreateMcpClientForServer(options)); + } + + [Fact] + public async Task Client_RejectsNullDiscoverServerInfo() + { + ConfigureDiscoverServerInfo(meta => meta[MetaKeys.ServerInfo] = null); + StartServer(); + + var options = new McpClientOptions { ProtocolVersion = McpProtocolVersions.July2026ProtocolVersion }; + await Assert.ThrowsAsync(() => CreateMcpClientForServer(options)); + } + [Fact] public async Task InitializeHandshakeClient_CannotCallServerDiscover() { @@ -86,4 +120,19 @@ public async Task ServerDiscover_IncludesJuly2026ProtocolVersion() Assert.Equal("complete", discoverResult.ResultType); Assert.Equal([McpProtocolVersions.July2026ProtocolVersion], discoverResult.SupportedVersions); } + + private void ConfigureDiscoverServerInfo(Action configure) + { + McpServerBuilder.WithMessageFilters(filters => filters.AddOutgoingFilter(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse { Result: JsonObject result } && + result["supportedVersions"] is not null && + result["_meta"] is JsonObject meta) + { + configure(meta); + } + + await next(context, cancellationToken); + })); + } } diff --git a/tests/ModelContextProtocol.Tests/Client/July2026ProtocolFallbackTests.cs b/tests/ModelContextProtocol.Tests/Client/July2026ProtocolFallbackTests.cs index 03f8f5b33..2cccd35b2 100644 --- a/tests/ModelContextProtocol.Tests/Client/July2026ProtocolFallbackTests.cs +++ b/tests/ModelContextProtocol.Tests/Client/July2026ProtocolFallbackTests.cs @@ -3,6 +3,7 @@ using ModelContextProtocol.Tests.Utils; using System.Diagnostics; using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading.Channels; namespace ModelContextProtocol.Tests.Client; @@ -351,7 +352,10 @@ private void HandleOutgoingMessage(JsonRpcMessage message) { SupportedVersions = [McpProtocolVersions.July2026ProtocolVersion], Capabilities = new ServerCapabilities(), - ServerInfo = new Implementation { Name = "per-request-metadata-test-server", Version = "1.0.0" }, + Meta = new JsonObject + { + [MetaKeys.ServerInfo] = JsonSerializer.SerializeToNode(new Implementation { Name = "per-request-metadata-test-server", Version = "1.0.0" }, McpJsonUtilities.DefaultOptions), + }, }, McpJsonUtilities.DefaultOptions), }); } diff --git a/tests/ModelContextProtocol.Tests/Client/McpClientCreationTests.cs b/tests/ModelContextProtocol.Tests/Client/McpClientCreationTests.cs index 48f4e66e1..c6f8016dd 100644 --- a/tests/ModelContextProtocol.Tests/Client/McpClientCreationTests.cs +++ b/tests/ModelContextProtocol.Tests/Client/McpClientCreationTests.cs @@ -4,6 +4,7 @@ using ModelContextProtocol.Tests.Utils; using System.IO.Pipelines; using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading.Channels; namespace ModelContextProtocol.Tests.Client; @@ -179,10 +180,13 @@ public virtual Task SendMessageAsync(JsonRpcMessage message, CancellationToken c { Capabilities = new ServerCapabilities(), SupportedVersions = [McpProtocolVersions.July2026ProtocolVersion], - ServerInfo = new Implementation + Meta = new JsonObject { - Name = "NopTransport", - Version = "1.0.0" + [MetaKeys.ServerInfo] = JsonSerializer.SerializeToNode(new Implementation + { + Name = "NopTransport", + Version = "1.0.0" + }, McpJsonUtilities.DefaultOptions), }, }, McpJsonUtilities.DefaultOptions), }); diff --git a/tests/ModelContextProtocol.Tests/Client/McpClientResourceSubscriptionTests.cs b/tests/ModelContextProtocol.Tests/Client/McpClientResourceSubscriptionTests.cs index 2ee3cec26..82a3bd9c2 100644 --- a/tests/ModelContextProtocol.Tests/Client/McpClientResourceSubscriptionTests.cs +++ b/tests/ModelContextProtocol.Tests/Client/McpClientResourceSubscriptionTests.cs @@ -19,6 +19,12 @@ protected override void ConfigureServices(ServiceCollection services, IMcpServer mcpServerBuilder.WithResources(); } + private Task CreateLegacyMcpClientForServer() => + CreateMcpClientForServer(new() + { + ProtocolVersion = McpProtocolVersions.November2025ProtocolVersion, + }); + [McpServerResourceType] private sealed class SubscribableResources { @@ -30,7 +36,7 @@ private sealed class SubscribableResources public async Task SubscribeToResourceAsync_WithHandler_ReceivesNotifications() { // Arrange - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateLegacyMcpClientForServer(); const string resourceUri = "test://resource/1"; var notificationReceived = new TaskCompletionSource(); @@ -61,7 +67,7 @@ await Server.SendNotificationAsync( public async Task SubscribeToResourceAsync_WithHandler_FiltersNotificationsByUri() { // Arrange - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateLegacyMcpClientForServer(); const string subscribedUri = "test://resource/1"; const string otherUri = "test://resource/2"; var notificationCount = 0; @@ -107,7 +113,7 @@ await Server.SendNotificationAsync( public async Task SubscribeToResourceAsync_WithHandler_DisposalUnsubscribes() { // Arrange - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateLegacyMcpClientForServer(); const string resourceUri = "test://resource/1"; var notificationCount = 0; @@ -148,7 +154,7 @@ await Server.SendNotificationAsync( public async Task SubscribeToResourceAsync_WithHandler_UriOverload_ReceivesNotifications() { // Arrange - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateLegacyMcpClientForServer(); var resourceUri = new Uri("test://resource/1"); var notificationReceived = new TaskCompletionSource(); @@ -179,7 +185,7 @@ await Server.SendNotificationAsync( public async Task SubscribeToResourceAsync_WithNullHandler_ThrowsArgumentNullException() { // Arrange - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateLegacyMcpClientForServer(); // Act & Assert await Assert.ThrowsAsync(async () => @@ -193,7 +199,7 @@ await client.SubscribeToResourceAsync( public async Task SubscribeToResourceAsync_WithNullUri_ThrowsArgumentNullException() { // Arrange - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateLegacyMcpClientForServer(); // Act & Assert await Assert.ThrowsAsync(async () => @@ -207,7 +213,7 @@ await client.SubscribeToResourceAsync( public async Task SubscribeToResourceAsync_WithEmptyUri_ThrowsArgumentException() { // Arrange - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateLegacyMcpClientForServer(); // Act & Assert await Assert.ThrowsAsync(async () => @@ -221,7 +227,7 @@ await client.SubscribeToResourceAsync( public async Task SubscribeToResourceAsync_MultipleSubscriptions_BothReceiveNotifications() { // Arrange - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateLegacyMcpClientForServer(); const string uri1 = "test://resource/1"; const string uri2 = "test://resource/2"; var notification1Received = new TaskCompletionSource(); @@ -278,7 +284,7 @@ await Task.WhenAll( public async Task SubscribeToResourceAsync_DisposalIsIdempotent() { // Arrange - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateLegacyMcpClientForServer(); const string resourceUri = "test://resource/1"; var subscription = await client.SubscribeToResourceAsync( @@ -299,7 +305,7 @@ public async Task SubscribeToResourceAsync_DisposalIsIdempotent() public async Task SubscribeToResourceAsync_MultipleHandlersSameUri_BothReceiveNotifications() { // Arrange - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateLegacyMcpClientForServer(); const string resourceUri = "test://resource/1"; var handler1Called = new TaskCompletionSource(); var handler2Called = new TaskCompletionSource(); diff --git a/tests/ModelContextProtocol.Tests/Client/MrtrIntegrationTests.cs b/tests/ModelContextProtocol.Tests/Client/MrtrIntegrationTests.cs index 70a9d1112..86a107fd9 100644 --- a/tests/ModelContextProtocol.Tests/Client/MrtrIntegrationTests.cs +++ b/tests/ModelContextProtocol.Tests/Client/MrtrIntegrationTests.cs @@ -195,7 +195,10 @@ public async Task LegacyRequestOnMrtrSession_LogsWarning() { SupportedVersions = new List { "2026-07-28" }, Capabilities = new ServerCapabilities(), - ServerInfo = new Implementation { Name = "MockMrtrServer", Version = "1.0" }, + Meta = new JsonObject + { + [MetaKeys.ServerInfo] = JsonSerializer.SerializeToNode(new Implementation { Name = "MockMrtrServer", Version = "1.0" }, McpJsonUtilities.DefaultOptions), + }, }, McpJsonUtilities.DefaultOptions), }; await WriteJsonRpcAsync(serverWriter, discoverResponse); @@ -445,7 +448,10 @@ public async Task IncompleteResultRetry_OmittingRequestState_StripsStaleStateFro { SupportedVersions = ["2026-07-28"], Capabilities = new ServerCapabilities { Tools = new() }, - ServerInfo = new Implementation { Name = "MrtrServer", Version = "1.0" } + Meta = new JsonObject + { + [MetaKeys.ServerInfo] = JsonSerializer.SerializeToNode(new Implementation { Name = "MrtrServer", Version = "1.0" }, McpJsonUtilities.DefaultOptions), + }, }, McpJsonUtilities.DefaultOptions), }; await WriteJsonRpcAsync(serverWriter, discoverResponse); diff --git a/tests/ModelContextProtocol.Tests/ClientIntegrationTests.cs b/tests/ModelContextProtocol.Tests/ClientIntegrationTests.cs index 9c63f12ce..d01f40a6f 100644 --- a/tests/ModelContextProtocol.Tests/ClientIntegrationTests.cs +++ b/tests/ModelContextProtocol.Tests/ClientIntegrationTests.cs @@ -277,6 +277,7 @@ public async Task SubscribeResource_Stdio() TaskCompletionSource tcs = new(); await using var client = await _fixture.CreateClientAsync(clientId, new() { + ProtocolVersion = McpProtocolVersions.November2025ProtocolVersion, Handlers = new() { NotificationHandlers = @@ -307,6 +308,7 @@ public async Task UnsubscribeResource_Stdio() TaskCompletionSource receivedNotification = new(); await using var client = await _fixture.CreateClientAsync(clientId, new() { + ProtocolVersion = McpProtocolVersions.November2025ProtocolVersion, Handlers = new() { NotificationHandlers = @@ -727,6 +729,7 @@ public async Task SubscribeToResourceAsync_WithRequestParams_Succeeds() TaskCompletionSource tcs = new(); await using var client = await _fixture.CreateClientAsync(clientId, new() { + ProtocolVersion = McpProtocolVersions.November2025ProtocolVersion, Handlers = new() { NotificationHandlers = @@ -756,6 +759,7 @@ public async Task UnsubscribeFromResourceAsync_WithRequestParams_Succeeds() TaskCompletionSource receivedNotification = new(); await using var client = await _fixture.CreateClientAsync(clientId, new() { + ProtocolVersion = McpProtocolVersions.November2025ProtocolVersion, Handlers = new() { NotificationHandlers = diff --git a/tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsRequestFilterTests.cs b/tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsRequestFilterTests.cs index d3de3a23e..3f6a4a349 100644 --- a/tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsRequestFilterTests.cs +++ b/tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsRequestFilterTests.cs @@ -256,7 +256,10 @@ public async Task AddCompleteFilter_Logs_When_Complete_Called() [Fact] public async Task AddSubscribeToResourcesFilter_Logs_When_SubscribeToResources_Called() { - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateMcpClientForServer(new() + { + ProtocolVersion = McpProtocolVersions.November2025ProtocolVersion, + }); await client.SubscribeToResourceAsync("test://resource/123", cancellationToken: TestContext.Current.CancellationToken); @@ -268,7 +271,10 @@ public async Task AddSubscribeToResourcesFilter_Logs_When_SubscribeToResources_C [Fact] public async Task AddUnsubscribeFromResourcesFilter_Logs_When_UnsubscribeFromResources_Called() { - await using McpClient client = await CreateMcpClientForServer(); + await using McpClient client = await CreateMcpClientForServer(new() + { + ProtocolVersion = McpProtocolVersions.November2025ProtocolVersion, + }); await client.UnsubscribeFromResourceAsync("test://resource/123", cancellationToken: TestContext.Current.CancellationToken); diff --git a/tests/ModelContextProtocol.Tests/Protocol/CacheableResultWarningTests.cs b/tests/ModelContextProtocol.Tests/Protocol/CacheableResultWarningTests.cs index 4a5873df6..20e55a782 100644 --- a/tests/ModelContextProtocol.Tests/Protocol/CacheableResultWarningTests.cs +++ b/tests/ModelContextProtocol.Tests/Protocol/CacheableResultWarningTests.cs @@ -292,7 +292,10 @@ private static async Task PerformHandshakeAsync( { SupportedVersions = [serverProtocolVersion], Capabilities = new ServerCapabilities(), - ServerInfo = new Implementation { Name = "MockServer", Version = "1.0" }, + Meta = new JsonObject + { + [MetaKeys.ServerInfo] = JsonSerializer.SerializeToNode(new Implementation { Name = "MockServer", Version = "1.0" }, McpJsonUtilities.DefaultOptions), + }, }, McpJsonUtilities.DefaultOptions), }, cancellationToken); } diff --git a/tests/ModelContextProtocol.Tests/Protocol/DiscoverProtocolTests.cs b/tests/ModelContextProtocol.Tests/Protocol/DiscoverProtocolTests.cs index 71afd8980..b225dd600 100644 --- a/tests/ModelContextProtocol.Tests/Protocol/DiscoverProtocolTests.cs +++ b/tests/ModelContextProtocol.Tests/Protocol/DiscoverProtocolTests.cs @@ -44,7 +44,6 @@ public static void DiscoverResult_SerializationRoundTrip_PreservesAllProperties( { Tools = new ToolsCapability { ListChanged = true }, }, - ServerInfo = new Implementation { Name = "test-server", Version = "2.0" }, Instructions = "Use this server for testing.", }; @@ -55,7 +54,6 @@ public static void DiscoverResult_SerializationRoundTrip_PreservesAllProperties( Assert.Equal(["2025-11-25", "2026-07-28"], deserialized.SupportedVersions); Assert.NotNull(deserialized.Capabilities.Tools); Assert.True(deserialized.Capabilities.Tools.ListChanged); - Assert.Equal("test-server", deserialized.ServerInfo.Name); Assert.Equal("Use this server for testing.", deserialized.Instructions); } @@ -66,7 +64,6 @@ public static void DiscoverResult_SerializationRoundTrip_WithMinimalProperties() { SupportedVersions = new List { "2026-07-28" }, Capabilities = new ServerCapabilities(), - ServerInfo = new Implementation { Name = "minimal-server", Version = "1.0" }, }; var json = JsonSerializer.Serialize(original, McpJsonUtilities.DefaultOptions); diff --git a/tests/ModelContextProtocol.Tests/Protocol/DiscoverResultCacheableTests.cs b/tests/ModelContextProtocol.Tests/Protocol/DiscoverResultCacheableTests.cs index 4a2d7e6df..0670f61b8 100644 --- a/tests/ModelContextProtocol.Tests/Protocol/DiscoverResultCacheableTests.cs +++ b/tests/ModelContextProtocol.Tests/Protocol/DiscoverResultCacheableTests.cs @@ -8,8 +8,8 @@ namespace ModelContextProtocol.Tests.Protocol; /// Targeted tests for the SEP-2549 caching hints (ttlMs and cacheScope) on /// . Spec PR #2855 promotes both fields to required on the discover /// response. has required CLR properties for -/// , , and -/// , which prevents reuse of the parameterized +/// and , +/// which prevents reuse of the parameterized /// helper (it instantiates via reflection). This file covers the /// same property-shape assertions for . /// @@ -19,7 +19,6 @@ public static class DiscoverResultCacheableTests { SupportedVersions = [McpProtocolVersions.November2025ProtocolVersion, McpProtocolVersions.July2026ProtocolVersion], Capabilities = new ServerCapabilities(), - ServerInfo = new Implementation { Name = "test-server", Version = "1.0" }, }; [Fact] diff --git a/tests/ModelContextProtocol.Tests/Server/NegotiatedProtocolVersionTests.cs b/tests/ModelContextProtocol.Tests/Server/NegotiatedProtocolVersionTests.cs index d3e6f5e69..d8cadeb61 100644 --- a/tests/ModelContextProtocol.Tests/Server/NegotiatedProtocolVersionTests.cs +++ b/tests/ModelContextProtocol.Tests/Server/NegotiatedProtocolVersionTests.cs @@ -82,7 +82,22 @@ public async Task PerRequestMetadata_RejectsInitializeHandshakeVersionBeforeInit } [Fact] - public async Task PerRequestMetadata_RejectsRequestMissingRequiredMetadata() + public async Task PerRequestMetadata_ServesRequestMissingClientInfo() + { + var ct = TestContext.Current.CancellationToken; + + // clientInfo is optional: a request whose _meta omits it is served. + var response = await RoundTripAsync( + id: 1, + McpProtocolVersions.July2026ProtocolVersion, + ct, + includeClientInfo: false); + + Assert.IsType(response); + } + + [Fact] + public async Task PerRequestMetadata_RejectsRequestMissingClientCapabilities() { var ct = TestContext.Current.CancellationToken; @@ -91,10 +106,10 @@ await RoundTripAsync( id: 1, McpProtocolVersions.July2026ProtocolVersion, ct, - includeClientInfo: false)); + includeClientCapabilities: false)); Assert.Equal((int)McpErrorCode.InvalidParams, error.Error.Code); - Assert.Contains(MetaKeys.ClientInfo, error.Error.Message, StringComparison.Ordinal); + Assert.Contains(MetaKeys.ClientCapabilities, error.Error.Message, StringComparison.Ordinal); } [Fact] @@ -176,25 +191,29 @@ public async Task SubscriptionsListen_WithInitializeProtocolVersion_IsRejected() Assert.Contains(RequestMethods.SubscriptionsListen, error.Error.Message, StringComparison.Ordinal); } - [Fact] - public async Task LoggingSetLevel_WithPerRequestMetadataProtocolVersion_IsRejected() + [Theory] + [InlineData("initialize")] + [InlineData("ping")] + [InlineData("logging/setLevel")] + [InlineData("resources/subscribe")] + [InlineData("resources/unsubscribe")] + public async Task RemovedMethod_WithPerRequestMetadataProtocolVersion_IsRejected(string method) { var ct = TestContext.Current.CancellationToken; var request = new JsonRpcRequest { Id = new RequestId(1), - Method = RequestMethods.LoggingSetLevel, + Method = method, Params = new JsonObject { - ["level"] = "info", ["_meta"] = PerRequestMetadata(), }, }; var error = Assert.IsType(await SendAndReceiveAsync(request, ct)); Assert.Equal((int)McpErrorCode.MethodNotFound, error.Error.Code); - Assert.Contains(RequestMethods.LoggingSetLevel, error.Error.Message, StringComparison.Ordinal); + Assert.Contains(method, error.Error.Message, StringComparison.Ordinal); } private async Task RoundTripAsync( diff --git a/tests/ModelContextProtocol.Tests/Server/RawStreamConformanceTests.cs b/tests/ModelContextProtocol.Tests/Server/RawStreamConformanceTests.cs index 5ece0f6b1..c068d227e 100644 --- a/tests/ModelContextProtocol.Tests/Server/RawStreamConformanceTests.cs +++ b/tests/ModelContextProtocol.Tests/Server/RawStreamConformanceTests.cs @@ -98,10 +98,10 @@ public async Task ServerDiscover_ReturnsSupportedVersionsIncludingJuly2026Protoc .ToList(); Assert.Contains(McpProtocolVersions.July2026ProtocolVersion, supportedVersions); - // Capabilities and serverInfo are mandatory in DiscoverResult per SEP-2575. + // Capabilities are mandatory in DiscoverResult; server identity is result metadata. Assert.NotNull(result["capabilities"]); - Assert.NotNull(result["serverInfo"]); - Assert.Equal("raw-conformance-server", result["serverInfo"]!["name"]!.GetValue()); + Assert.Null(result["serverInfo"]); + Assert.Equal("raw-conformance-server", result["_meta"]![MetaKeys.ServerInfo]!["name"]!.GetValue()); // Spec PR #2855 makes ttlMs and cacheScope required on DiscoverResult; the server emits the // safest defaults (immediately stale, not shareable) when the application hasn't customized. @@ -126,6 +126,7 @@ await SendAsync( var content = result!["content"]!.AsArray(); Assert.Single(content); Assert.Equal("echo:hello", content[0]!["text"]!.GetValue()); + Assert.Equal("raw-conformance-server", result["_meta"]![MetaKeys.ServerInfo]!["name"]!.GetValue()); } [Fact] @@ -146,7 +147,7 @@ await SendAsync( Assert.NotNull(data); Assert.Equal("9999-99-99", data!["requested"]!.GetValue()); var supported = data["supported"]!.AsArray().Select(n => n!.GetValue()).ToList(); - Assert.Contains(McpProtocolVersions.July2026ProtocolVersion, supported); + Assert.Equal([McpProtocolVersions.July2026ProtocolVersion], supported); } [Fact] @@ -161,6 +162,7 @@ public async Task InitializeHandshake_StillWorks_OnJuly2026ProtocolDefaultServer var result = response["result"]; Assert.NotNull(result); Assert.Equal("2025-11-25", result!["protocolVersion"]!.GetValue()); + Assert.Null(result["_meta"]?[MetaKeys.ServerInfo]); } [Fact] diff --git a/tests/ModelContextProtocol.Tests/Server/ResourceSubscriptionProtocolGatingTests.cs b/tests/ModelContextProtocol.Tests/Server/ResourceSubscriptionProtocolGatingTests.cs new file mode 100644 index 000000000..6024e296a --- /dev/null +++ b/tests/ModelContextProtocol.Tests/Server/ResourceSubscriptionProtocolGatingTests.cs @@ -0,0 +1,91 @@ +using Microsoft.Extensions.DependencyInjection; +using ModelContextProtocol.Client; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using System.ComponentModel; + +namespace ModelContextProtocol.Tests.Server; + +/// +/// Verifies that the legacy resources/subscribe and resources/unsubscribe RPCs are +/// gated by protocol version. SEP-2575 (the 2026-07-28 revision) removes them in favor of +/// subscriptions/listen with resourceSubscriptions; servers must respond with +/// -32601 MethodNotFound. Initialize-handshake protocol versions still support the legacy +/// RPCs per the spec. +/// +public sealed class ResourceSubscriptionProtocolGatingTests : ClientServerTestBase +{ + public ResourceSubscriptionProtocolGatingTests(ITestOutputHelper testOutputHelper) + : base(testOutputHelper, startServer: false) + { + } + + protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder) + { + mcpServerBuilder.WithResources(); + } + + [McpServerResourceType] + private sealed class SubscribableResources + { + [McpServerResource(UriTemplate = "test://resource/{id}"), Description("A subscribable test resource")] + public static string GetResource(string id) => $"Resource content: {id}"; + } + + [Fact] + public async Task Subscribe_OnJuly2026ProtocolSession_ReturnsMethodNotFound() + { + StartServer(); + await using var client = await CreateMcpClientForServer(new McpClientOptions + { + ProtocolVersion = McpProtocolVersions.July2026ProtocolVersion, + }); + + var ex = await Assert.ThrowsAsync(async () => + await client.SubscribeToResourceAsync( + new SubscribeRequestParams { Uri = "test://resource/1" }, + TestContext.Current.CancellationToken)); + + Assert.Equal(McpErrorCode.MethodNotFound, ex.ErrorCode); + // The rejection must point callers at the SEP-2575 replacement. + Assert.Contains(RequestMethods.SubscriptionsListen, ex.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task Unsubscribe_OnJuly2026ProtocolSession_ReturnsMethodNotFound() + { + StartServer(); + await using var client = await CreateMcpClientForServer(new McpClientOptions + { + ProtocolVersion = McpProtocolVersions.July2026ProtocolVersion, + }); + + var ex = await Assert.ThrowsAsync(async () => + await client.UnsubscribeFromResourceAsync( + new UnsubscribeRequestParams { Uri = "test://resource/1" }, + TestContext.Current.CancellationToken)); + + Assert.Equal(McpErrorCode.MethodNotFound, ex.ErrorCode); + Assert.Contains(RequestMethods.SubscriptionsListen, ex.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task Subscribe_OnInitializeHandshakeSession_StillSucceeds() + { + // Default server config; client pinned to 2025-11-25. + StartServer(); + await using var client = await CreateMcpClientForServer(new McpClientOptions + { + ProtocolVersion = McpProtocolVersions.November2025ProtocolVersion, + }); + + // Should complete without throwing on the initialize-handshake revision. + await client.SubscribeToResourceAsync( + new SubscribeRequestParams { Uri = "test://resource/1" }, + TestContext.Current.CancellationToken); + + await client.UnsubscribeFromResourceAsync( + new UnsubscribeRequestParams { Uri = "test://resource/1" }, + TestContext.Current.CancellationToken); + } +}