-
Notifications
You must be signed in to change notification settings - Fork 680
Expand file tree
/
Copy pathMcpSessionHandler.cs
More file actions
952 lines (820 loc) · 40.8 KB
/
McpSessionHandler.cs
File metadata and controls
952 lines (820 loc) · 40.8 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
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Text.Json;
using System.Text.Json.Nodes;
#if !NET
using System.Threading.Channels;
#endif
namespace ModelContextProtocol;
/// <summary>
/// Class for managing an MCP JSON-RPC session. This covers both MCP clients and servers.
/// </summary>
internal sealed partial class McpSessionHandler : IAsyncDisposable
{
private static readonly Histogram<double> s_clientSessionDuration = Diagnostics.CreateDurationHistogram(
"mcp.client.session.duration", "Measures the duration of a client session.", longBuckets: true);
private static readonly Histogram<double> s_serverSessionDuration = Diagnostics.CreateDurationHistogram(
"mcp.server.session.duration", "Measures the duration of a server session.", longBuckets: true);
private static readonly Histogram<double> s_clientOperationDuration = Diagnostics.CreateDurationHistogram(
"mcp.client.operation.duration", "Measures the duration of outbound message.", longBuckets: false);
private static readonly Histogram<double> s_serverOperationDuration = Diagnostics.CreateDurationHistogram(
"mcp.server.operation.duration", "Measures the duration of inbound message processing.", longBuckets: false);
/// <summary>The latest version of the protocol supported by this implementation.</summary>
internal const string LatestProtocolVersion = "2025-11-25";
/// <summary>All protocol versions supported by this implementation.</summary>
internal static readonly string[] SupportedProtocolVersions =
[
"2024-11-05",
"2025-03-26",
"2025-06-18",
LatestProtocolVersion,
];
private readonly bool _isServer;
private readonly string _transportKind;
private readonly ITransport _transport;
private readonly RequestHandlers _requestHandlers;
private readonly NotificationHandlers _notificationHandlers;
private readonly long _sessionStartingTimestamp = Stopwatch.GetTimestamp();
private readonly DistributedContextPropagator _propagator = DistributedContextPropagator.Current;
/// <summary>Collection of requests sent on this session and waiting for responses.</summary>
private readonly ConcurrentDictionary<RequestId, TaskCompletionSource<JsonRpcMessage>> _pendingRequests = [];
/// <summary>
/// Collection of requests received on this session and currently being handled. The value provides a <see cref="CancellationTokenSource"/>
/// that can be used to request cancellation of the in-flight handler.
/// </summary>
private readonly ConcurrentDictionary<RequestId, CancellationTokenSource> _handlingRequests = new();
private readonly ILogger _logger;
// This _sessionId is solely used to identify the session in telemetry and logs.
private readonly string _sessionId = Guid.NewGuid().ToString("N");
private long _lastRequestId;
private CancellationTokenSource? _messageProcessingCts;
private Task? _messageProcessingTask;
/// <summary>
/// Initializes a new instance of the <see cref="McpSessionHandler"/> class.
/// </summary>
/// <param name="isServer">true if this is a server; false if it's a client.</param>
/// <param name="transport">An MCP transport implementation.</param>
/// <param name="endpointName">The name of the endpoint for logging and debug purposes.</param>
/// <param name="requestHandlers">A collection of request handlers.</param>
/// <param name="notificationHandlers">A collection of notification handlers.</param>
/// <param name="logger">The logger.</param>
public McpSessionHandler(
bool isServer,
ITransport transport,
string endpointName,
RequestHandlers requestHandlers,
NotificationHandlers notificationHandlers,
ILogger logger)
{
Throw.IfNull(transport);
_transportKind = transport switch
{
StdioClientSessionTransport or StdioServerTransport => "stdio",
StreamClientSessionTransport or StreamServerTransport => "stream",
SseClientSessionTransport or SseResponseStreamTransport => "sse",
StreamableHttpClientSessionTransport or StreamableHttpServerTransport or StreamableHttpPostTransport => "http",
_ => "unknownTransport"
};
_isServer = isServer;
_transport = transport;
EndpointName = endpointName;
_requestHandlers = requestHandlers;
_notificationHandlers = notificationHandlers;
_logger = logger ?? NullLogger.Instance;
LogSessionCreated(EndpointName, _sessionId, _transportKind);
}
/// <summary>
/// Gets and sets the name of the endpoint for logging and debug purposes.
/// </summary>
public string EndpointName { get; set; }
/// <summary>
/// Starts processing messages from the transport. This method will block until the transport is disconnected.
/// This is generally started in a background task or thread from the initialization logic of the derived class.
/// </summary>
public Task ProcessMessagesAsync(CancellationToken cancellationToken)
{
if (_messageProcessingTask is not null)
{
throw new InvalidOperationException("The message processing loop has already started.");
}
Debug.Assert(_messageProcessingCts is null);
_messageProcessingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_messageProcessingTask = ProcessMessagesCoreAsync(_messageProcessingCts.Token);
return _messageProcessingTask;
}
private async Task ProcessMessagesCoreAsync(CancellationToken cancellationToken)
{
try
{
await foreach (var message in _transport.MessageReader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
LogMessageRead(EndpointName, message.GetType().Name);
// Fire and forget the message handling to avoid blocking the transport.
if (message.Context?.ExecutionContext is null)
{
_ = ProcessMessageAsync();
}
else
{
// Flow the execution context from the HTTP request corresponding to this message if provided.
ExecutionContext.Run(message.Context.ExecutionContext, _ => _ = ProcessMessageAsync(), null);
}
async Task ProcessMessageAsync()
{
JsonRpcMessageWithId? messageWithId = message as JsonRpcMessageWithId;
CancellationTokenSource? combinedCts = null;
try
{
// Register before we yield, so that the tracking is guaranteed to be there
// when subsequent messages arrive, even if the asynchronous processing happens
// out of order.
if (messageWithId is not null)
{
combinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_handlingRequests[messageWithId.Id] = combinedCts;
}
// If we await the handler without yielding first, the transport may not be able to read more messages,
// which could lead to a deadlock if the handler sends a message back.
#if NET
await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);
#else
await default(ForceYielding);
#endif
// Handle the message.
await HandleMessageAsync(message, combinedCts?.Token ?? cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
// Only send responses for request errors that aren't user-initiated cancellation.
bool isUserCancellation =
ex is OperationCanceledException &&
!cancellationToken.IsCancellationRequested &&
combinedCts?.IsCancellationRequested is true;
if (!isUserCancellation && message is JsonRpcRequest request)
{
JsonRpcErrorDetail detail = ex switch
{
UrlElicitationRequiredException urlException => new()
{
Code = (int)urlException.ErrorCode,
Message = urlException.Message,
Data = urlException.CreateErrorDataNode(),
},
McpProtocolException mcpProtocolException => new()
{
Code = (int)mcpProtocolException.ErrorCode,
Message = mcpProtocolException.Message,
Data = ConvertExceptionData(mcpProtocolException.Data),
},
McpException mcpException => new()
{
Code = (int)McpErrorCode.InternalError,
Message = mcpException.Message,
},
_ => new()
{
Code = (int)McpErrorCode.InternalError,
Message = "An error occurred.",
},
};
var errorMessage = new JsonRpcError
{
Id = request.Id,
JsonRpc = "2.0",
Error = detail,
Context = new JsonRpcMessageContext { RelatedTransport = request.Context?.RelatedTransport },
};
await SendMessageAsync(errorMessage, cancellationToken).ConfigureAwait(false);
}
else if (ex is not OperationCanceledException)
{
if (_logger.IsEnabled(LogLevel.Trace))
{
LogMessageHandlerExceptionSensitive(EndpointName, message.GetType().Name, JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage), ex);
}
else
{
LogMessageHandlerException(EndpointName, message.GetType().Name, ex);
}
}
}
finally
{
if (messageWithId is not null)
{
_handlingRequests.TryRemove(messageWithId.Id, out _);
combinedCts!.Dispose();
}
}
}
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// Normal shutdown
LogEndpointMessageProcessingCanceled(EndpointName);
}
finally
{
// Fail any pending requests, as they'll never be satisfied.
foreach (var entry in _pendingRequests)
{
entry.Value.TrySetException(new IOException("The server shut down unexpectedly."));
}
}
}
private async Task HandleMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken)
{
Histogram<double> durationMetric = _isServer ? s_serverOperationDuration : s_clientOperationDuration;
string method = GetMethodName(message);
long? startingTimestamp = durationMetric.Enabled ? Stopwatch.GetTimestamp() : null;
Activity? activity = Diagnostics.ShouldInstrumentMessage(message) ?
Diagnostics.ActivitySource.StartActivity(
CreateActivityName(method),
ActivityKind.Server,
parentContext: _propagator.ExtractActivityContext(message),
links: Diagnostics.ActivityLinkFromCurrent()) :
null;
TagList tags = default;
bool addTags = activity is { IsAllDataRequested: true } || startingTimestamp is not null;
try
{
if (addTags)
{
AddTags(ref tags, activity, message, method);
}
switch (message)
{
case JsonRpcRequest request:
LogRequestHandlerCalled(EndpointName, request.Method);
long requestStartingTimestamp = Stopwatch.GetTimestamp();
try
{
var result = await HandleRequest(request, cancellationToken).ConfigureAwait(false);
LogRequestHandlerCompleted(EndpointName, request.Method, GetElapsed(requestStartingTimestamp).TotalMilliseconds);
AddResponseTags(ref tags, activity, result, method);
}
catch (Exception ex)
{
LogRequestHandlerException(EndpointName, request.Method, GetElapsed(requestStartingTimestamp).TotalMilliseconds, ex);
throw;
}
break;
case JsonRpcNotification notification:
await HandleNotification(notification, cancellationToken).ConfigureAwait(false);
break;
case JsonRpcMessageWithId messageWithId:
HandleMessageWithId(message, messageWithId);
break;
default:
LogEndpointHandlerUnexpectedMessageType(EndpointName, message.GetType().Name);
break;
}
}
catch (Exception e) when (addTags)
{
AddExceptionTags(ref tags, activity, e);
throw;
}
finally
{
FinalizeDiagnostics(activity, startingTimestamp, durationMetric, ref tags);
}
}
private async Task HandleNotification(JsonRpcNotification notification, CancellationToken cancellationToken)
{
// Special-case cancellation to cancel a pending operation. (We'll still subsequently invoke a user-specified handler if one exists.)
if (notification.Method == NotificationMethods.CancelledNotification)
{
try
{
if (GetCancelledNotificationParams(notification.Params) is CancelledNotificationParams cn &&
_handlingRequests.TryGetValue(cn.RequestId, out var cts))
{
await cts.CancelAsync().ConfigureAwait(false);
LogRequestCanceled(EndpointName, cn.RequestId, cn.Reason);
}
}
catch
{
// "Invalid cancellation notifications SHOULD be ignored"
}
}
// Handle user-defined notifications.
await _notificationHandlers.InvokeHandlers(notification.Method, notification, cancellationToken).ConfigureAwait(false);
}
private void HandleMessageWithId(JsonRpcMessage message, JsonRpcMessageWithId messageWithId)
{
if (_pendingRequests.TryRemove(messageWithId.Id, out var tcs))
{
tcs.TrySetResult(message);
}
else
{
LogNoRequestFoundForMessageWithId(EndpointName, messageWithId.Id);
}
}
private async Task<JsonNode?> HandleRequest(JsonRpcRequest request, CancellationToken cancellationToken)
{
if (!_requestHandlers.TryGetValue(request.Method, out var handler))
{
LogNoHandlerFoundForRequest(EndpointName, request.Method);
throw new McpProtocolException($"Method '{request.Method}' is not available.", McpErrorCode.MethodNotFound);
}
JsonNode? result = await handler(request, cancellationToken).ConfigureAwait(false);
await SendMessageAsync(new JsonRpcResponse
{
Id = request.Id,
Result = result,
Context = request.Context,
}, cancellationToken).ConfigureAwait(false);
return result;
}
private CancellationTokenRegistration RegisterCancellation(CancellationToken cancellationToken, JsonRpcRequest request)
{
if (!cancellationToken.CanBeCanceled)
{
return default;
}
return cancellationToken.Register(static objState =>
{
var state = (Tuple<McpSessionHandler, JsonRpcRequest>)objState!;
_ = state.Item1.SendMessageAsync(new JsonRpcNotification
{
Method = NotificationMethods.CancelledNotification,
Params = JsonSerializer.SerializeToNode(new CancelledNotificationParams { RequestId = state.Item2.Id }, McpJsonUtilities.JsonContext.Default.CancelledNotificationParams),
Context = new JsonRpcMessageContext { RelatedTransport = state.Item2.Context?.RelatedTransport },
});
}, Tuple.Create(this, request));
}
public IAsyncDisposable RegisterNotificationHandler(string method, Func<JsonRpcNotification, CancellationToken, ValueTask> handler)
{
Throw.IfNullOrWhiteSpace(method);
Throw.IfNull(handler);
return _notificationHandlers.Register(method, handler);
}
/// <summary>
/// Sends a JSON-RPC request to the server.
/// It is strongly recommended use the capability-specific methods instead of this one.
/// Use this method for custom requests or those not yet covered explicitly by the endpoint implementation.
/// </summary>
/// <param name="request">The JSON-RPC request to send.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task containing the server's response.</returns>
public async Task<JsonRpcResponse> SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken)
{
Throw.IfNull(request);
cancellationToken.ThrowIfCancellationRequested();
Histogram<double> durationMetric = _isServer ? s_serverOperationDuration : s_clientOperationDuration;
string method = request.Method;
long? startingTimestamp = durationMetric.Enabled ? Stopwatch.GetTimestamp() : null;
using Activity? activity = Diagnostics.ShouldInstrumentMessage(request) ?
Diagnostics.ActivitySource.StartActivity(McpSessionHandler.CreateActivityName(method), ActivityKind.Client) :
null;
// Set request ID
if (request.Id.Id is null)
{
request = request.WithId(new RequestId(Interlocked.Increment(ref _lastRequestId)));
}
_propagator.InjectActivityContext(activity, request);
TagList tags = default;
bool addTags = activity is { IsAllDataRequested: true } || startingTimestamp is not null;
var tcs = new TaskCompletionSource<JsonRpcMessage>(TaskCreationOptions.RunContinuationsAsynchronously);
_pendingRequests[request.Id] = tcs;
try
{
if (addTags)
{
AddTags(ref tags, activity, request, method);
}
if (_logger.IsEnabled(LogLevel.Trace))
{
LogSendingRequestSensitive(EndpointName, request.Method, JsonSerializer.Serialize(request, McpJsonUtilities.JsonContext.Default.JsonRpcMessage));
}
else
{
LogSendingRequest(EndpointName, request.Method);
}
await SendToRelatedTransportAsync(request, cancellationToken).ConfigureAwait(false);
// Now that the request has been sent, register for cancellation. If we registered before,
// a cancellation request could arrive before the server knew about that request ID, in which
// case the server could ignore it.
LogRequestSentAwaitingResponse(EndpointName, request.Method, request.Id);
JsonRpcMessage? response;
using (var registration = RegisterCancellation(cancellationToken, request))
{
response = await tcs.Task.WaitAsync(cancellationToken).ConfigureAwait(false);
}
if (response is JsonRpcError error)
{
LogSendingRequestFailed(EndpointName, request.Method, error.Error.Message, error.Error.Code);
throw CreateRemoteProtocolException(error);
}
if (response is JsonRpcResponse success)
{
if (addTags)
{
AddResponseTags(ref tags, activity, success.Result, method);
}
if (_logger.IsEnabled(LogLevel.Trace))
{
LogRequestResponseReceivedSensitive(EndpointName, request.Method, success.Result?.ToJsonString() ?? "null");
}
else
{
LogRequestResponseReceived(EndpointName, request.Method);
}
return success;
}
// Unexpected response type
LogSendingRequestInvalidResponseType(EndpointName, request.Method);
throw new McpException("Invalid response type");
}
catch (Exception ex) when (addTags)
{
AddExceptionTags(ref tags, activity, ex);
throw;
}
finally
{
_pendingRequests.TryRemove(request.Id, out _);
FinalizeDiagnostics(activity, startingTimestamp, durationMetric, ref tags);
}
}
public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)
{
Throw.IfNull(message);
cancellationToken.ThrowIfCancellationRequested();
Histogram<double> durationMetric = _isServer ? s_serverOperationDuration : s_clientOperationDuration;
string method = GetMethodName(message);
long? startingTimestamp = durationMetric.Enabled ? Stopwatch.GetTimestamp() : null;
using Activity? activity = Diagnostics.ShouldInstrumentMessage(message) ?
Diagnostics.ActivitySource.StartActivity(McpSessionHandler.CreateActivityName(method), ActivityKind.Client) :
null;
TagList tags = default;
bool addTags = activity is { IsAllDataRequested: true } || startingTimestamp is not null;
// propagate trace context
_propagator?.InjectActivityContext(activity, message);
try
{
if (addTags)
{
AddTags(ref tags, activity, message, method);
}
if (_logger.IsEnabled(LogLevel.Trace))
{
LogSendingMessageSensitive(EndpointName, JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage));
}
else
{
LogSendingMessage(EndpointName);
}
await SendToRelatedTransportAsync(message, cancellationToken).ConfigureAwait(false);
// If the sent notification was a cancellation notification, cancel the pending request's await, as either the
// server won't be sending a response, or per the specification, the response should be ignored. There are inherent
// race conditions here, so it's possible and allowed for the operation to complete before we get to this point.
if (message is JsonRpcNotification { Method: NotificationMethods.CancelledNotification } notification &&
GetCancelledNotificationParams(notification.Params) is CancelledNotificationParams cn &&
_pendingRequests.TryRemove(cn.RequestId, out var tcs))
{
tcs.TrySetCanceled(default);
}
}
catch (Exception ex) when (addTags)
{
AddExceptionTags(ref tags, activity, ex);
throw;
}
finally
{
FinalizeDiagnostics(activity, startingTimestamp, durationMetric, ref tags);
}
}
// The JsonRpcMessage should be sent over the RelatedTransport if set. This is used to support the
// Streamable HTTP transport where the specification states that the server SHOULD include JSON-RPC responses in
// the HTTP response body for the POST request containing the corresponding JSON-RPC request.
private Task SendToRelatedTransportAsync(JsonRpcMessage message, CancellationToken cancellationToken)
=> (message.Context?.RelatedTransport ?? _transport).SendMessageAsync(message, cancellationToken);
private static CancelledNotificationParams? GetCancelledNotificationParams(JsonNode? notificationParams)
{
try
{
return JsonSerializer.Deserialize(notificationParams, McpJsonUtilities.JsonContext.Default.CancelledNotificationParams);
}
catch
{
return null;
}
}
private static string CreateActivityName(string method) => method;
private static string GetMethodName(JsonRpcMessage message) =>
message switch
{
JsonRpcRequest request => request.Method,
JsonRpcNotification notification => notification.Method,
_ => "unknownMethod"
};
private void AddTags(ref TagList tags, Activity? activity, JsonRpcMessage message, string method)
{
tags.Add("mcp.method.name", method);
tags.Add("network.transport", _transportKind);
// TODO: When using SSE transport, add:
// - server.address and server.port on client spans and metrics
// - client.address and client.port on server spans (not metrics because of cardinality) when using SSE transport
if (activity is { IsAllDataRequested: true })
{
// session and request id have high cardinality, so not applying to metric tags
activity.AddTag("mcp.session.id", _sessionId);
if (message is JsonRpcMessageWithId withId)
{
activity.AddTag("mcp.request.id", withId.Id.Id?.ToString());
}
}
JsonObject? paramsObj = message switch
{
JsonRpcRequest request => request.Params as JsonObject,
JsonRpcNotification notification => notification.Params as JsonObject,
_ => null
};
if (paramsObj == null)
{
return;
}
string? target = null;
switch (method)
{
case RequestMethods.ToolsCall:
case RequestMethods.PromptsGet:
target = GetStringProperty(paramsObj, "name");
if (target is not null)
{
tags.Add(method == RequestMethods.ToolsCall ? "mcp.tool.name" : "mcp.prompt.name", target);
}
break;
case RequestMethods.ResourcesRead:
case RequestMethods.ResourcesSubscribe:
case RequestMethods.ResourcesUnsubscribe:
case NotificationMethods.ResourceUpdatedNotification:
target = GetStringProperty(paramsObj, "uri");
if (target is not null)
{
tags.Add("mcp.resource.uri", target);
}
break;
}
if (activity is { IsAllDataRequested: true })
{
activity.DisplayName = target == null ? method : $"{method} {target}";
}
}
private static void AddExceptionTags(ref TagList tags, Activity? activity, Exception e)
{
if (e is AggregateException ae && ae.InnerException is not null and not AggregateException)
{
e = ae.InnerException;
}
int? intErrorCode =
(int?)((e as McpProtocolException)?.ErrorCode) is int errorCode ? errorCode :
e is JsonException ? (int)McpErrorCode.ParseError :
null;
string? errorType = intErrorCode?.ToString() ?? e.GetType().FullName;
tags.Add("error.type", errorType);
if (intErrorCode is not null)
{
tags.Add("rpc.jsonrpc.error_code", errorType);
}
if (activity is { IsAllDataRequested: true })
{
activity.SetStatus(ActivityStatusCode.Error, e.Message);
}
}
private static void AddResponseTags(ref TagList tags, Activity? activity, JsonNode? response, string method)
{
if (response is JsonObject jsonObject
&& jsonObject.TryGetPropertyValue("isError", out var isError)
&& isError?.GetValueKind() == JsonValueKind.True)
{
if (activity is { IsAllDataRequested: true })
{
string? content = null;
if (jsonObject.TryGetPropertyValue("content", out var prop) && prop != null)
{
content = prop.ToJsonString();
}
activity.SetStatus(ActivityStatusCode.Error, content);
}
tags.Add("error.type", method == RequestMethods.ToolsCall ? "tool_error" : "_OTHER");
}
}
private static void FinalizeDiagnostics(
Activity? activity, long? startingTimestamp, Histogram<double> durationMetric, ref TagList tags)
{
try
{
if (startingTimestamp is not null)
{
durationMetric.Record(GetElapsed(startingTimestamp.Value).TotalSeconds, tags);
}
if (activity is { IsAllDataRequested: true })
{
foreach (var tag in tags)
{
activity.AddTag(tag.Key, tag.Value);
}
}
}
finally
{
activity?.Dispose();
}
}
public async ValueTask DisposeAsync()
{
Histogram<double> durationMetric = _isServer ? s_serverSessionDuration : s_clientSessionDuration;
if (durationMetric.Enabled)
{
TagList tags = default;
tags.Add("network.transport", _transportKind);
// TODO: Add server.address and server.port on client-side when using SSE transport,
// client.* attributes are not added to metrics because of cardinality
durationMetric.Record(GetElapsed(_sessionStartingTimestamp).TotalSeconds, tags);
}
foreach (var entry in _pendingRequests)
{
entry.Value.TrySetCanceled();
}
_pendingRequests.Clear();
if (_messageProcessingCts is not null)
{
await _messageProcessingCts.CancelAsync().ConfigureAwait(false);
}
if (_messageProcessingTask is not null)
{
try
{
await _messageProcessingTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Ignore cancellation
}
}
LogSessionDisposed(EndpointName, _sessionId, _transportKind);
}
#if !NET
private static readonly double s_timestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
#endif
private static TimeSpan GetElapsed(long startingTimestamp) =>
#if NET
Stopwatch.GetElapsedTime(startingTimestamp);
#else
new((long)(s_timestampToTicks * (Stopwatch.GetTimestamp() - startingTimestamp)));
#endif
private static string? GetStringProperty(JsonObject parameters, string propName)
{
if (parameters.TryGetPropertyValue(propName, out var prop) && prop?.GetValueKind() is JsonValueKind.String)
{
return prop.GetValue<string>();
}
return null;
}
private static McpProtocolException CreateRemoteProtocolException(JsonRpcError error)
{
string formattedMessage = $"Request failed (remote): {error.Error.Message}";
var errorCode = (McpErrorCode)error.Error.Code;
McpProtocolException exception;
if (errorCode == McpErrorCode.UrlElicitationRequired &&
UrlElicitationRequiredException.TryCreateFromError(formattedMessage, error.Error, out var urlException))
{
exception = urlException;
}
else
{
exception = new McpProtocolException(formattedMessage, errorCode);
}
// Populate exception.Data with the error data if present.
// When deserializing JSON, Data will be a JsonElement.
// We extract primitive values (strings, numbers, bools) for broader compatibility,
// as JsonElement is not [Serializable] and cannot be stored in Exception.Data on .NET Framework.
if (error.Error.Data is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object)
{
foreach (var property in jsonElement.EnumerateObject())
{
object? value = property.Value.ValueKind switch
{
JsonValueKind.String => property.Value.GetString(),
JsonValueKind.Number => property.Value.GetDouble(),
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Null => null,
#if NET
// Objects and arrays are stored as JsonElement on .NET Core only
_ => property.Value,
#else
// Skip objects/arrays on .NET Framework as JsonElement is not serializable
_ => (object?)null,
#endif
};
if (value is not null || property.Value.ValueKind == JsonValueKind.Null)
{
exception.Data[property.Name] = value;
}
}
}
return exception;
}
/// <summary>
/// Converts the <see cref="Exception.Data"/> dictionary to a serializable <see cref="Dictionary{TKey, TValue}"/>.
/// Returns null if the data dictionary is empty or contains no string keys with serializable values.
/// </summary>
/// <remarks>
/// <para>
/// Only entries with string keys are included in the result. Entries with non-string keys are ignored.
/// </para>
/// <para>
/// Each value is serialized to a <see cref="JsonElement"/> to ensure it can be safely included in the
/// JSON-RPC error response. Values that cannot be serialized are silently skipped.
/// </para>
/// </remarks>
private static Dictionary<string, JsonElement>? ConvertExceptionData(System.Collections.IDictionary data)
{
if (data.Count == 0)
{
return null;
}
var typeInfo = McpJsonUtilities.DefaultOptions.GetTypeInfo<object?>();
Dictionary<string, JsonElement>? result = null;
foreach (System.Collections.DictionaryEntry entry in data)
{
if (entry.Key is string key)
{
try
{
// Serialize each value upfront to catch any serialization issues
// before attempting to send the message. If the value is already a
// JsonElement, use it directly.
var element = entry.Value is JsonElement je
? je
: JsonSerializer.SerializeToElement(entry.Value, typeInfo);
result ??= new(data.Count);
result[key] = element;
}
catch (Exception ex) when (ex is JsonException or NotSupportedException)
{
// Skip non-serializable values silently
}
}
}
return result?.Count > 0 ? result : null;
}
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} message processing canceled.")]
private partial void LogEndpointMessageProcessingCanceled(string endpointName);
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} method '{Method}' request handler called.")]
private partial void LogRequestHandlerCalled(string endpointName, string method);
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} method '{Method}' request handler completed in {ElapsedMilliseconds}ms.")]
private partial void LogRequestHandlerCompleted(string endpointName, string method, double elapsedMilliseconds);
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} method '{Method}' request handler failed in {ElapsedMilliseconds}ms.")]
private partial void LogRequestHandlerException(string endpointName, string method, double elapsedMilliseconds, Exception exception);
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} received request for unknown request ID '{RequestId}'.")]
private partial void LogNoRequestFoundForMessageWithId(string endpointName, RequestId requestId);
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} request failed for method '{Method}': {ErrorMessage} ({ErrorCode}).")]
private partial void LogSendingRequestFailed(string endpointName, string method, string errorMessage, int errorCode);
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} received invalid response for method '{Method}'.")]
private partial void LogSendingRequestInvalidResponseType(string endpointName, string method);
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName} sending method '{Method}' request.")]
private partial void LogSendingRequest(string endpointName, string method);
[LoggerMessage(Level = LogLevel.Trace, Message = "{EndpointName} sending method '{Method}' request. Request: '{Request}'.")]
private partial void LogSendingRequestSensitive(string endpointName, string method, string request);
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} canceled request '{RequestId}' per client notification. Reason: '{Reason}'.")]
private partial void LogRequestCanceled(string endpointName, RequestId requestId, string? reason);
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName} Request response received for method {method}")]
private partial void LogRequestResponseReceived(string endpointName, string method);
[LoggerMessage(Level = LogLevel.Trace, Message = "{EndpointName} Request response received for method {method}. Response: '{Response}'.")]
private partial void LogRequestResponseReceivedSensitive(string endpointName, string method, string response);
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName} read {MessageType} message from channel.")]
private partial void LogMessageRead(string endpointName, string messageType);
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} message handler {MessageType} failed.")]
private partial void LogMessageHandlerException(string endpointName, string messageType, Exception exception);
[LoggerMessage(Level = LogLevel.Trace, Message = "{EndpointName} message handler {MessageType} failed. Message: '{Message}'.")]
private partial void LogMessageHandlerExceptionSensitive(string endpointName, string messageType, string message, Exception exception);
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} received unexpected {MessageType} message type.")]
private partial void LogEndpointHandlerUnexpectedMessageType(string endpointName, string messageType);
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} received request for method '{Method}', but no handler is available.")]
private partial void LogNoHandlerFoundForRequest(string endpointName, string method);
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName} waiting for response to request '{RequestId}' for method '{Method}'.")]
private partial void LogRequestSentAwaitingResponse(string endpointName, string method, RequestId requestId);
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName} sending message.")]
private partial void LogSendingMessage(string endpointName);
[LoggerMessage(Level = LogLevel.Trace, Message = "{EndpointName} sending message. Message: '{Message}'.")]
private partial void LogSendingMessageSensitive(string endpointName, string message);
[LoggerMessage(Level = LogLevel.Trace, Message = "{EndpointName} session {SessionId} created with transport {TransportKind}")]
private partial void LogSessionCreated(string endpointName, string sessionId, string transportKind);
[LoggerMessage(Level = LogLevel.Trace, Message = "{EndpointName} session {SessionId} disposed with transport {TransportKind}")]
private partial void LogSessionDisposed(string endpointName, string sessionId, string transportKind);
}