-
Notifications
You must be signed in to change notification settings - Fork 496
Add articles on logging and progress #717
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
--- | ||
title: Logging | ||
author: mikekistler | ||
description: How to use the logging feature in the MCP C# SDK. | ||
uid: logging | ||
--- | ||
|
||
MCP servers may expose log messages to clients through the [Logging utility]. | ||
|
||
[Logging utility]: https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/logging | ||
|
||
This document describes how to implement logging in MCP servers and how clients can consume log messages. | ||
|
||
### Logging Levels | ||
|
||
MCP uses the logging levels defined in [RFC 5424](https://tools.ietf.org/html/rfc5424). | ||
|
||
The MCP C# SDK uses the standard .NET [ILogger] and [ILoggerProvider] abstractions, which support a slightly | ||
different set of logging levels. Here's the levels and how they map to standard .NET logging levels. | ||
|
||
| Level | .NET | Description | Example Use Case | | ||
|-----------|------|-----------------------------------|------------------------------| | ||
| debug | ✓ | Detailed debugging information | Function entry/exit points | | ||
| info | ✓ | General informational messages | Operation progress updates | | ||
| notice | | Normal but significant events | Configuration changes | | ||
| warning | ✓ | Warning conditions | Deprecated feature usage | | ||
| error | ✓ | Error conditions | Operation failures | | ||
| critical | ✓ | Critical conditions | System component failures | | ||
| alert | | Action must be taken immediately | Data corruption detected | | ||
| emergency | | System is unusable | | | ||
|
||
**Note:** .NET's [ILogger] also supports a `Trace` level (more verbose than Debug) log level. | ||
As there is no equivalent level in the MCP logging levels, Trace level logs messages are silently | ||
dropped when sending messages to the client. | ||
|
||
[ILogger]: https://learn.microsoft.com/dotnet/api/microsoft.extensions.logging.ilogger | ||
[ILoggerProvider]: https://learn.microsoft.com/dotnet/api/microsoft.extensions.logging.iloggerprovider | ||
|
||
### Server configuration and logging | ||
|
||
MCP servers that implement the Logging utility must declare this in the capabilities sent in the | ||
[Initialization] phase at the beginning of the MCP session. | ||
|
||
[Initialization]: https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle#initialization | ||
|
||
Servers built with the C# SDK always declare the logging capability. The C# SDK provides an extension method | ||
[WithSetLoggingLevelHandler] on [IMcpServerBuilder] to allow the server to perform any special logic it wants to perform | ||
when a client sets the logging level. However, the SDK already takes care of setting the [LoggingLevel] | ||
in the [IMcpServer], so most servers will not need to implement this. | ||
|
||
[IMcpServer]: https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.Server.IMcpServer.html | ||
[IMcpServerBuilder]: https://modelcontextprotocol.github.io/csharp-sdk/api/Microsoft.Extensions.DependencyInjection.IMcpServerBuilder.html | ||
[WithSetLoggingLevelHandler]: https://modelcontextprotocol.github.io/csharp-sdk/api/Microsoft.Extensions.DependencyInjection.McpServerBuilderExtensions.html#Microsoft_Extensions_DependencyInjection_McpServerBuilderExtensions_WithSetLoggingLevelHandler_Microsoft_Extensions_DependencyInjection_IMcpServerBuilder_System_Func_ModelContextProtocol_Server_RequestContext_ModelContextProtocol_Protocol_SetLevelRequestParams__System_Threading_CancellationToken_System_Threading_Tasks_ValueTask_ModelContextProtocol_Protocol_EmptyResult___ | ||
[LoggingLevel]: https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.Server.IMcpServer.html#ModelContextProtocol_Server_IMcpServer_LoggingLevel | ||
|
||
MCP Servers using the MCP C# SDK can obtain an [ILoggerProvider] from the IMcpServer [AsClientLoggerProvider] extension method, | ||
and from that can create an [ILogger] instance for logging messages that should be sent to the MCP client. | ||
|
||
[!code-csharp[](samples/server/Tools/LoggingTools.cs?name=snippet_LoggingConfiguration)] | ||
mikekistler marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
[ILoggerProvider]: https://learn.microsoft.com/dotnet/api/microsoft.extensions.logging.iloggerprovider | ||
[AsClientLoggerProvider]: https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.Server.McpServerExtensions.html#ModelContextProtocol_Server_McpServerExtensions_AsClientLoggerProvider_ModelContextProtocol_Server_IMcpServer_ | ||
[ILogger]: https://learn.microsoft.com/dotnet/api/microsoft.extensions.logging.ilogger | ||
|
||
### Client support for logging | ||
|
||
Clients that wish to receive log messages from the server must first check if logging is supported. | ||
This is done by checking the [Logging] property of the [ServerCapabilities] field of [IMcpClient]. | ||
|
||
[IMcpClient]: https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.Client.IMcpClient.html | ||
[ServerCapabilities]: https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.Client.IMcpClient.html#ModelContextProtocol_Client_IMcpClient_ServerCapabilities | ||
[Logging]: https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.Protocol.ServerCapabilities.html#ModelContextProtocol_Protocol_ServerCapabilities_Logging | ||
|
||
[!code-csharp[](samples/client/Program.cs?name=snippet_LoggingCapabilities)] | ||
|
||
If the server supports logging, the client can set the level of log messages it wishes to receive with | ||
mikekistler marked this conversation as resolved.
Show resolved
Hide resolved
|
||
the [SetLoggingLevel] method on [IMcpClient]. The `loggingLevel` specified here is an MCP logging level. | ||
See the [Logging Levels](#logging-levels) section above for the mapping between MCP and .NET logging levels. | ||
|
||
[SetLoggingLevel]: https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.Client.McpClientExtensions.html#ModelContextProtocol_Client_McpClientExtensions_SetLoggingLevel_ModelContextProtocol_Client_IMcpClient_Microsoft_Extensions_Logging_LogLevel_System_Threading_CancellationToken_ | ||
|
||
[!code-csharp[](samples/client/Program.cs?name=snippet_LoggingLevel)] | ||
|
||
Lastly, the client must configure a notification handler for [NotificationMethods.LoggingMessageNotification] notifications. | ||
|
||
[NotificationMethods.LoggingMessageNotification]: https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.Protocol.NotificationMethods.html#ModelContextProtocol_Protocol_NotificationMethods_LoggingMessageNotification | ||
|
||
[!code-csharp[](samples/client/Program.cs?name=snippet_LoggingHandler)] | ||
mikekistler marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="ModelContextProtocol.Core" Version="0.3.0-preview.3" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
using ModelContextProtocol.Protocol; | ||
using ModelContextProtocol.Client; | ||
using System.Text.Json; | ||
|
||
var endpoint = Environment.GetEnvironmentVariable("ENDPOINT") ?? "http://localhost:3001"; | ||
|
||
var clientTransport = new SseClientTransport(new() | ||
{ | ||
Endpoint = new Uri(endpoint), | ||
TransportMode = HttpTransportMode.StreamableHttp, | ||
}); | ||
|
||
await using var mcpClient = await McpClientFactory.CreateAsync(clientTransport); | ||
|
||
// <snippet_LoggingCapabilities> | ||
// Verify that the server supports logging | ||
if (mcpClient.ServerCapabilities.Logging is null) | ||
{ | ||
Console.WriteLine("Server does not support logging."); | ||
return; | ||
} | ||
// </snippet_LoggingCapabilities> | ||
|
||
// Get the first argument if it was specified | ||
var firstArgument = args.Length > 0 ? args[0] : null; | ||
|
||
if (firstArgument is not null) | ||
{ | ||
// Set the logging level to the value from the first argument | ||
if (Enum.TryParse<LoggingLevel>(firstArgument, true, out var loggingLevel)) | ||
{ | ||
// <snippet_LoggingLevel> | ||
await mcpClient.SetLoggingLevel(loggingLevel); | ||
// </snippet_LoggingLevel> | ||
} | ||
else | ||
{ | ||
Console.WriteLine($"Invalid logging level: {firstArgument}"); | ||
// Print a list of valid logging levels | ||
Console.WriteLine("Valid logging levels are:"); | ||
foreach (var level in Enum.GetValues<LoggingLevel>()) | ||
{ | ||
Console.WriteLine($" - {level}"); | ||
} | ||
} | ||
} | ||
|
||
// </snippet_LoggingHandler> | ||
mcpClient.RegisterNotificationHandler(NotificationMethods.LoggingMessageNotification, | ||
(notification, ct) => | ||
{ | ||
if (JsonSerializer.Deserialize<LoggingMessageNotificationParams>(notification.Params) is { } ln) | ||
{ | ||
Console.WriteLine($"[{ln.Level}] {ln.Logger} {ln.Data}"); | ||
} | ||
else | ||
{ | ||
Console.WriteLine($"Received unexpected logging notification: {notification.Params}"); | ||
} | ||
|
||
return default; | ||
}); | ||
// </snippet_LoggingHandler> | ||
|
||
// Now call the "logging_tool" tool | ||
await mcpClient.CallToolAsync("logging_tool"); | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<Nullable>enable</Nullable> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="ModelContextProtocol.AspNetCore" Version="0.3.0-preview.3" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
@HostAddress = http://localhost:3001 | ||
|
||
POST {{HostAddress}}/ | ||
Accept: application/json, text/event-stream | ||
Content-Type: application/json | ||
|
||
{ | ||
"jsonrpc": "2.0", | ||
"id": 1, | ||
"method": "initialize", | ||
"params": { | ||
"clientInfo": { | ||
"name": "RestClient", | ||
"version": "0.1.0" | ||
}, | ||
"capabilities": {}, | ||
"protocolVersion": "2025-06-18" | ||
} | ||
} | ||
|
||
### | ||
|
||
@SessionId = JCo3W4Q7KA_evyWoFE5qwA | ||
|
||
### | ||
|
||
POST {{HostAddress}}/ | ||
Accept: application/json, text/event-stream | ||
Content-Type: application/json | ||
MCP-Protocol-Version: 2025-06-18 | ||
Mcp-Session-Id: {{SessionId}} | ||
|
||
{ | ||
"jsonrpc": "2.0", | ||
"id": 2, | ||
"method": "tools/call", | ||
"params": { | ||
"name": "logging_tool" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
using Logging.Tools; | ||
|
||
var builder = WebApplication.CreateBuilder(args); | ||
|
||
// Add services to the container. | ||
|
||
builder.Services.AddMcpServer() | ||
.WithHttpTransport(options => | ||
options.IdleTimeout = Timeout.InfiniteTimeSpan // Never timeout | ||
) | ||
.WithTools<LoggingTools>(); | ||
// .WithSetLoggingLevelHandler(async (ctx, ct) => new EmptyResult()); | ||
|
||
var app = builder.Build(); | ||
|
||
app.UseHttpsRedirection(); | ||
|
||
app.MapMcp(); | ||
|
||
app.Run(); |
23 changes: 23 additions & 0 deletions
23
docs/concepts/logging/samples/server/Properties/launchSettings.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
{ | ||
"$schema": "https://json.schemastore.org/launchsettings.json", | ||
"profiles": { | ||
"http": { | ||
"commandName": "Project", | ||
"dotnetRunMessages": true, | ||
"launchBrowser": false, | ||
"applicationUrl": "http://localhost:3001", | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
}, | ||
"https": { | ||
"commandName": "Project", | ||
"dotnetRunMessages": true, | ||
"launchBrowser": false, | ||
"applicationUrl": "https://localhost:7207;http://localhost:3001", | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
} | ||
} | ||
} |
45 changes: 45 additions & 0 deletions
45
docs/concepts/logging/samples/server/Tools/LoggingTools.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
using System.ComponentModel; | ||
using ModelContextProtocol.Protocol; | ||
using ModelContextProtocol.Server; | ||
|
||
namespace Logging.Tools; | ||
|
||
[McpServerToolType] | ||
public class LoggingTools | ||
{ | ||
[McpServerTool, Description("Demonstrates a tool that produces log messages")] | ||
public static async Task<string> LoggingTool( | ||
RequestContext<CallToolRequestParams> context, | ||
int duration = 10, | ||
int steps = 10) | ||
{ | ||
var progressToken = context.Params?.ProgressToken; | ||
var stepDuration = duration / steps; | ||
|
||
// <sinppet_LoggingConfiguration > | ||
ILoggerProvider loggerProvider = context.Server.AsClientLoggerProvider(); | ||
ILogger logger = loggerProvider.CreateLogger("LoggingTools"); | ||
// </snippet_LoggingConfiguration> | ||
|
||
for (int i = 1; i <= steps; i++) | ||
{ | ||
await Task.Delay(stepDuration * 1000); | ||
|
||
try | ||
{ | ||
logger.LogCritical("A critial log message"); | ||
logger.LogError("An error log message"); | ||
logger.LogWarning("A warning log message"); | ||
logger.LogInformation("An informational log message"); | ||
logger.LogDebug("A debug log message"); | ||
logger.LogTrace("A trace log message"); | ||
} | ||
catch (Exception ex) | ||
{ | ||
logger.LogError(ex, "An error occurred while logging messages"); | ||
} | ||
} | ||
|
||
return $"Long running tool completed. Duration: {duration} seconds. Steps: {steps}."; | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
docs/concepts/logging/samples/server/appsettings.Development.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Information", | ||
"Microsoft.AspNetCore": "Warning" | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Information", | ||
"Microsoft.AspNetCore": "Warning" | ||
} | ||
}, | ||
"AllowedHosts": "*" | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.