Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<PackageVersion Include="Microsoft.Extensions.AI.Abstractions" Version="$(MicrosoftExtensionsVersion)" />
<PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="$(System10Version)" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="$(System10Version)" />
<PackageVersion Include="Microsoft.Extensions.Diagnostics.ExceptionSummarization" Version="10.8.0" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="$(System10Version)" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="$(System10Version)" />
</ItemGroup>
Expand Down
39 changes: 39 additions & 0 deletions docs/concepts/logging/logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,42 @@ Lastly, the client must configure a notification handler for <xref:ModelContextP
The following example simply writes the log messages to the console.

[!code-csharp[](samples/client/Program.cs?name=snippet_LoggingHandler)]

### Sanitizing exceptions in the server's own diagnostic logs

Separately from the MCP Logging utility described above, the server writes its own diagnostic logs to the
[ILogger] it was configured with. When a request handler, tool, prompt, or resource throws, those logs include the
raw <xref:System.Exception>, which most logging providers render as the exception message plus its stack trace.
That output can contain sensitive or overly detailed runtime data.

Set <xref:ModelContextProtocol.Server.McpServerOptions.ExceptionSummarizer> to log a sanitized description instead.
When it is set, the failure paths log only the string the delegate returns, and the raw exception is not attached to
the log entry. The default is `null`, which preserves the existing behavior of logging the raw exception.

```csharp
builder.Services.AddMcpServer(options =>
{
options.ExceptionSummarizer = ex => ex.GetType().Name;
});
```

The summarized and raw forms of each event share one `EventId`, so filters and alerts keyed on `EventId` behave the
same whether or not a summarizer is configured. The delegate runs only when the corresponding log level is enabled,
so it costs nothing on a level that is filtered out.

The `ModelContextProtocol` package also integrates with the standard
[Microsoft.Extensions.Diagnostics.ExceptionSummarization](https://learn.microsoft.com/dotnet/api/microsoft.extensions.diagnostics.exceptionsummarization)
abstractions. If an `IExceptionSummarizer` is registered in the container and `ExceptionSummarizer` has not been set
explicitly, the SDK populates it with `"{ExceptionType}: {Description}"` taken from the `ExceptionSummary`:

```csharp
builder.Services.AddExceptionSummarizer(b => b.AddHttpProvider());
builder.Services.AddMcpServer();
```

Both of those fields are documented as free of privacy-sensitive information. `ExceptionSummary.AdditionalDetails` is
not, and `ExceptionSummary.ToString()` appends it, so neither is used. The exception type is included because
`Description` on its own is `"Unknown"` for exception types that no registered provider handles.

If the delegate throws or returns `null`, the SDK falls back to logging the raw exception, so a faulty summarizer
can never fail the session.
35 changes: 35 additions & 0 deletions src/ModelContextProtocol.Core/ExceptionSummaryHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Diagnostics.CodeAnalysis;

namespace ModelContextProtocol;

/// <summary>
/// Provides the single, shared entry point used by exception-logging callsites to apply a
/// user-supplied exception summarizer.
/// </summary>
internal static class ExceptionSummaryHelper
{
/// <summary>
/// Attempts to produce a sanitized description of <paramref name="exception"/> using <paramref name="summarizer"/>.
/// Callers check that a summarizer is configured, and that the event's level is enabled, before calling this.
/// </summary>
/// <returns>
/// <see langword="true"/> if a summary was produced and the caller should log it in place of
/// <paramref name="exception"/>; otherwise, <see langword="false"/>, in which case the caller must log
/// <paramref name="exception"/> exactly as it would have without a summarizer. The summarizer is supplied
/// by the host, so throwing or returning <see langword="null"/> both fall back rather than disrupt the session.
/// </returns>
public static bool TrySummarize(Func<Exception, string> summarizer, Exception exception, [NotNullWhen(true)] out string? summary)
{
try
{
summary = summarizer(exception);
return summary is not null;
}
catch
{
// A faulty summarizer must never fail logging; fall back to the raw exception.
summary = null;
return false;
}
}
}
85 changes: 75 additions & 10 deletions src/ModelContextProtocol.Core/McpSessionHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ internal static bool SupportsNaturalOutputSchemas(string? protocolVersion)
/// </summary>
private readonly ConcurrentDictionary<RequestId, CancellationTokenSource> _handlingRequests = new();
private readonly ILogger _logger;
private readonly Func<Exception, string>? _exceptionSummarizer;

// This _sessionId is solely used to identify the session in telemetry and logs.
private readonly string _sessionId = Guid.NewGuid().ToString("N");
Expand All @@ -115,6 +116,10 @@ internal static bool SupportsNaturalOutputSchemas(string? protocolVersion)
/// <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>
/// <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>
/// <param name="logger">The logger.</param>
/// <param name="exceptionSummarizer">
/// An optional callback that produces a sanitized description of an exception. When non-<see langword="null"/>,
/// exception logging callsites log that description instead of the raw <see cref="Exception"/>.
/// </param>
public McpSessionHandler(
bool isServer,
ITransport transport,
Expand All @@ -123,7 +128,8 @@ public McpSessionHandler(
NotificationHandlers notificationHandlers,
JsonRpcMessageFilter? incomingMessageFilter,
JsonRpcMessageFilter? outgoingMessageFilter,
ILogger logger)
ILogger logger,
Func<Exception, string>? exceptionSummarizer = null)
{
Throw.IfNull(transport);

Expand All @@ -144,6 +150,7 @@ public McpSessionHandler(
_incomingMessageFilter = incomingMessageFilter ?? (next => next);
_outgoingMessageFilter = outgoingMessageFilter ?? (next => next);
_logger = logger;
_exceptionSummarizer = exceptionSummarizer;

// ping was removed in the 2026-07-28 protocol revision (SEP-2575). On the 2026-07-28 or later version,
// return MethodNotFound; on an older version, the per-spec behavior is to always answer
Expand Down Expand Up @@ -323,14 +330,7 @@ ex is OperationCanceledException &&
}
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);
}
LogMessageHandlerFailure(message, ex);
}
}
finally
Expand Down Expand Up @@ -470,7 +470,7 @@ await _incomingMessageFilter(async (msg, ct) =>
}
catch (Exception ex)
{
LogRequestHandlerException(EndpointName, request.Method, GetElapsed(requestStartingTimestamp).TotalMilliseconds, ex);
LogRequestHandlerFailure(EndpointName, request.Method, GetElapsed(requestStartingTimestamp).TotalMilliseconds, ex);
throw;
}

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

/// <summary>
/// Logs a failed request handler, substituting a sanitized description for the raw exception when a
/// summarizer is configured. The summarizer only runs when the event's level is enabled, matching the
/// enabled-check the generated logging methods perform internally.
/// </summary>
private void LogRequestHandlerFailure(string endpointName, string method, double elapsedMilliseconds, Exception exception)
{
if (_exceptionSummarizer is not null &&
_logger.IsEnabled(LogLevel.Warning) &&
ExceptionSummaryHelper.TrySummarize(_exceptionSummarizer, exception, out string? exceptionSummary))
{
LogRequestHandlerExceptionSummarized(endpointName, method, elapsedMilliseconds, exceptionSummary);
}
else
{
LogRequestHandlerException(endpointName, method, elapsedMilliseconds, exception);
}
}

/// <summary>
/// Logs a failed message handler. The trace-vs-warning selection is unchanged from the non-summarizing
/// path; only the payload differs. The summarizer runs only when the selected event's level is enabled.
/// </summary>
private void LogMessageHandlerFailure(JsonRpcMessage message, Exception exception)
{
string messageType = message.GetType().Name;

if (_logger.IsEnabled(LogLevel.Trace))
{
if (_exceptionSummarizer is not null &&
ExceptionSummaryHelper.TrySummarize(_exceptionSummarizer, exception, out string? exceptionSummary))
{
LogMessageHandlerExceptionSensitiveSummarized(EndpointName, messageType, exceptionSummary, JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage));
}
else
{
LogMessageHandlerExceptionSensitive(EndpointName, messageType, JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage), exception);
}
}
else if (_exceptionSummarizer is not null &&
_logger.IsEnabled(LogLevel.Warning) &&
ExceptionSummaryHelper.TrySummarize(_exceptionSummarizer, exception, out string? exceptionSummary))
{
LogMessageHandlerExceptionSummarized(EndpointName, messageType, exceptionSummary);
}
else
{
LogMessageHandlerException(EndpointName, messageType, exception);
}
}

// Each summarized variant names its raw counterpart as its EventName so the pair emits one EventId and
// one event name, keeping consumers that filter on EventId working when a summarizer is configured. The
// generator derives the numeric id from the event name, which defaults to the method name, so only the
// summarized variant declares EventName: declaring it on both trips SYSLIB1025.

[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.Warning, EventName = nameof(LogRequestHandlerException), Message = "{EndpointName} method '{Method}' request handler failed in {ElapsedMilliseconds}ms: {ExceptionSummary}.")]
private partial void LogRequestHandlerExceptionSummarized(string endpointName, string method, double elapsedMilliseconds, string exceptionSummary);

[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} received request for unknown request ID '{RequestId}'.")]
private partial void LogNoRequestFoundForMessageWithId(string endpointName, RequestId requestId);

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

[LoggerMessage(Level = LogLevel.Warning, EventName = nameof(LogMessageHandlerException), Message = "{EndpointName} message handler {MessageType} failed: {ExceptionSummary}.")]
private partial void LogMessageHandlerExceptionSummarized(string endpointName, string messageType, string exceptionSummary);

[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.Trace, EventName = nameof(LogMessageHandlerExceptionSensitive), Message = "{EndpointName} message handler {MessageType} failed: {ExceptionSummary}. Message: '{Message}'.")]
private partial void LogMessageHandlerExceptionSensitiveSummarized(string endpointName, string messageType, string exceptionSummary, string message);

[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} received unexpected {MessageType} message type.")]
private partial void LogEndpointHandlerUnexpectedMessageType(string endpointName, string messageType);

Expand Down
Loading
Loading