-
Notifications
You must be signed in to change notification settings - Fork 650
Expand file tree
/
Copy pathMcpServerImpl.cs
More file actions
1246 lines (1062 loc) · 51.1 KB
/
McpServerImpl.cs
File metadata and controls
1246 lines (1062 loc) · 51.1 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.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
namespace ModelContextProtocol.Server;
/// <inheritdoc />
#pragma warning disable 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 SemaphoreSlim _disposeLock = new(1, 1);
private readonly McpTaskCancellationTokenProvider? _taskCancellationTokenProvider;
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;
_serverOnlyEndpointName = $"Server ({options.ServerInfo?.Name ?? DefaultImplementation.Name} {options.ServerInfo?.Version ?? DefaultImplementation.Version})";
_endpointName = _serverOnlyEndpointName;
_servicesScopePerRequest = options.ScopeRequests;
_logger = loggerFactory?.CreateLogger<McpServer>() ?? NullLogger<McpServer>.Instance;
// Only allocate the cancellation token provider if a task store is configured
if (options.TaskStore is not null)
{
_taskCancellationTokenProvider = new McpTaskCancellationTokenProvider();
}
_clientInfo = options.KnownClientInfo;
_clientCapabilities = options.KnownClientCapabilities;
UpdateEndpointNameWithClientInfo();
_notificationHandlers = new();
_requestHandlers = [];
// Configure all request handlers based on the supplied options.
ServerCapabilities = new();
ConfigureInitialize(options);
ConfigureTools(options);
ConfigurePrompts(options);
ConfigureResources(options);
ConfigureTasks(options);
ConfigureLogging(options);
ConfigureCompletion(options);
ConfigureExperimentalAndExtensions(options);
// Register any notification handlers that were provided.
if (options.Handlers.NotificationHandlers is { } notificationHandlers)
{
_notificationHandlers.RegisterRange(notificationHandlers);
}
// Now that everything has been configured, subscribe to any necessary notifications.
if (transport is not StreamableHttpServerTransport streamableHttpTransport || streamableHttpTransport.Stateless is false)
{
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) => _ = this.SendNotificationAsync(notificationMethod);
collection.Changed += changed;
_disposables.Add(() => collection.Changed -= changed);
}
}
}
// And initialize the session.
var incomingMessageFilter = BuildMessageFilterPipeline(options.Filters.Message.IncomingFilters);
var outgoingMessageFilter = BuildMessageFilterPipeline(options.Filters.Message.OutgoingFilters);
_sessionHandler = new McpSessionHandler(
isServer: true,
_sessionTransport,
_endpointName!,
_requestHandlers,
_notificationHandlers,
incomingMessageFilter,
outgoingMessageFilter,
_logger);
}
/// <inheritdoc/>
public override string? SessionId => _sessionTransport.SessionId;
/// <inheritdoc/>
public override string? NegotiatedProtocolVersion => _negotiatedProtocolVersion;
/// <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 />
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;
_taskCancellationTokenProvider?.Dispose();
_disposables.ForEach(d => d());
await _sessionHandler.DisposeAsync().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 a protocol version. If the server options provide one, use that.
// Otherwise, try to use whatever the client requested as long as it's supported.
// If it's not supported, fall back to the latest supported version.
string? protocolVersion = options.ProtocolVersion;
protocolVersion ??= request?.ProtocolVersion is string clientProtocolVersion && McpSessionHandler.SupportedProtocolVersions.Contains(clientProtocolVersion) ?
clientProtocolVersion :
McpSessionHandler.LatestProtocolVersion;
_negotiatedProtocolVersion = protocolVersion;
// Update session handler with the negotiated protocol version for telemetry
_sessionHandler.NegotiatedProtocolVersion = protocolVersion;
return new InitializeResult
{
ProtocolVersion = protocolVersion,
Instructions = options.ServerInstructions,
ServerInfo = options.ServerInfo ?? DefaultImplementation,
Capabilities = ServerCapabilities ?? new(),
};
},
McpJsonUtilities.JsonContext.Default.InitializeRequestParams,
McpJsonUtilities.JsonContext.Default.InitializeResult);
}
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;
}
private void ConfigureExperimentalAndExtensions(McpServerOptions options)
{
ServerCapabilities.Experimental = options.Capabilities?.Experimental;
ServerCapabilities.Extensions = options.Capabilities?.Extensions;
}
private void ConfigureResources(McpServerOptions options)
{
var listResourcesHandler = options.Handlers.ListResourcesHandler;
var listResourceTemplatesHandler = options.Handlers.ListResourceTemplatesHandler;
var readResourceHandler = options.Handlers.ReadResourceHandler;
var subscribeHandler = options.Handlers.SubscribeToResourcesHandler;
var unsubscribeHandler = options.Handlers.UnsubscribeFromResourcesHandler;
var resources = options.ResourceCollection;
var resourcesCapability = options.Capabilities?.Resources;
if (listResourcesHandler is null && listResourceTemplatesHandler is null && readResourceHandler is null &&
subscribeHandler is null && unsubscribeHandler is null && resources is null &&
resourcesCapability is null)
{
return;
}
ServerCapabilities.Resources = new();
listResourcesHandler ??= (static async (_, __) => new ListResourcesResult());
listResourceTemplatesHandler ??= (static async (_, __) => new ListResourceTemplatesResult());
readResourceHandler ??= (static async (request, _) => throw new McpProtocolException($"Unknown resource URI: '{request.Params?.Uri}'", McpErrorCode.ResourceNotFound));
subscribeHandler ??= (static async (_, __) => new EmptyResult());
unsubscribeHandler ??= (static async (_, __) => new EmptyResult());
var listChanged = resourcesCapability?.ListChanged;
var subscribe = resourcesCapability?.Subscribe;
// Handle resources provided via DI.
if (resources is not null)
{
var originalListResourcesHandler = listResourcesHandler;
listResourcesHandler = async (request, cancellationToken) =>
{
ListResourcesResult result = originalListResourcesHandler is not null ?
await originalListResourcesHandler(request, cancellationToken).ConfigureAwait(false) :
new();
if (request.Params?.Cursor is null)
{
foreach (var r in resources)
{
if (r.ProtocolResource is { } resource)
{
result.Resources.Add(resource);
}
}
}
return result;
};
var originalListResourceTemplatesHandler = listResourceTemplatesHandler;
listResourceTemplatesHandler = async (request, cancellationToken) =>
{
ListResourceTemplatesResult result = originalListResourceTemplatesHandler is not null ?
await originalListResourceTemplatesHandler(request, cancellationToken).ConfigureAwait(false) :
new();
if (request.Params?.Cursor is null)
{
foreach (var rt in resources)
{
if (rt.IsTemplated)
{
result.ResourceTemplates.Add(rt.ProtocolResourceTemplate);
}
}
}
return result;
};
// Synthesize read resource handler, which covers both resources and resource templates.
var originalReadResourceHandler = readResourceHandler;
readResourceHandler = async (request, cancellationToken) =>
{
if (request.MatchedPrimitive is McpServerResource matchedResource)
{
return await matchedResource.ReadAsync(request, cancellationToken).ConfigureAwait(false);
}
return await originalReadResourceHandler(request, cancellationToken).ConfigureAwait(false);
};
listChanged = true;
// TODO: Implement subscribe/unsubscribe logic for resource and resource template collections.
// subscribe = true;
}
listResourcesHandler = BuildFilterPipeline(listResourcesHandler, options.Filters.Request.ListResourcesFilters);
listResourceTemplatesHandler = BuildFilterPipeline(listResourceTemplatesHandler, options.Filters.Request.ListResourceTemplatesFilters);
readResourceHandler = BuildFilterPipeline(readResourceHandler, options.Filters.Request.ReadResourceFilters, handler =>
async (request, cancellationToken) =>
{
// Initial handler that sets MatchedPrimitive
if (request.Params?.Uri is { } uri && resources is not null)
{
// First try an O(1) lookup by exact match.
if (resources.TryGetPrimitive(uri, out var resource) && !resource.IsTemplated)
{
request.MatchedPrimitive = resource;
}
else
{
// Fall back to an O(N) lookup, trying to match against each URI template.
foreach (var resourceTemplate in resources)
{
if (resourceTemplate.IsMatch(uri))
{
request.MatchedPrimitive = resourceTemplate;
break;
}
}
}
}
try
{
var result = await handler(request, cancellationToken).ConfigureAwait(false);
ReadResourceCompleted(request.Params?.Uri ?? string.Empty);
return result;
}
catch (Exception e)
{
ReadResourceError(request.Params?.Uri ?? string.Empty, e);
throw;
}
});
subscribeHandler = BuildFilterPipeline(subscribeHandler, options.Filters.Request.SubscribeToResourcesFilters);
unsubscribeHandler = BuildFilterPipeline(unsubscribeHandler, options.Filters.Request.UnsubscribeFromResourcesFilters);
ServerCapabilities.Resources.ListChanged = listChanged;
ServerCapabilities.Resources.Subscribe = subscribe;
SetHandler(
RequestMethods.ResourcesList,
listResourcesHandler,
McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,
McpJsonUtilities.JsonContext.Default.ListResourcesResult);
SetHandler(
RequestMethods.ResourcesTemplatesList,
listResourceTemplatesHandler,
McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,
McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult);
SetHandler(
RequestMethods.ResourcesRead,
readResourceHandler,
McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,
McpJsonUtilities.JsonContext.Default.ReadResourceResult);
SetHandler(
RequestMethods.ResourcesSubscribe,
subscribeHandler,
McpJsonUtilities.JsonContext.Default.SubscribeRequestParams,
McpJsonUtilities.JsonContext.Default.EmptyResult);
SetHandler(
RequestMethods.ResourcesUnsubscribe,
unsubscribeHandler,
McpJsonUtilities.JsonContext.Default.UnsubscribeRequestParams,
McpJsonUtilities.JsonContext.Default.EmptyResult);
}
private void ConfigurePrompts(McpServerOptions options)
{
var listPromptsHandler = options.Handlers.ListPromptsHandler;
var getPromptHandler = options.Handlers.GetPromptHandler;
var prompts = options.PromptCollection;
var promptsCapability = options.Capabilities?.Prompts;
if (listPromptsHandler is null && getPromptHandler is null && prompts is null &&
promptsCapability is null)
{
return;
}
ServerCapabilities.Prompts = new();
listPromptsHandler ??= (static async (_, __) => new ListPromptsResult());
getPromptHandler ??= (static async (request, _) => throw new McpProtocolException($"Unknown prompt: '{request.Params?.Name}'", McpErrorCode.InvalidParams));
var listChanged = promptsCapability?.ListChanged;
// Handle tools provided via DI by augmenting the handlers to incorporate them.
if (prompts is not null)
{
var originalListPromptsHandler = listPromptsHandler;
listPromptsHandler = async (request, cancellationToken) =>
{
ListPromptsResult result = originalListPromptsHandler is not null ?
await originalListPromptsHandler(request, cancellationToken).ConfigureAwait(false) :
new();
if (request.Params?.Cursor is null)
{
foreach (var p in prompts)
{
result.Prompts.Add(p.ProtocolPrompt);
}
}
return result;
};
var originalGetPromptHandler = getPromptHandler;
getPromptHandler = (request, cancellationToken) =>
{
if (request.MatchedPrimitive is McpServerPrompt prompt)
{
return prompt.GetAsync(request, cancellationToken);
}
return originalGetPromptHandler(request, cancellationToken);
};
listChanged = true;
}
listPromptsHandler = BuildFilterPipeline(listPromptsHandler, options.Filters.Request.ListPromptsFilters);
getPromptHandler = BuildFilterPipeline(getPromptHandler, options.Filters.Request.GetPromptFilters, handler =>
async (request, cancellationToken) =>
{
// Initial handler that sets MatchedPrimitive
if (request.Params?.Name is { } promptName && prompts is not null &&
prompts.TryGetPrimitive(promptName, out var prompt))
{
request.MatchedPrimitive = prompt;
}
try
{
var result = await handler(request, cancellationToken).ConfigureAwait(false);
GetPromptCompleted(request.Params?.Name ?? string.Empty);
return result;
}
catch (Exception e)
{
GetPromptError(request.Params?.Name ?? string.Empty, e);
throw;
}
});
ServerCapabilities.Prompts.ListChanged = listChanged;
SetHandler(
RequestMethods.PromptsList,
listPromptsHandler,
McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,
McpJsonUtilities.JsonContext.Default.ListPromptsResult);
SetHandler(
RequestMethods.PromptsGet,
getPromptHandler,
McpJsonUtilities.JsonContext.Default.GetPromptRequestParams,
McpJsonUtilities.JsonContext.Default.GetPromptResult);
}
private void ConfigureTools(McpServerOptions options)
{
var listToolsHandler = options.Handlers.ListToolsHandler;
var callToolHandler = options.Handlers.CallToolHandler;
var tools = options.ToolCollection;
var toolsCapability = options.Capabilities?.Tools;
if (listToolsHandler is null && callToolHandler is null && tools is null &&
toolsCapability is null)
{
return;
}
ServerCapabilities.Tools = new();
listToolsHandler ??= (static async (_, __) => new ListToolsResult());
callToolHandler ??= (static async (request, _) => throw new McpProtocolException($"Unknown tool: '{request.Params?.Name}'", McpErrorCode.InvalidParams));
var listChanged = toolsCapability?.ListChanged;
// Handle tools provided via DI by augmenting the handlers to incorporate them.
if (tools is not null)
{
var originalListToolsHandler = listToolsHandler;
listToolsHandler = async (request, cancellationToken) =>
{
ListToolsResult result = originalListToolsHandler is not null ?
await originalListToolsHandler(request, cancellationToken).ConfigureAwait(false) :
new();
if (request.Params?.Cursor is null)
{
foreach (var t in tools)
{
result.Tools.Add(t.ProtocolTool);
}
}
return result;
};
var originalCallToolHandler = callToolHandler;
var taskStore = options.TaskStore;
var sendNotifications = options.SendTaskStatusNotifications;
callToolHandler = async (request, cancellationToken) =>
{
if (request.MatchedPrimitive is McpServerTool tool)
{
var taskSupport = tool.ProtocolTool.Execution?.TaskSupport ?? ToolTaskSupport.Forbidden;
// Check if this is a task-augmented request
if (request.Params?.Task is { } taskMetadata)
{
// Validate tool-level task support
if (taskSupport is ToolTaskSupport.Forbidden)
{
throw new McpProtocolException(
$"Tool '{tool.ProtocolTool.Name}' does not support task-augmented execution.",
McpErrorCode.InvalidParams);
}
// Task augmentation requested - return CreateTaskResult
return await ExecuteToolAsTaskAsync(tool, request, taskMetadata, taskStore, sendNotifications, cancellationToken).ConfigureAwait(false);
}
// Validate that required task support is satisfied
if (taskSupport is ToolTaskSupport.Required)
{
throw new McpProtocolException(
$"Tool '{tool.ProtocolTool.Name}' requires task-augmented execution. " +
"Include a 'task' parameter with the request.",
McpErrorCode.InvalidParams);
}
// Normal synchronous execution
return await tool.InvokeAsync(request, cancellationToken).ConfigureAwait(false);
}
return await originalCallToolHandler(request, cancellationToken).ConfigureAwait(false);
};
listChanged = true;
}
listToolsHandler = BuildFilterPipeline(listToolsHandler, options.Filters.Request.ListToolsFilters);
callToolHandler = BuildFilterPipeline(callToolHandler, options.Filters.Request.CallToolFilters, handler =>
async (request, cancellationToken) =>
{
// Initial handler that sets MatchedPrimitive
if (request.Params?.Name is { } toolName && tools is not null &&
tools.TryGetPrimitive(toolName, out var tool))
{
request.MatchedPrimitive = tool;
}
try
{
var result = await handler(request, cancellationToken).ConfigureAwait(false);
// Don't log here for task-augmented calls; logging happens asynchronously
// in ExecuteToolAsTaskAsync when the tool actually completes.
if (result.Task is null)
{
ToolCallCompleted(request.Params?.Name ?? string.Empty, result.IsError is true);
}
return result;
}
catch (Exception e)
{
ToolCallError(request.Params?.Name ?? string.Empty, e);
if ((e is OperationCanceledException && cancellationToken.IsCancellationRequested) || e is McpProtocolException)
{
throw;
}
return new()
{
IsError = true,
Content = [new TextContentBlock
{
Text = e is McpException ?
$"An error occurred invoking '{request.Params?.Name}': {e.Message}" :
$"An error occurred invoking '{request.Params?.Name}'.",
}],
};
}
});
ServerCapabilities.Tools.ListChanged = listChanged;
SetHandler(
RequestMethods.ToolsList,
listToolsHandler,
McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,
McpJsonUtilities.JsonContext.Default.ListToolsResult);
SetHandler(
RequestMethods.ToolsCall,
callToolHandler,
McpJsonUtilities.JsonContext.Default.CallToolRequestParams,
McpJsonUtilities.JsonContext.Default.CallToolResult);
}
private void ConfigureTasks(McpServerOptions options)
{
var taskStore = options.TaskStore;
// If no task store is configured, tasks are not supported
if (taskStore is null)
{
return;
}
// Advertise task support in server capabilities
ServerCapabilities.Tasks = new McpTasksCapability
{
List = new ListMcpTasksCapability(),
Cancel = new CancelMcpTasksCapability(),
Requests = new RequestMcpTasksCapability
{
Tools = new ToolsMcpTasksCapability
{
Call = new CallToolMcpTasksCapability()
}
}
};
// tasks/get handler - Retrieve task status
McpRequestHandler<GetTaskRequestParams, McpTask> getTaskHandler = async (request, cancellationToken) =>
{
if (request.Params?.TaskId is not { } taskId)
{
throw new McpProtocolException("Missing required parameter 'taskId'", McpErrorCode.InvalidParams);
}
var task = await taskStore.GetTaskAsync(taskId, SessionId, cancellationToken).ConfigureAwait(false);
if (task is null)
{
throw new McpProtocolException($"Task not found: '{taskId}'", McpErrorCode.InvalidParams);
}
return task;
};
// tasks/result handler - Retrieve task result (blocking until terminal status)
McpRequestHandler<GetTaskPayloadRequestParams, JsonElement> getTaskResultHandler = (request, cancellationToken) =>
{
return new ValueTask<JsonElement>(GetTaskResultAsync(request, cancellationToken));
async Task<JsonElement> GetTaskResultAsync(RequestContext<GetTaskPayloadRequestParams> request, CancellationToken cancellationToken)
{
if (request.Params?.TaskId is not { } taskId)
{
throw new McpProtocolException("Missing required parameter 'taskId'", McpErrorCode.InvalidParams);
}
// Poll until task reaches terminal status
while (true)
{
McpTask? task = await taskStore.GetTaskAsync(taskId, SessionId, cancellationToken).ConfigureAwait(false);
if (task is null)
{
throw new McpProtocolException($"Task not found: '{taskId}'", McpErrorCode.InvalidParams);
}
// If terminal, break and retrieve result
if (task.Status is McpTaskStatus.Completed or McpTaskStatus.Failed or McpTaskStatus.Cancelled)
{
break;
}
// Poll according to task's pollInterval (default 1 second)
var pollInterval = task.PollInterval ?? TimeSpan.FromSeconds(1);
await Task.Delay(pollInterval, cancellationToken).ConfigureAwait(false);
}
// Retrieve the stored result - already stored as JsonElement
return await taskStore.GetTaskResultAsync(taskId, SessionId, cancellationToken).ConfigureAwait(false);
}
};
// tasks/list handler - List tasks with pagination
McpRequestHandler<ListTasksRequestParams, ListTasksResult> listTasksHandler = async (request, cancellationToken) =>
{
var cursor = request.Params?.Cursor;
return await taskStore.ListTasksAsync(cursor, SessionId, cancellationToken).ConfigureAwait(false);
};
// tasks/cancel handler - Cancel a task
McpRequestHandler<CancelMcpTaskRequestParams, McpTask> cancelTaskHandler = async (request, cancellationToken) =>
{
if (request.Params?.TaskId is not { } taskId)
{
throw new McpProtocolException("Missing required parameter 'taskId'", McpErrorCode.InvalidParams);
}
// Signal cancellation if task is still running
_taskCancellationTokenProvider!.Cancel(taskId);
// Delegate to task store - it handles idempotent cancellation
var task = await taskStore.CancelTaskAsync(taskId, SessionId, cancellationToken).ConfigureAwait(false);
if (task is null)
{
throw new McpProtocolException($"Task not found: '{taskId}'", McpErrorCode.InvalidParams);
}
return task;
};
// Register handlers
SetHandler(
RequestMethods.TasksGet,
getTaskHandler,
McpJsonUtilities.JsonContext.Default.GetTaskRequestParams,
McpJsonUtilities.JsonContext.Default.McpTask);
SetHandler(
RequestMethods.TasksResult,
getTaskResultHandler,
McpJsonUtilities.JsonContext.Default.GetTaskPayloadRequestParams,
McpJsonUtilities.JsonContext.Default.JsonElement);
SetHandler(
RequestMethods.TasksList,
listTasksHandler,
McpJsonUtilities.JsonContext.Default.ListTasksRequestParams,
McpJsonUtilities.JsonContext.Default.ListTasksResult);
SetHandler(
RequestMethods.TasksCancel,
cancelTaskHandler,
McpJsonUtilities.JsonContext.Default.CancelMcpTaskRequestParams,
McpJsonUtilities.JsonContext.Default.McpTask);
}
private void ConfigureLogging(McpServerOptions options)
{
// We don't require that the handler be provided, as we always store the provided log level to the server.
var setLoggingLevelHandler = options.Handlers.SetLoggingLevelHandler;
// Apply filters to the handler
if (setLoggingLevelHandler is not null)
{
setLoggingLevelHandler = BuildFilterPipeline(setLoggingLevelHandler, options.Filters.Request.SetLoggingLevelFilters);
}
ServerCapabilities.Logging = new();
_requestHandlers.Set(
RequestMethods.LoggingSetLevel,
(request, jsonRpcRequest, cancellationToken) =>
{
// Store the provided level.
if (request is not null)
{
if (_loggingLevel is null)
{
Interlocked.CompareExchange(ref _loggingLevel, new(request.Level), null);
}
_loggingLevel.Value = request.Level;
}
// If a handler was provided, now delegate to it.
if (setLoggingLevelHandler is not null)
{
return InvokeHandlerAsync(setLoggingLevelHandler, request, jsonRpcRequest, cancellationToken);
}
// Otherwise, consider it handled.
return new ValueTask<EmptyResult>(EmptyResult.Instance);
},
McpJsonUtilities.JsonContext.Default.SetLevelRequestParams,
McpJsonUtilities.JsonContext.Default.EmptyResult);
}
private ValueTask<TResult> InvokeHandlerAsync<TParams, TResult>(
McpRequestHandler<TParams, TResult> handler,
TParams? args,
JsonRpcRequest jsonRpcRequest,
CancellationToken cancellationToken = default)
{
return _servicesScopePerRequest ?
InvokeScopedAsync(handler, args, jsonRpcRequest, cancellationToken) :
handler(new(new DestinationBoundMcpServer(this, jsonRpcRequest.Context?.RelatedTransport), jsonRpcRequest) { Params = args }, cancellationToken);
async ValueTask<TResult> InvokeScopedAsync(
McpRequestHandler<TParams, TResult> handler,
TParams? args,
JsonRpcRequest jsonRpcRequest,
CancellationToken cancellationToken)
{
var scope = Services?.GetService<IServiceScopeFactory>()?.CreateAsyncScope();
try
{
return await handler(
new RequestContext<TParams>(new DestinationBoundMcpServer(this, jsonRpcRequest.Context?.RelatedTransport), jsonRpcRequest)
{
Services = scope?.ServiceProvider ?? Services,
Params = args
},
cancellationToken).ConfigureAwait(false);
}
finally
{
if (scope is not null)
{
await scope.Value.DisposeAsync().ConfigureAwait(false);
}
}