Skip to content

Commit fb61315

Browse files
author
Akbar Dızajı
committed
Add opt-in exception summarization for server-side logging
Adds McpServerOptions.ExceptionSummarizer, an optional delegate that maps an Exception to a sanitized description. When set, server-side failure paths log that description instead of attaching the raw Exception. When null (the default), every callsite logs exactly as before. The delegate runs only when the level of the event being written is enabled, matching the enabled-check the generated logging methods perform internally, and each summarized variant reuses its raw counterpart's EventName so both emit the same EventId. Core stays free of a hard dependency on Microsoft.Extensions.Diagnostics.ExceptionSummarization; the DI package takes the package reference and McpServerOptionsSetup populates the delegate from an optionally-registered IExceptionSummarizer. Fixes #1690
1 parent 15f8b2d commit fb61315

9 files changed

Lines changed: 702 additions & 17 deletions

File tree

Directory.Packages.props

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
<PackageVersion Include="Microsoft.Extensions.AI.Abstractions" Version="$(MicrosoftExtensionsVersion)" />
1414
<PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="$(System10Version)" />
1515
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="$(System10Version)" />
16+
<PackageVersion Include="Microsoft.Extensions.Diagnostics.ExceptionSummarization" Version="10.8.0" />
1617
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="$(System10Version)" />
1718
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="$(System10Version)" />
1819
</ItemGroup>

docs/concepts/logging/logging.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,42 @@ Lastly, the client must configure a notification handler for <xref:ModelContextP
8585
The following example simply writes the log messages to the console.
8686

8787
[!code-csharp[](samples/client/Program.cs?name=snippet_LoggingHandler)]
88+
89+
### Sanitizing exceptions in the server's own diagnostic logs
90+
91+
Separately from the MCP Logging utility described above, the server writes its own diagnostic logs to the
92+
[ILogger] it was configured with. When a request handler, tool, prompt, or resource throws, those logs include the
93+
raw <xref:System.Exception>, which most logging providers render as the exception message plus its stack trace.
94+
That output can contain sensitive or overly detailed runtime data.
95+
96+
Set <xref:ModelContextProtocol.Server.McpServerOptions.ExceptionSummarizer> to log a sanitized description instead.
97+
When it is set, the failure paths log only the string the delegate returns, and the raw exception is not attached to
98+
the log entry. The default is `null`, which preserves the existing behavior of logging the raw exception.
99+
100+
```csharp
101+
builder.Services.AddMcpServer(options =>
102+
{
103+
options.ExceptionSummarizer = ex => ex.GetType().Name;
104+
});
105+
```
106+
107+
The summarized and raw forms of each event share one `EventId`, so filters and alerts keyed on `EventId` behave the
108+
same whether or not a summarizer is configured. The delegate runs only when the corresponding log level is enabled,
109+
so it costs nothing on a level that is filtered out.
110+
111+
The `ModelContextProtocol` package also integrates with the standard
112+
[Microsoft.Extensions.Diagnostics.ExceptionSummarization](https://learn.microsoft.com/dotnet/api/microsoft.extensions.diagnostics.exceptionsummarization)
113+
abstractions. If an `IExceptionSummarizer` is registered in the container and `ExceptionSummarizer` has not been set
114+
explicitly, the SDK populates it with `"{ExceptionType}: {Description}"` taken from the `ExceptionSummary`:
115+
116+
```csharp
117+
builder.Services.AddExceptionSummarizer(b => b.AddHttpProvider());
118+
builder.Services.AddMcpServer();
119+
```
120+
121+
Both of those fields are documented as free of privacy-sensitive information. `ExceptionSummary.AdditionalDetails` is
122+
not, and `ExceptionSummary.ToString()` appends it, so neither is used. The exception type is included because
123+
`Description` on its own is `"Unknown"` for exception types that no registered provider handles.
124+
125+
If the delegate throws or returns `null`, the SDK falls back to logging the raw exception, so a faulty summarizer
126+
can never fail the session.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using System.Diagnostics.CodeAnalysis;
2+
3+
namespace ModelContextProtocol;
4+
5+
/// <summary>
6+
/// Provides the single, shared entry point used by exception-logging callsites to apply an
7+
/// optional user-supplied exception summarizer.
8+
/// </summary>
9+
internal static class ExceptionSummaryHelper
10+
{
11+
/// <summary>
12+
/// Attempts to produce a sanitized description of <paramref name="exception"/> using <paramref name="summarizer"/>.
13+
/// </summary>
14+
/// <returns>
15+
/// <see langword="true"/> if a summary was produced and the caller should log it in place of
16+
/// <paramref name="exception"/>; otherwise, <see langword="false"/>, in which case the caller must log
17+
/// <paramref name="exception"/> exactly as it would have without a summarizer. The summarizer is supplied
18+
/// by the host, so throwing or returning <see langword="null"/> both fall back rather than disrupt the session.
19+
/// </returns>
20+
public static bool TrySummarize(Func<Exception, string>? summarizer, Exception exception, [NotNullWhen(true)] out string? summary)
21+
{
22+
if (summarizer is not null)
23+
{
24+
try
25+
{
26+
summary = summarizer(exception);
27+
return summary is not null;
28+
}
29+
catch
30+
{
31+
// A faulty summarizer must never fail logging; fall back to the raw exception.
32+
}
33+
}
34+
35+
summary = null;
36+
return false;
37+
}
38+
}

src/ModelContextProtocol.Core/McpSessionHandler.cs

Lines changed: 75 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ internal static bool SupportsNaturalOutputSchemas(string? protocolVersion)
9595
/// </summary>
9696
private readonly ConcurrentDictionary<RequestId, CancellationTokenSource> _handlingRequests = new();
9797
private readonly ILogger _logger;
98+
private readonly Func<Exception, string>? _exceptionSummarizer;
9899

99100
// This _sessionId is solely used to identify the session in telemetry and logs.
100101
private readonly string _sessionId = Guid.NewGuid().ToString("N");
@@ -115,6 +116,10 @@ internal static bool SupportsNaturalOutputSchemas(string? protocolVersion)
115116
/// <param name="incomingMessageFilter">A filter that wraps incoming message processing. Takes the next handler and returns a wrapped handler. If null, a passthrough filter is used.</param>
116117
/// <param name="outgoingMessageFilter">A filter that wraps outgoing message processing. Takes the next handler and returns a wrapped handler. If null, a passthrough filter is used.</param>
117118
/// <param name="logger">The logger.</param>
119+
/// <param name="exceptionSummarizer">
120+
/// An optional callback that produces a sanitized description of an exception. When non-<see langword="null"/>,
121+
/// exception logging callsites log that description instead of the raw <see cref="Exception"/>.
122+
/// </param>
118123
public McpSessionHandler(
119124
bool isServer,
120125
ITransport transport,
@@ -123,7 +128,8 @@ public McpSessionHandler(
123128
NotificationHandlers notificationHandlers,
124129
JsonRpcMessageFilter? incomingMessageFilter,
125130
JsonRpcMessageFilter? outgoingMessageFilter,
126-
ILogger logger)
131+
ILogger logger,
132+
Func<Exception, string>? exceptionSummarizer = null)
127133
{
128134
Throw.IfNull(transport);
129135

@@ -144,6 +150,7 @@ public McpSessionHandler(
144150
_incomingMessageFilter = incomingMessageFilter ?? (next => next);
145151
_outgoingMessageFilter = outgoingMessageFilter ?? (next => next);
146152
_logger = logger;
153+
_exceptionSummarizer = exceptionSummarizer;
147154

148155
// ping was removed in the 2026-07-28 protocol revision (SEP-2575). On the 2026-07-28 or later version,
149156
// return MethodNotFound; on an older version, the per-spec behavior is to always answer
@@ -323,14 +330,7 @@ ex is OperationCanceledException &&
323330
}
324331
else if (ex is not OperationCanceledException)
325332
{
326-
if (_logger.IsEnabled(LogLevel.Trace))
327-
{
328-
LogMessageHandlerExceptionSensitive(EndpointName, message.GetType().Name, JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage), ex);
329-
}
330-
else
331-
{
332-
LogMessageHandlerException(EndpointName, message.GetType().Name, ex);
333-
}
333+
LogMessageHandlerFailure(message, ex);
334334
}
335335
}
336336
finally
@@ -470,7 +470,7 @@ await _incomingMessageFilter(async (msg, ct) =>
470470
}
471471
catch (Exception ex)
472472
{
473-
LogRequestHandlerException(EndpointName, request.Method, GetElapsed(requestStartingTimestamp).TotalMilliseconds, ex);
473+
LogRequestHandlerFailure(EndpointName, request.Method, GetElapsed(requestStartingTimestamp).TotalMilliseconds, ex);
474474
throw;
475475
}
476476

@@ -1280,9 +1280,68 @@ internal static McpProtocolException CreateRemoteProtocolExceptionFromError(Json
12801280
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} method '{Method}' request handler completed in {ElapsedMilliseconds}ms.")]
12811281
private partial void LogRequestHandlerCompleted(string endpointName, string method, double elapsedMilliseconds);
12821282

1283+
/// <summary>
1284+
/// Logs a failed request handler, substituting a sanitized description for the raw exception when a
1285+
/// summarizer is configured. The summarizer only runs when the event's level is enabled, matching the
1286+
/// enabled-check the generated logging methods perform internally.
1287+
/// </summary>
1288+
private void LogRequestHandlerFailure(string endpointName, string method, double elapsedMilliseconds, Exception exception)
1289+
{
1290+
if (_exceptionSummarizer is not null &&
1291+
_logger.IsEnabled(LogLevel.Warning) &&
1292+
ExceptionSummaryHelper.TrySummarize(_exceptionSummarizer, exception, out string? exceptionSummary))
1293+
{
1294+
LogRequestHandlerExceptionSummarized(endpointName, method, elapsedMilliseconds, exceptionSummary);
1295+
}
1296+
else
1297+
{
1298+
LogRequestHandlerException(endpointName, method, elapsedMilliseconds, exception);
1299+
}
1300+
}
1301+
1302+
/// <summary>
1303+
/// Logs a failed message handler. The trace-vs-warning selection is unchanged from the non-summarizing
1304+
/// path; only the payload differs. The summarizer runs only when the selected event's level is enabled.
1305+
/// </summary>
1306+
private void LogMessageHandlerFailure(JsonRpcMessage message, Exception exception)
1307+
{
1308+
string messageType = message.GetType().Name;
1309+
1310+
if (_logger.IsEnabled(LogLevel.Trace))
1311+
{
1312+
if (_exceptionSummarizer is not null &&
1313+
ExceptionSummaryHelper.TrySummarize(_exceptionSummarizer, exception, out string? exceptionSummary))
1314+
{
1315+
LogMessageHandlerExceptionSensitiveSummarized(EndpointName, messageType, exceptionSummary, JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage));
1316+
}
1317+
else
1318+
{
1319+
LogMessageHandlerExceptionSensitive(EndpointName, messageType, JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage), exception);
1320+
}
1321+
}
1322+
else if (_exceptionSummarizer is not null &&
1323+
_logger.IsEnabled(LogLevel.Warning) &&
1324+
ExceptionSummaryHelper.TrySummarize(_exceptionSummarizer, exception, out string? exceptionSummary))
1325+
{
1326+
LogMessageHandlerExceptionSummarized(EndpointName, messageType, exceptionSummary);
1327+
}
1328+
else
1329+
{
1330+
LogMessageHandlerException(EndpointName, messageType, exception);
1331+
}
1332+
}
1333+
1334+
// Each summarized variant names its raw counterpart as its EventName so the pair emits one EventId and
1335+
// one event name, keeping consumers that filter on EventId working when a summarizer is configured. The
1336+
// generator derives the numeric id from the event name, which defaults to the method name, so only the
1337+
// summarized variant declares EventName: declaring it on both trips SYSLIB1025.
1338+
12831339
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} method '{Method}' request handler failed in {ElapsedMilliseconds}ms.")]
12841340
private partial void LogRequestHandlerException(string endpointName, string method, double elapsedMilliseconds, Exception exception);
12851341

1342+
[LoggerMessage(Level = LogLevel.Warning, EventName = nameof(LogRequestHandlerException), Message = "{EndpointName} method '{Method}' request handler failed in {ElapsedMilliseconds}ms: {ExceptionSummary}.")]
1343+
private partial void LogRequestHandlerExceptionSummarized(string endpointName, string method, double elapsedMilliseconds, string exceptionSummary);
1344+
12861345
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} received request for unknown request ID '{RequestId}'.")]
12871346
private partial void LogNoRequestFoundForMessageWithId(string endpointName, RequestId requestId);
12881347

@@ -1313,9 +1372,15 @@ internal static McpProtocolException CreateRemoteProtocolExceptionFromError(Json
13131372
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} message handler {MessageType} failed.")]
13141373
private partial void LogMessageHandlerException(string endpointName, string messageType, Exception exception);
13151374

1375+
[LoggerMessage(Level = LogLevel.Warning, EventName = nameof(LogMessageHandlerException), Message = "{EndpointName} message handler {MessageType} failed: {ExceptionSummary}.")]
1376+
private partial void LogMessageHandlerExceptionSummarized(string endpointName, string messageType, string exceptionSummary);
1377+
13161378
[LoggerMessage(Level = LogLevel.Trace, Message = "{EndpointName} message handler {MessageType} failed. Message: '{Message}'.")]
13171379
private partial void LogMessageHandlerExceptionSensitive(string endpointName, string messageType, string message, Exception exception);
13181380

1381+
[LoggerMessage(Level = LogLevel.Trace, EventName = nameof(LogMessageHandlerExceptionSensitive), Message = "{EndpointName} message handler {MessageType} failed: {ExceptionSummary}. Message: '{Message}'.")]
1382+
private partial void LogMessageHandlerExceptionSensitiveSummarized(string endpointName, string messageType, string exceptionSummary, string message);
1383+
13191384
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} received unexpected {MessageType} message type.")]
13201385
private partial void LogEndpointHandlerUnexpectedMessageType(string endpointName, string messageType);
13211386

0 commit comments

Comments
 (0)