Skip to content

Commit cff1165

Browse files
author
Tarek Mahmoud Sayed
committed
Address review feedback for subscriptions/listen handler
- Normalize a null Notifications to empty in the custom-handler wrapper so a '{"notifications": null}' payload no longer NREs into a generic InternalError. - Decide the listChanged capability per response instead of clearing it in the constructor: initialize never advertises it for stateless servers, while server/discover advertises it when a custom SubscriptionsListenHandler can deliver it over the listen stream. - Add WithSubscriptionsListenHandler_Sets_Handler builder test. - Add stateless test covering listChanged advertisement and delivery over the held-open POST. - Remove the unnecessary McpServerToolType attribute from the ListenTools test type registered via WithTools<T>().
1 parent afe7ed1 commit cff1165

4 files changed

Lines changed: 161 additions & 14 deletions

File tree

‎src/ModelContextProtocol.Core/Server/McpServerImpl.cs‎

Lines changed: 65 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,11 @@ public McpServerImpl(ITransport transport, McpServerOptions options, ILoggerFact
117117
}
118118

119119
// A stateful session can push unsolicited list-changed notifications, so subscribe to the
120-
// collection change events. A stateless HTTP server cannot send unsolicited notifications, so
121-
// instead suppress the listChanged capability it would otherwise advertise.
120+
// collection change events. A stateless HTTP server cannot push unsolicited notifications; whether it
121+
// may still advertise the listChanged capability (over a custom subscriptions/listen stream to a
122+
// 2026-07-28+ client) is decided per response in GetAdvertisedCapabilities rather than cleared here,
123+
// because the same ServerCapabilities feeds both the legacy initialize handshake (which can never
124+
// deliver it) and server/discover (which can, given a custom handler).
122125
if (HasStatefulTransport())
123126
{
124127
Register(ServerOptions.ToolCollection, NotificationMethods.ToolListChangedNotification);
@@ -136,15 +139,6 @@ void Register<TPrimitive>(McpServerPrimitiveCollection<TPrimitive>? collection,
136139
}
137140
}
138141
}
139-
else
140-
{
141-
if (ServerCapabilities.Tools is not null)
142-
ServerCapabilities.Tools.ListChanged = null;
143-
if (ServerCapabilities.Prompts is not null)
144-
ServerCapabilities.Prompts.ListChanged = null;
145-
if (ServerCapabilities.Resources is not null)
146-
ServerCapabilities.Resources.ListChanged = null;
147-
}
148142

149143
// And initialize the session. The built-in protocol metadata filters run ahead of any
150144
// user-supplied message filters.
@@ -516,6 +510,46 @@ private void SetNegotiatedProtocolVersion(string protocolVersion)
516510
/// <inheritdoc/>
517511
public ServerCapabilities ServerCapabilities { get; }
518512

513+
/// <summary>
514+
/// Returns the <see cref="ServerCapabilities"/> to advertise in a specific response, suppressing the
515+
/// <c>listChanged</c> flags the server has no way to honor.
516+
/// </summary>
517+
/// <param name="listenStreamCanDeliverListChanged">
518+
/// <see langword="true"/> when the client this response targets can receive <c>*/list_changed</c>
519+
/// notifications over a <c>subscriptions/listen</c> stream.
520+
/// </param>
521+
/// <remarks>
522+
/// A stateless HTTP server has no session-wide channel to push unsolicited <c>*/list_changed</c>
523+
/// notifications. It can only deliver them over a <c>subscriptions/listen</c> stream, which requires both
524+
/// a 2026-07-28+ client (so the request is reachable at all) and a custom
525+
/// <see cref="McpServerHandlers.SubscriptionsListenHandler"/> to own that stream (the built-in stateless
526+
/// handler grants no notifications). When neither the transport is stateful nor that stream can carry
527+
/// them, the <c>listChanged</c> flags are dropped so the server never advertises a capability it cannot
528+
/// deliver. Everything else (for example <c>resources.subscribe</c>) is preserved.
529+
/// </remarks>
530+
private ServerCapabilities GetAdvertisedCapabilities(bool listenStreamCanDeliverListChanged)
531+
{
532+
if (HasStatefulTransport() || listenStreamCanDeliverListChanged)
533+
{
534+
return ServerCapabilities;
535+
}
536+
537+
// Copy onto a fresh instance so the shared ServerCapabilities keeps the authored listChanged flags;
538+
// server/discover with a custom listen handler may still advertise them.
539+
return new ServerCapabilities
540+
{
541+
Experimental = ServerCapabilities.Experimental,
542+
Logging = ServerCapabilities.Logging,
543+
Completions = ServerCapabilities.Completions,
544+
Extensions = ServerCapabilities.Extensions,
545+
Prompts = ServerCapabilities.Prompts is null ? null : new PromptsCapability { ListChanged = null },
546+
Resources = ServerCapabilities.Resources is { } resources
547+
? new ResourcesCapability { Subscribe = resources.Subscribe, ListChanged = null }
548+
: null,
549+
Tools = ServerCapabilities.Tools is null ? null : new ToolsCapability { ListChanged = null },
550+
};
551+
}
552+
519553
/// <inheritdoc />
520554
public override ClientCapabilities? ClientCapabilities => _clientCapabilities;
521555

@@ -667,7 +701,11 @@ private void ConfigureInitialize(McpServerOptions options)
667701
ProtocolVersion = negotiatedProtocolVersion,
668702
Instructions = options.ServerInstructions,
669703
ServerInfo = options.ServerInfo ?? DefaultImplementation,
670-
Capabilities = ServerCapabilities ?? new(),
704+
705+
// The initialize handshake only serves pre-2026-07-28 clients, which cannot open a
706+
// subscriptions/listen stream, so a stateless server has no way to deliver list-changed
707+
// notifications to them regardless of any custom handler.
708+
Capabilities = GetAdvertisedCapabilities(listenStreamCanDeliverListChanged: false),
671709

672710
// resultType is a 2026-07-28 result field. The initialize handshake is only available on
673711
// 2025-11-25 and earlier revisions (2026-07-28+ negotiate via server/discover and throw
@@ -694,7 +732,13 @@ private void ConfigureDiscover(McpServerOptions options)
694732
return new ValueTask<DiscoverResult>(new DiscoverResult
695733
{
696734
SupportedVersions = [.. _perRequestMetadataProtocolVersions],
697-
Capabilities = ServerCapabilities ?? new(),
735+
736+
// server/discover only serves 2026-07-28+ clients, which can open a subscriptions/listen
737+
// stream. A stateless server can therefore still deliver list-changed notifications if the
738+
// author supplied a custom handler to own that stream (the built-in stateless handler
739+
// grants nothing, so it cannot).
740+
Capabilities = GetAdvertisedCapabilities(
741+
listenStreamCanDeliverListChanged: options.Handlers.SubscriptionsListenHandler is not null),
698742
Instructions = options.ServerInstructions,
699743
// Spec PR #2855 makes ttlMs and cacheScope required on DiscoverResult. Default to
700744
// the safest values (immediately stale, not shareable) so existing servers keep
@@ -762,6 +806,14 @@ private void ConfigureSubscriptions(McpServerOptions options)
762806
McpErrorCode.MethodNotFound);
763807
}
764808

809+
// Notifications is 'required', but that only enforces presence during deserialization,
810+
// not non-nullness: a '{"notifications": null}' payload produces a non-null params object
811+
// with a null Notifications (DefaultOptions does not set RespectNullableAnnotations).
812+
// Normalize null to empty so a custom handler can dereference request.Params.Notifications
813+
// without an NRE, matching the built-in handler's request?.Notifications guard below.
814+
request.Params ??= new SubscriptionsListenRequestParams { Notifications = new() };
815+
request.Params.Notifications ??= new SubscriptionsListenNotifications();
816+
765817
return subscriptionsListenHandler(request, cancellationToken);
766818
},
767819
McpJsonUtilities.JsonContext.Default.SubscriptionsListenRequestParams,

‎tests/ModelContextProtocol.AspNetCore.Tests/StatelessServerTests.cs‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,89 @@ await client.SendRequestAsync(listenRequest, TestContext.Current.CancellationTok
465465
Assert.Equal(subscribedUri, Assert.IsType<JsonObject>(updated.Params)["uri"]?.GetValue<string>());
466466
}
467467

468+
[Fact]
469+
public async Task SubscriptionsListen_WithCustomHandler_InStatelessMode_AdvertisesAndStreamsListChanged()
470+
{
471+
// resources/updated rides on resources.subscribe, which is never suppressed, so it cannot prove the
472+
// listChanged capability is advertised. A custom SubscriptionsListenHandler gives a stateless server a
473+
// way to deliver */list_changed over the held-open POST, so server/discover (the only path a
474+
// 2026-07-28+ client uses) must advertise tools.listChanged rather than dropping it (issue #1662).
475+
Builder.Services.AddMcpServer()
476+
.WithHttpTransport(options =>
477+
{
478+
options.Stateless = true;
479+
})
480+
.WithTools([McpServerTool.Create(() => "result", new() { Name = "myTool" })])
481+
.WithSubscriptionsListenHandler(async (request, cancellationToken) =>
482+
{
483+
var subscriptionId = request.JsonRpcRequest.Id;
484+
485+
var ack = new JsonRpcNotification
486+
{
487+
Method = NotificationMethods.SubscriptionsAcknowledgedNotification,
488+
Params = JsonSerializer.SerializeToNode(
489+
new SubscriptionsAcknowledgedNotificationParams
490+
{
491+
Notifications = new SubscriptionsListenNotifications
492+
{
493+
ToolsListChanged = request.Params.Notifications.ToolsListChanged,
494+
},
495+
},
496+
McpJsonUtilities.DefaultOptions),
497+
};
498+
TagWithSubscriptionId(ack, subscriptionId);
499+
await request.Server.SendMessageAsync(ack, cancellationToken);
500+
501+
var listChanged = new JsonRpcNotification { Method = NotificationMethods.ToolListChangedNotification };
502+
TagWithSubscriptionId(listChanged, subscriptionId);
503+
await request.Server.SendMessageAsync(listChanged, cancellationToken);
504+
505+
return new EmptyResult();
506+
});
507+
508+
// Advertise tools.listChanged so the per-response capability decision has something to preserve.
509+
Builder.Services.Configure<McpServerOptions>(options =>
510+
{
511+
options.Capabilities ??= new();
512+
options.Capabilities.Tools ??= new();
513+
options.Capabilities.Tools.ListChanged = true;
514+
});
515+
516+
_app = Builder.Build();
517+
_app.MapMcp();
518+
await _app.StartAsync(TestContext.Current.CancellationToken);
519+
520+
HttpClient.DefaultRequestHeaders.Accept.Add(new("application/json"));
521+
HttpClient.DefaultRequestHeaders.Accept.Add(new("text/event-stream"));
522+
523+
await using var client = await ConnectMcpClientAsync();
524+
525+
// The stateless server can now deliver tools/list_changed over the custom listen stream, so the
526+
// capability must survive on the server/discover response instead of being cleared.
527+
Assert.True(client.ServerCapabilities.Tools?.ListChanged);
528+
529+
var listChangedChannel = Channel.CreateUnbounded<JsonRpcNotification>();
530+
await using var listChangedReg = client.RegisterNotificationHandler(NotificationMethods.ToolListChangedNotification,
531+
(notification, _) => { listChangedChannel.Writer.TryWrite(notification); return default; });
532+
533+
var listenRequest = new JsonRpcRequest
534+
{
535+
Method = RequestMethods.SubscriptionsListen,
536+
Params = JsonSerializer.SerializeToNode(
537+
new SubscriptionsListenRequestParams
538+
{
539+
Notifications = new SubscriptionsListenNotifications { ToolsListChanged = true },
540+
},
541+
McpJsonUtilities.DefaultOptions),
542+
};
543+
544+
await client.SendRequestAsync(listenRequest, TestContext.Current.CancellationToken)
545+
.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken);
546+
547+
var listChangedNotification = await listChangedChannel.Reader.ReadAsync(TestContext.Current.CancellationToken);
548+
Assert.NotNull(GetSubscriptionId(listChangedNotification));
549+
}
550+
468551
private static string? GetSubscriptionId(JsonRpcNotification notification)
469552
=> ((notification.Params as JsonObject)?["_meta"] as JsonObject)?[MetaKeys.SubscriptionId]?.ToJsonString();
470553

‎tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsHandlerTests.cs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,4 +147,17 @@ public void WithUnsubscribeFromResourcesHandler_Sets_Handler()
147147

148148
Assert.Equal(handler, options.Handlers.UnsubscribeFromResourcesHandler);
149149
}
150+
151+
[Fact]
152+
public void WithSubscriptionsListenHandler_Sets_Handler()
153+
{
154+
McpRequestHandler<SubscriptionsListenRequestParams, EmptyResult> handler = async (context, token) => new EmptyResult();
155+
156+
_builder.Object.WithSubscriptionsListenHandler(handler);
157+
158+
var serviceProvider = _services.BuildServiceProvider();
159+
var options = serviceProvider.GetRequiredService<IOptions<McpServerOptions>>().Value;
160+
161+
Assert.Equal(handler, options.Handlers.SubscriptionsListenHandler);
162+
}
150163
}

‎tests/ModelContextProtocol.Tests/Server/SubscriptionsListenHandlerTests.cs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,6 @@ private static void TagWithSubscriptionId(JsonRpcNotification notification, Requ
270270
notification.Params = paramsObject;
271271
}
272272

273-
[McpServerToolType]
274273
private sealed class ListenTools
275274
{
276275
[McpServerTool, System.ComponentModel.Description("Echoes the input back to the caller.")]

0 commit comments

Comments
 (0)