forked from modelcontextprotocol/csharp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMcpServerImpl.cs
More file actions
2315 lines (2022 loc) · 107 KB
/
Copy pathMcpServerImpl.cs
File metadata and controls
2315 lines (2022 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ModelContextProtocol.Protocol;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization.Metadata;
namespace ModelContextProtocol.Server;
/// <inheritdoc />
#pragma warning disable MCPEXP001, MCPEXP002
internal sealed partial class McpServerImpl : McpServer
{
internal static Implementation DefaultImplementation { get; } = new()
{
Name = AssemblyNameHelper.DefaultAssemblyName.Name ?? nameof(McpServer),
Version = AssemblyNameHelper.DefaultAssemblyName.Version?.ToString() ?? "1.0.0",
};
private readonly ILogger _logger;
private readonly ITransport _sessionTransport;
private readonly bool _servicesScopePerRequest;
private readonly List<Action> _disposables = [];
private readonly NotificationHandlers _notificationHandlers;
private readonly RequestHandlers _requestHandlers;
private readonly McpSessionHandler _sessionHandler;
private readonly string[] _supportedProtocolVersions;
private readonly string[] _initializeHandshakeProtocolVersions;
private readonly string[] _perRequestMetadataProtocolVersions;
private readonly SemaphoreSlim _disposeLock = new(1, 1);
private readonly ConcurrentDictionary<string, MrtrContinuation> _mrtrContinuations = new();
private readonly ConcurrentDictionary<RequestId, MrtrContext> _mrtrContextsByRequestId = new();
private static readonly string[] s_perRequestMetadataKeys =
[
MetaKeys.ProtocolVersion,
MetaKeys.ClientInfo,
MetaKeys.ClientCapabilities,
MetaKeys.LogLevel,
];
// Track MRTR handler tasks using the same inFlightCount + TCS pattern as
// McpSessionHandler.ProcessMessagesCoreAsync. Starts at 1 for DisposeAsync itself.
private int _mrtrInFlightCount = 1;
private readonly TaskCompletionSource<bool> _allMrtrHandlersCompleted = new(TaskCreationOptions.RunContinuationsAsynchronously);
private ClientCapabilities? _clientCapabilities;
private Implementation? _clientInfo;
private readonly string _serverOnlyEndpointName;
private string? _negotiatedProtocolVersion;
private string _endpointName;
private int _started;
private bool _disposed;
/// <summary>Holds a boxed <see cref="LoggingLevel"/> value for the server.</summary>
/// <remarks>
/// Initialized to non-null the first time SetLevel is used. This is stored as a strong box
/// rather than a nullable to be able to manipulate it atomically.
/// </remarks>
private StrongBox<LoggingLevel>? _loggingLevel;
/// <summary>
/// Creates a new instance of <see cref="McpServerImpl"/>.
/// </summary>
/// <param name="transport">Transport to use for the server representing an already-established session.</param>
/// <param name="options">Configuration options for this server, including capabilities.
/// Make sure to accurately reflect exactly what capabilities the server supports and does not support.</param>
/// <param name="loggerFactory">Logger factory to use for logging</param>
/// <param name="serviceProvider">Optional service provider to use for dependency injection</param>
/// <exception cref="McpException">The server was incorrectly configured.</exception>
public McpServerImpl(ITransport transport, McpServerOptions options, ILoggerFactory? loggerFactory, IServiceProvider? serviceProvider)
#pragma warning restore MCPEXP002
{
Throw.IfNull(transport);
Throw.IfNull(options);
_sessionTransport = transport;
ServerOptions = options;
Services = serviceProvider;
_supportedProtocolVersions = GetConfiguredSupportedProtocolVersions(options.ProtocolVersion);
_initializeHandshakeProtocolVersions = [.. _supportedProtocolVersions.Where(McpProtocolVersions.SupportsInitializeHandshake)];
_perRequestMetadataProtocolVersions = [.. _supportedProtocolVersions.Where(McpProtocolVersions.RequiresPerRequestMetadata)];
_serverOnlyEndpointName = $"Server ({options.ServerInfo?.Name ?? DefaultImplementation.Name} {options.ServerInfo?.Version ?? DefaultImplementation.Version})";
_endpointName = _serverOnlyEndpointName;
_servicesScopePerRequest = options.ScopeRequests;
_logger = loggerFactory?.CreateLogger<McpServer>() ?? NullLogger<McpServer>.Instance;
_clientInfo = options.KnownClientInfo;
_clientCapabilities = options.KnownClientCapabilities;
UpdateEndpointNameWithClientInfo();
_notificationHandlers = new();
_requestHandlers = [];
// Configure all request handlers based on the supplied options.
ServerCapabilities = new();
ConfigureInitialize(options);
ConfigureDiscover(options);
ConfigureTools(options);
ConfigurePrompts(options);
ConfigureResources(options);
ConfigureLogging(options);
ConfigureCompletion(options);
ConfigureSubscriptions(options);
ConfigureExperimentalAndExtensions(options);
ConfigureMrtr();
ConfigureCustomRequestHandlers(options);
// Register any notification handlers that were provided.
if (options.Handlers.NotificationHandlers is { } notificationHandlers)
{
_notificationHandlers.RegisterRange(notificationHandlers);
}
// A stateful session can push unsolicited list-changed notifications, so subscribe to the
// collection change events. A stateless HTTP server cannot send unsolicited notifications, so
// instead suppress the listChanged capability it would otherwise advertise.
if (HasStatefulTransport())
{
Register(ServerOptions.ToolCollection, NotificationMethods.ToolListChangedNotification);
Register(ServerOptions.PromptCollection, NotificationMethods.PromptListChangedNotification);
Register(ServerOptions.ResourceCollection, NotificationMethods.ResourceListChangedNotification);
void Register<TPrimitive>(McpServerPrimitiveCollection<TPrimitive>? collection, string notificationMethod)
where TPrimitive : IMcpServerPrimitive
{
if (collection is not null)
{
EventHandler changed = (sender, e) => _ = SendListChangedNotificationAsync(notificationMethod);
collection.Changed += changed;
_disposables.Add(() => collection.Changed -= changed);
}
}
}
else
{
if (ServerCapabilities.Tools is not null)
ServerCapabilities.Tools.ListChanged = null;
if (ServerCapabilities.Prompts is not null)
ServerCapabilities.Prompts.ListChanged = null;
if (ServerCapabilities.Resources is not null)
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.
var incomingMessageFilter = PrependMetaReadingFilter(BuildMessageFilterPipeline(options.Filters.Message.IncomingFilters));
var outgoingMessageFilter = BuildMessageFilterPipeline(options.Filters.Message.OutgoingFilters);
_sessionHandler = new McpSessionHandler(
isServer: true,
_sessionTransport,
_endpointName!,
_requestHandlers,
_notificationHandlers,
incomingMessageFilter,
outgoingMessageFilter,
_logger);
}
/// <summary>
/// Wraps <paramref name="inner"/> so that, for every JSON-RPC request, a built-in filter first
/// synchronizes server-side state (<see cref="_negotiatedProtocolVersion"/>, <see cref="_clientInfo"/>)
/// from the per-request <c>_meta</c> values projected onto <see cref="JsonRpcMessageContext"/> and
/// validates the per-request protocol version, before delegating to the user-supplied incoming filters.
/// </summary>
/// <remarks>
/// Under the 2026-07-28 protocol revision (SEP-2575) there is no <c>initialize</c> handshake, so these values
/// MUST be populated per-request. Per-request client capabilities and client info are consumed request-scoped
/// by <see cref="DestinationBoundMcpServer"/> and are not read from server-wide state by request handlers. The
/// shared <see cref="_clientInfo"/> 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).
/// </remarks>
private JsonRpcMessageFilter PrependMetaReadingFilter(JsonRpcMessageFilter inner)
{
JsonRpcMessageFilter metaReadingFilter = next => async (message, cancellationToken) =>
{
if (message is JsonRpcRequest { Method: RequestMethods.Initialize } initializeRequest)
{
ValidateInitializeRequestBoundary(initializeRequest);
}
else if (message is JsonRpcRequest request)
{
var context = request.Context;
bool endpointNameNeedsRefresh = false;
bool hasProtocolVersionMeta = HasMetaKey(request, MetaKeys.ProtocolVersion);
bool hasReservedPerRequestMeta = TryGetPerRequestMetadataKey(request, out var reservedPerRequestMetaKey);
// Initialize-handshake protocols establish their version once per session. Surface that
// established version on later raw requests so extension handlers can gate their wire behavior.
if (context?.ProtocolVersion is null && _negotiatedProtocolVersion is { } negotiatedProtocolVersion)
{
context ??= request.Context = new JsonRpcMessageContext();
context.ProtocolVersion = negotiatedProtocolVersion;
}
if (context?.ProtocolVersion is { } protocolVersion)
{
bool protocolVersionAlreadyEstablished = _negotiatedProtocolVersion is not null;
if (protocolVersionAlreadyEstablished)
{
SetNegotiatedProtocolVersion(protocolVersion);
}
// Per SEP-2575, the server MUST reject any request whose per-request
// _meta/io.modelcontextprotocol/protocolVersion is not one of its supported versions
// with an UnsupportedProtocolVersionError (-32022) carrying the supported list.
if (!_supportedProtocolVersions.Contains(protocolVersion))
{
throw new UnsupportedProtocolVersionException(
requested: protocolVersion,
supported: _supportedProtocolVersions);
}
if (McpProtocolVersions.RequiresPerRequestMetadata(protocolVersion))
{
ValidateRequiredPerRequestMetadata(
protocolVersion,
hasProtocolVersionMeta,
context.ClientInfo is not null,
context.ClientCapabilities is not null);
}
else if (McpProtocolVersions.SupportsInitializeHandshake(protocolVersion))
{
if (_negotiatedProtocolVersion is null && hasProtocolVersionMeta)
{
throw new UnsupportedProtocolVersionException(
requested: protocolVersion,
supported: _perRequestMetadataProtocolVersions,
message: $"Protocol version '{protocolVersion}' requires the initialize handshake and cannot be selected through per-request metadata.");
}
if (hasReservedPerRequestMeta)
{
ThrowReservedPerRequestMetadata(requestedProtocolVersion: protocolVersion, reservedPerRequestMetaKey);
}
}
if (!protocolVersionAlreadyEstablished)
{
SetNegotiatedProtocolVersion(protocolVersion);
}
}
else if (_negotiatedProtocolVersion is null)
{
if (request.Method == RequestMethods.ServerDiscover)
{
throw new McpProtocolException(
$"The '{RequestMethods.ServerDiscover}' request requires per-request metadata declaring a supported protocol version.",
McpErrorCode.InvalidParams);
}
if (hasReservedPerRequestMeta)
{
ThrowReservedPerRequestMetadata(requestedProtocolVersion: null, reservedPerRequestMetaKey);
}
}
else if (McpProtocolVersions.SupportsInitializeHandshake(_negotiatedProtocolVersion) && hasReservedPerRequestMeta)
{
ThrowReservedPerRequestMetadata(_negotiatedProtocolVersion, reservedPerRequestMetaKey);
}
ValidateRequestMethodBoundary(request);
if (context?.ClientInfo is { } clientInfo &&
(_clientInfo is null || !string.Equals(_clientInfo.Name, clientInfo.Name, StringComparison.Ordinal) ||
!string.Equals(_clientInfo.Version, clientInfo.Version, StringComparison.Ordinal)))
{
// This shared write is best-effort and used only to derive the session endpoint name for
// logging/telemetry. It is intentionally NOT read by request handlers on 2026-07-28+ sessions:
// DestinationBoundMcpServer resolves ClientInfo (and ClientCapabilities) request-scoped from
// the per-request _meta so concurrent requests never observe each other's values. Under a
// draft stateful session with differing per-request client info, the last writer wins here,
// which only affects the logged endpoint name and never the request-scoped values handlers see.
_clientInfo = clientInfo;
endpointNameNeedsRefresh = true;
}
if (endpointNameNeedsRefresh)
{
UpdateEndpointNameWithClientInfo();
_sessionHandler.EndpointName = _endpointName;
}
}
else if (message is JsonRpcNotification notification)
{
ValidateNotificationBoundary(notification);
}
await next(message, cancellationToken).ConfigureAwait(false);
};
return next => metaReadingFilter(inner(next));
}
private static void ValidateRequiredPerRequestMetadata(
string protocolVersion,
bool hasProtocolVersionMeta,
bool hasClientInfoMeta,
bool hasClientCapabilitiesMeta)
{
if (!hasProtocolVersionMeta)
{
ThrowMissingPerRequestMetadata(protocolVersion, MetaKeys.ProtocolVersion);
}
if (!hasClientInfoMeta)
{
ThrowMissingPerRequestMetadata(protocolVersion, MetaKeys.ClientInfo);
}
if (!hasClientCapabilitiesMeta)
{
ThrowMissingPerRequestMetadata(protocolVersion, MetaKeys.ClientCapabilities);
}
}
private static void ThrowMissingPerRequestMetadata(string protocolVersion, string key) =>
throw new McpProtocolException(
$"Requests using protocol version '{protocolVersion}' must include '_meta/{key}'.",
McpErrorCode.InvalidParams);
private static void ThrowReservedPerRequestMetadata(string? requestedProtocolVersion, string key) =>
throw new McpProtocolException(
requestedProtocolVersion is null
? $"The reserved per-request metadata key '_meta/{key}' requires a protocol version that uses per-request metadata."
: $"The reserved per-request metadata key '_meta/{key}' is not valid with protocol version '{requestedProtocolVersion}'.",
McpErrorCode.InvalidRequest);
private static bool TryGetPerRequestMetadataKey(JsonRpcRequest request, out string key)
{
foreach (var candidate in s_perRequestMetadataKeys)
{
if (HasMetaKey(request, candidate))
{
key = candidate;
return true;
}
}
key = "";
return false;
}
private static bool HasMetaKey(JsonRpcRequest request, string key) =>
request.Params is JsonObject paramsObj &&
paramsObj["_meta"] is JsonObject metaObj &&
metaObj.ContainsKey(key);
private void ValidateInitializeRequestBoundary(JsonRpcRequest request)
{
if (request.Context?.ProtocolVersion is { } protocolVersion &&
!McpProtocolVersions.SupportsInitializeHandshake(protocolVersion))
{
throw new UnsupportedProtocolVersionException(
requested: protocolVersion,
supported: _initializeHandshakeProtocolVersions,
message: $"Protocol version '{protocolVersion}' is not available through the initialize handshake.");
}
if (TryGetPerRequestMetadataKey(request, out var key))
{
ThrowReservedPerRequestMetadata(TryGetStringParam(request, "protocolVersion"), key);
}
}
private static string? TryGetStringParam(JsonRpcRequest request, string propertyName)
{
if (request.Params is JsonObject paramsObj &&
paramsObj[propertyName] is JsonValue value &&
value.TryGetValue(out string? result))
{
return result;
}
return null;
}
private static string[] GetConfiguredSupportedProtocolVersions(string? protocolVersion)
{
if (protocolVersion is null)
{
return McpProtocolVersions.SupportedProtocolVersions;
}
if (!McpProtocolVersions.IsSupportedProtocolVersion(protocolVersion))
{
throw new McpException(
$"Unsupported server protocol version '{protocolVersion}'. Supported protocol versions: " +
string.Join(", ", McpProtocolVersions.SupportedProtocolVersions) + ".");
}
return [protocolVersion];
}
private void ValidateNotificationBoundary(JsonRpcNotification notification)
{
if (notification.Method == NotificationMethods.InitializedNotification &&
McpProtocolVersions.RequiresPerRequestMetadata(notification.Context?.ProtocolVersion ?? _negotiatedProtocolVersion))
{
throw new McpProtocolException(
$"The notification '{NotificationMethods.InitializedNotification}' is only valid after the initialize handshake.",
McpErrorCode.InvalidRequest);
}
}
private void ValidateRequestMethodBoundary(JsonRpcRequest request)
{
bool usesPerRequestMetadata = IsJuly2026OrLaterProtocolRequest(request);
if (!usesPerRequestMetadata &&
request.Method is RequestMethods.SubscriptionsListen
or RequestMethods.ServerDiscover)
{
throw new McpProtocolException(
$"The method '{request.Method}' requires a newer protocol revision that supports per-request metadata; " +
$"the negotiated protocol version is '{NegotiatedProtocolVersion ?? "(none)"}'.",
McpErrorCode.MethodNotFound);
}
if (usesPerRequestMetadata && request.Method == RequestMethods.LoggingSetLevel)
{
throw new McpProtocolException(
$"The method '{RequestMethods.LoggingSetLevel}' is not available on protocol version '{request.Context?.ProtocolVersion ?? NegotiatedProtocolVersion}'. Use per-request _meta/{MetaKeys.LogLevel} instead.",
McpErrorCode.MethodNotFound);
}
}
/// <inheritdoc/>
public override string? SessionId => _sessionTransport.SessionId;
/// <inheritdoc/>
public override string? NegotiatedProtocolVersion => _negotiatedProtocolVersion;
/// <summary>
/// Records the negotiated MCP protocol version for the session. The version is established exactly
/// once: the initial <see langword="null"/>-to-value transition is allowed (and racing requests that
/// select the same version are idempotent no-ops), but any later attempt to switch to a different
/// version throws. A single session MUST NOT change protocol versions, so a conflicting per-request
/// <c>_meta</c> protocol version (or <c>Mcp-Protocol-Version</c> header) is a client error rather than
/// something we silently overwrite.
/// </summary>
private void SetNegotiatedProtocolVersion(string protocolVersion)
{
string? previous = Interlocked.CompareExchange(ref _negotiatedProtocolVersion, protocolVersion, null);
if (previous is null)
{
// We won the initial null-to-value transition; publish it to the session handler for telemetry.
_sessionHandler.NegotiatedProtocolVersion = protocolVersion;
}
else if (!string.Equals(previous, protocolVersion, StringComparison.Ordinal))
{
throw new McpProtocolException(
$"The negotiated protocol version cannot change within a session. " +
$"The session negotiated '{previous}', but a request specified '{protocolVersion}'.",
McpErrorCode.InvalidRequest);
}
}
/// <inheritdoc/>
public ServerCapabilities ServerCapabilities { get; }
/// <inheritdoc />
public override ClientCapabilities? ClientCapabilities => _clientCapabilities;
/// <inheritdoc />
public override Implementation? ClientInfo => _clientInfo;
/// <inheritdoc />
public override McpServerOptions ServerOptions { get; }
/// <inheritdoc />
public override IServiceProvider? Services { get; }
/// <inheritdoc />
[Obsolete(Obsoletions.DeprecatedLogging_Message, DiagnosticId = Obsoletions.Deprecated_DiagnosticId, UrlFormat = Obsoletions.Deprecated_Url)]
public override LoggingLevel? LoggingLevel => _loggingLevel?.Value;
/// <inheritdoc />
public override async Task RunAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _started, 1) != 0)
{
throw new InvalidOperationException($"{nameof(RunAsync)} must only be called once.");
}
try
{
await _sessionHandler.ProcessMessagesAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
await DisposeAsync().ConfigureAwait(false);
}
}
/// <inheritdoc/>
public override Task<JsonRpcResponse> SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default)
=> _sessionHandler.SendRequestAsync(request, cancellationToken);
/// <inheritdoc/>
public override Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)
=> _sessionHandler.SendMessageAsync(message, cancellationToken);
/// <inheritdoc/>
public override IAsyncDisposable RegisterNotificationHandler(string method, Func<JsonRpcNotification, CancellationToken, ValueTask> handler)
=> _sessionHandler.RegisterNotificationHandler(method, handler);
/// <inheritdoc/>
public override async ValueTask DisposeAsync()
{
using var _ = await _disposeLock.LockAsync().ConfigureAwait(false);
if (_disposed)
{
return;
}
_disposed = true;
// Dispose the session handler - cancels message processing and waits for all
// in-flight request handlers (including retries in AwaitMrtrHandlerAsync) to complete.
// After this returns, no new requests can be processed and no new MRTR continuations
// can be created, so _mrtrContinuations is effectively frozen.
_disposables.ForEach(d => d());
await _sessionHandler.DisposeAsync().ConfigureAwait(false);
// Cancel all orphaned MRTR handlers still suspended in continuations (waiting for
// retries that will never arrive now that the session handler is disposed).
int cancelledCount = _mrtrContinuations.Count;
foreach (var continuation in _mrtrContinuations.Values)
{
continuation.CancelHandler();
}
if (cancelledCount > 0)
{
MrtrContinuationsCancelled(cancelledCount);
}
// Wait for all MRTR handler tasks to complete using the same inFlightCount + TCS
// pattern as McpSessionHandler.ProcessMessagesCoreAsync. The count started at 1
// (for DisposeAsync itself); decrementing it here triggers the drain if handlers
// are still in flight. ObserveHandlerCompletionAsync decrements for each handler.
if (Interlocked.Decrement(ref _mrtrInFlightCount) != 0)
{
await _allMrtrHandlersCompleted.Task.ConfigureAwait(false);
}
}
private void ConfigureInitialize(McpServerOptions options)
{
_requestHandlers.Set(RequestMethods.Initialize,
async (request, _, _) =>
{
_clientCapabilities = request?.Capabilities ?? new();
_clientInfo = request?.ClientInfo;
// Use the ClientInfo to update the session EndpointName for logging.
UpdateEndpointNameWithClientInfo();
_sessionHandler.EndpointName = _endpointName;
// Negotiate an initialize-handshake protocol version. initialize is not available in the 2026-07-28
// and later protocol revisions, so those versions must use server/discover with
// per-request _meta instead.
string? protocolVersion = options.ProtocolVersion;
if (protocolVersion is { } configuredProtocolVersion &&
McpProtocolVersions.IsJuly2026OrLaterProtocolVersion(configuredProtocolVersion))
{
throw new UnsupportedProtocolVersionException(
configuredProtocolVersion,
_initializeHandshakeProtocolVersions,
$"Protocol version '{configuredProtocolVersion}' is not available through the initialize handshake.");
}
if (protocolVersion is null)
{
if (request?.ProtocolVersion is string clientProtocolVersion)
{
if (McpProtocolVersions.IsJuly2026OrLaterProtocolVersion(clientProtocolVersion))
{
throw new UnsupportedProtocolVersionException(
clientProtocolVersion,
_initializeHandshakeProtocolVersions,
$"Protocol version '{clientProtocolVersion}' is not available through the initialize handshake.");
}
protocolVersion = McpProtocolVersions.SupportsInitializeHandshake(clientProtocolVersion) ?
clientProtocolVersion :
McpProtocolVersions.November2025ProtocolVersion;
}
else
{
protocolVersion = McpProtocolVersions.November2025ProtocolVersion;
}
}
string negotiatedProtocolVersion = protocolVersion ?? McpProtocolVersions.November2025ProtocolVersion;
// The initialize handshake is authoritative: it may supersede a protocol version
// a prior server/discover probe established on the same connection (the dual-path
// fallback path a permissive client takes against an unknown server). Unlike the
// per-request 2026-07-28 version - which SetNegotiatedProtocolVersion locks once negotiated -
// initialize force-sets the version.
_negotiatedProtocolVersion = negotiatedProtocolVersion;
_sessionHandler.NegotiatedProtocolVersion = negotiatedProtocolVersion;
return new InitializeResult
{
ProtocolVersion = negotiatedProtocolVersion,
Instructions = options.ServerInstructions,
ServerInfo = options.ServerInfo ?? DefaultImplementation,
Capabilities = ServerCapabilities ?? new(),
ResultType = "complete",
};
},
McpJsonUtilities.JsonContext.Default.InitializeRequestParams,
McpJsonUtilities.JsonContext.Default.InitializeResult);
}
/// <summary>
/// Registers the <c>server/discover</c> request handler introduced by the 2026-07-28 protocol revision (SEP-2575).
/// </summary>
/// <remarks>
/// The handler is registered unconditionally so requests can be routed to the protocol boundary filters. Successful
/// <c>server/discover</c> responses advertise only protocol versions available through per-request metadata; versions
/// that require the <c>initialize</c> handshake are negotiated through <c>initialize</c> instead.
/// </remarks>
private void ConfigureDiscover(McpServerOptions options)
{
_requestHandlers.Set(RequestMethods.ServerDiscover,
(request, _, _) =>
{
return new ValueTask<DiscoverResult>(new DiscoverResult
{
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
// their "do not cache" behavior while satisfying the wire requirement.
TimeToLive = TimeSpan.Zero,
CacheScope = CacheScope.Private,
ResultType = "complete",
});
},
McpJsonUtilities.JsonContext.Default.DiscoverRequestParams,
McpJsonUtilities.JsonContext.Default.DiscoverResult);
}
/// <summary>
/// Registers the <c>subscriptions/listen</c> request handler introduced by the 2026-07-28 protocol revision (SEP-2575).
/// </summary>
/// <remarks>
/// <para>
/// The handler opens a long-lived response stream (over the per-request <see cref="StreamableHttpPostTransport"/>
/// for HTTP, or the shared STDIO channel) that first sends
/// <see cref="NotificationMethods.SubscriptionsAcknowledgedNotification"/> reporting which subscriptions the
/// server agreed to honor, and then streams matching notifications until the request is cancelled.
/// </para>
/// <para>
/// Subscription-bound notifications carry the listen request's id in their
/// <c>_meta/io.modelcontextprotocol/subscriptionId</c> field per SEP-2575 so clients can demultiplex.
/// </para>
/// </remarks>
private void ConfigureSubscriptions(McpServerOptions options)
{
_requestHandlers.Set(RequestMethods.SubscriptionsListen,
async (request, jsonRpcRequest, cancellationToken) =>
{
if (!IsJuly2026OrLaterProtocolRequest(jsonRpcRequest))
{
throw new McpProtocolException(
$"The method '{RequestMethods.SubscriptionsListen}' requires a newer protocol revision that supports per-request subscriptions; " +
$"the negotiated protocol version is '{NegotiatedProtocolVersion ?? "(none)"}'.",
McpErrorCode.MethodNotFound);
}
var requested = request?.Notifications ?? new SubscriptionsListenNotifications();
// A stateless session (Streamable HTTP with no session) cannot deliver out-of-band
// notifications: each request is isolated and nothing outlives it to push later list/resource
// changes back to the client (tracked by #1662). Rather than hold the POST open forever only
// to deliver nothing - pinning the connection and its request scope - acknowledge the listen
// request granting no notifications and complete immediately. This runs after protocol
// negotiation, so it is not an initialize-handshake-server signal and never triggers a client fallback to the
// initialize handshake.
if (!HasStatefulTransport())
{
var statelessSubscription = new ActiveSubscription(
jsonRpcRequest.Id,
new SubscriptionsListenNotifications(),
jsonRpcRequest.Context?.RelatedTransport);
await SendSubscriptionAckAsync(statelessSubscription, cancellationToken).ConfigureAwait(false);
return EmptyResult.Instance;
}
// Filter the requested notifications against what the server actually supports.
var granted = new SubscriptionsListenNotifications
{
ToolsListChanged = requested.ToolsListChanged == true && ServerCapabilities?.Tools?.ListChanged == true ? true : null,
PromptsListChanged = requested.PromptsListChanged == true && ServerCapabilities?.Prompts?.ListChanged == true ? true : null,
ResourcesListChanged = requested.ResourcesListChanged == true && ServerCapabilities?.Resources?.ListChanged == true ? true : null,
ResourceSubscriptions = requested.ResourceSubscriptions is { Count: > 0 } subs && ServerCapabilities?.Resources?.Subscribe == true
? new List<string>(subs)
: null,
};
// Track this subscription so list-changed notifications can be fanned out to it, tagged with
// the right subscriptionId, and routed back over the stream this request opened.
var subscription = new ActiveSubscription(
jsonRpcRequest.Id,
granted,
jsonRpcRequest.Context?.RelatedTransport);
_activeSubscriptions[jsonRpcRequest.Id] = subscription;
try
{
// Send the acknowledgement notification first, as required by SEP-2575. Like every other
// notification delivered on the subscription it is routed back over this request's own
// stream and tagged with the subscription id so shared-channel clients can demultiplex it.
await SendSubscriptionAckAsync(subscription, cancellationToken).ConfigureAwait(false);
// Keep the subscription open until the request is cancelled (client disconnect on HTTP,
// or notifications/cancelled on STDIO).
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
using var registration = cancellationToken.Register(static state => ((TaskCompletionSource<bool>)state!).TrySetResult(true), tcs);
await tcs.Task.ConfigureAwait(false);
}
finally
{
_activeSubscriptions.TryRemove(jsonRpcRequest.Id, out _);
}
return EmptyResult.Instance;
},
McpJsonUtilities.JsonContext.Default.SubscriptionsListenRequestParams,
McpJsonUtilities.JsonContext.Default.EmptyResult);
}
/// <summary>Tracks an active <c>subscriptions/listen</c> subscription for notification fan-out.</summary>
/// <param name="Id">The id of the <c>subscriptions/listen</c> request, reused as the SEP-2575 subscription id.</param>
/// <param name="Granted">The notification types the server agreed to deliver on this subscription.</param>
/// <param name="RelatedTransport">
/// The transport the <c>subscriptions/listen</c> request arrived on. For Streamable HTTP this is the
/// per-request response stream the subscription must be delivered on; for stdio it is <see langword="null"/>,
/// so notifications fall back to the shared session channel.
/// </param>
private sealed record ActiveSubscription(RequestId Id, SubscriptionsListenNotifications Granted, ITransport? RelatedTransport);
private readonly ConcurrentDictionary<RequestId, ActiveSubscription> _activeSubscriptions = new();
/// <summary>
/// Delivers a <c>*/list_changed</c> notification triggered by a server-side collection change.
/// </summary>
/// <remarks>
/// Pre-SEP-2575 clients do not open <c>subscriptions/listen</c> streams, so they keep receiving a single
/// session-wide broadcast. Clients on the 2026-07-28 or later revision instead receive only the change notifications they explicitly
/// requested, each routed back over the originating subscription stream and tagged with its id; the server
/// <b>MUST NOT</b> send such a client notification types it never subscribed to.
/// </remarks>
private async Task SendListChangedNotificationAsync(string notificationMethod)
{
// Initialize-handshake clients never open a subscriptions/listen stream, so they keep the session-wide broadcast.
// subscriptions/listen is a SEP-2575 feature, so clients on the 2026-07-28 or later revision instead get
// a fan-out limited to the notification types they explicitly subscribed to.
if (!IsJuly2026OrLaterProtocol())
{
await this.SendNotificationAsync(notificationMethod).ConfigureAwait(false);
return;
}
foreach (var subscription in _activeSubscriptions.Values)
{
if (!GrantsListChanged(subscription.Granted, notificationMethod))
{
continue;
}
try
{
await SendSubscriptionNotificationAsync(subscription, notificationMethod, paramsNode: null, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
// A single closed or faulted subscription stream must not prevent fan-out to the others.
SubscriptionNotificationFailed(notificationMethod, subscription.Id.ToString(), ex);
}
}
}
/// <summary>
/// Sends <paramref name="method"/> over <paramref name="subscription"/>'s stream, tagging it with the
/// SEP-2575 <c>_meta</c> subscription id so clients sharing a channel (notably stdio) can demultiplex it.
/// </summary>
private Task SendSubscriptionNotificationAsync(ActiveSubscription subscription, string method, JsonNode? paramsNode, CancellationToken cancellationToken)
{
var paramsObject = paramsNode as JsonObject ?? new JsonObject();
if (paramsObject["_meta"] is not JsonObject meta)
{
meta = new JsonObject();
paramsObject["_meta"] = meta;
}
meta[MetaKeys.SubscriptionId] = subscription.Id.Id switch
{
string stringId => JsonValue.Create(stringId),
long longId => JsonValue.Create(longId),
_ => null,
};
var notification = new JsonRpcNotification
{
Method = method,
Params = paramsObject,
Context = new JsonRpcMessageContext { RelatedTransport = subscription.RelatedTransport },
};
return SendMessageAsync(notification, cancellationToken);
}
/// <summary>
/// Sends the SEP-2575 <c>subscriptions/acknowledged</c> notification for a subscription, carrying the
/// notification types the server agreed to deliver. Routed back over the subscription's own stream and
/// tagged with its id like every other subscription notification.
/// </summary>
private Task SendSubscriptionAckAsync(ActiveSubscription subscription, CancellationToken cancellationToken)
{
var ackParams = JsonSerializer.SerializeToNode(
new SubscriptionsAcknowledgedNotificationParams { Notifications = subscription.Granted },
McpJsonUtilities.JsonContext.Default.SubscriptionsAcknowledgedNotificationParams);
return SendSubscriptionNotificationAsync(
subscription,
NotificationMethods.SubscriptionsAcknowledgedNotification,
ackParams,
cancellationToken);
}
/// <summary>Maps a <c>*/list_changed</c> method to the subscription filter flag that enables it.</summary>
private static bool GrantsListChanged(SubscriptionsListenNotifications granted, string method) => method switch
{
NotificationMethods.ToolListChangedNotification => granted.ToolsListChanged == true,
NotificationMethods.PromptListChangedNotification => granted.PromptsListChanged == true,
NotificationMethods.ResourceListChangedNotification => granted.ResourcesListChanged == true,
_ => false,
};
private void ConfigureCompletion(McpServerOptions options)
{
var completeHandler = options.Handlers.CompleteHandler;
var completionsCapability = options.Capabilities?.Completions;
// Build completion value lookups from prompt/resource collections' [AllowedValues]-attributed parameters.
Dictionary<string, Dictionary<string, string[]>>? promptCompletions = BuildAllowedValueCompletions(options.PromptCollection);
Dictionary<string, Dictionary<string, string[]>>? resourceCompletions = BuildAllowedValueCompletions(options.ResourceCollection);
bool hasCollectionCompletions = promptCompletions is not null || resourceCompletions is not null;
if (completeHandler is null && completionsCapability is null && !hasCollectionCompletions)
{
return;
}
completeHandler ??= (static async (_, __) => new CompleteResult());
// Augment the completion handler with allowed values from prompt/resource collections.
if (hasCollectionCompletions)
{
var originalCompleteHandler = completeHandler;
completeHandler = async (request, cancellationToken) =>
{
CompleteResult result = await originalCompleteHandler(request, cancellationToken).ConfigureAwait(false);
string[]? allowedValues = null;
switch (request.Params?.Ref)
{
case PromptReference pr when promptCompletions is not null:
if (promptCompletions.TryGetValue(pr.Name, out var promptParams))
{
promptParams.TryGetValue(request.Params.Argument.Name, out allowedValues);
}
break;
case ResourceTemplateReference rtr when resourceCompletions is not null:
if (rtr.Uri is not null && resourceCompletions.TryGetValue(rtr.Uri, out var resourceParams))
{
resourceParams.TryGetValue(request.Params.Argument.Name, out allowedValues);
}
break;
}
if (allowedValues is not null)
{
string partialValue = request.Params!.Argument.Value;
foreach (var v in allowedValues)
{
if (v.StartsWith(partialValue, StringComparison.OrdinalIgnoreCase))
{
result.Completion.Values.Add(v);
}
}
result.Completion.Total = result.Completion.Values.Count;
}
return result;
};
}
completeHandler = BuildFilterPipeline(completeHandler, options.Filters.Request.CompleteFilters);
ServerCapabilities.Completions = new();
SetHandler(
RequestMethods.CompletionComplete,
completeHandler,
McpJsonUtilities.JsonContext.Default.CompleteRequestParams,
McpJsonUtilities.JsonContext.Default.CompleteResult);
}
/// <summary>
/// Builds a lookup of primitive name/URI → (parameter name → allowed values) from the enum values
/// in the JSON schemas of AIFunction-based prompts or resources.
/// </summary>
private static Dictionary<string, Dictionary<string, string[]>>? BuildAllowedValueCompletions<T>(
McpServerPrimitiveCollection<T>? primitives) where T : class, IMcpServerPrimitive
{
if (primitives is null)
{
return null;
}
Dictionary<string, Dictionary<string, string[]>>? result = null;
foreach (var primitive in primitives)
{
JsonElement schema;
string id;
if (primitive is AIFunctionMcpServerPrompt aiPrompt)
{
schema = aiPrompt.AIFunction.JsonSchema;
id = aiPrompt.ProtocolPrompt.Name;
}
else if (primitive is AIFunctionMcpServerResource aiResource && aiResource.IsTemplated)
{
schema = aiResource.AIFunction.JsonSchema;
id = aiResource.ProtocolResourceTemplate.UriTemplate;
}
else
{
continue;
}
if (schema.TryGetProperty("properties", out JsonElement properties) &&
properties.ValueKind is JsonValueKind.Object)
{
Dictionary<string, string[]>? paramValues = null;
foreach (var param in properties.EnumerateObject())
{
if (param.Value.TryGetProperty("enum", out JsonElement enumValues) &&
enumValues.ValueKind is JsonValueKind.Array)
{
List<string>? values = null;
foreach (var item in enumValues.EnumerateArray())
{
if (item.ValueKind is JsonValueKind.String && item.GetString() is { } str)
{
values ??= [];
values.Add(str);
}
}
if (values is not null)
{
paramValues ??= new(StringComparer.Ordinal);
paramValues[param.Name] = [.. values];
}
}
}
if (paramValues is not null)
{
result ??= new(StringComparer.Ordinal);
result[id] = paramValues;
}
}
}
return result;
}