Logging Capability (#53)

* Logging Capability

* Readability

* Redundant using

---------

Co-authored-by: Stephen Toub <stoub@microsoft.com>
This commit is contained in:
Peder Holdgaard Pedersen 2025-03-21 22:50:41 +01:00 • committed by GitHub
commit 10c712a12f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 253 additions and 0 deletions

View file

@ -51,6 +51,7 @@ internal sealed class McpServer : McpJsonRpcEndpoint, IMcpServer
SetToolsHandler(options);
SetPromptsHandler(options);
SetResourcesHandler(options);
SetSetLoggingLevelHandler(options);
}
public ClientCapabilities? ClientCapabilities { get; set; }
@ -210,4 +211,19 @@ internal sealed class McpServer : McpJsonRpcEndpoint, IMcpServer
SetRequestHandler<ListToolsRequestParams, ListToolsResult>("tools/list", (request, ct) => listToolsHandler(new(this, request), ct));
SetRequestHandler<CallToolRequestParams, CallToolResponse>("tools/call", (request, ct) => callToolHandler(new(this, request), ct));
}
private void SetSetLoggingLevelHandler(McpServerOptions options)
{
if (options.Capabilities?.Logging is not { } loggingCapability)
{
return;
}
if (loggingCapability.SetLoggingLevelHandler is not { } setLoggingLevelHandler)
{
throw new McpServerException("Logging capability was enabled, but SetLoggingLevelHandler was not specified.");
}
SetRequestHandler<SetLevelRequestParams, EmptyResult>("logging/setLevel", (request, ct) => setLoggingLevelHandler(new(this, request), ct));
}
}

View file

@ -57,6 +57,11 @@ public sealed class McpServerHandlers
/// </summary>
public Func<RequestContext<UnsubscribeRequestParams>, CancellationToken, Task<EmptyResult>>? UnsubscribeFromResourcesHandler { get; set; }
/// <summary>
/// Get or sets the handler for set logging level requests.
/// </summary>
public Func<RequestContext<SetLevelRequestParams>, CancellationToken, Task<EmptyResult>>? SetLoggingLevelHandler { get; set; }
/// <summary>
/// Overwrite any handlers in McpServerOptions with non-null handlers from this instance.
/// </summary>
@ -125,6 +130,20 @@ public sealed class McpServerHandlers
};
}
LoggingCapability? loggingCapability = options.Capabilities?.Logging;
if (SetLoggingLevelHandler is not null)
{
loggingCapability = loggingCapability is null ?
new()
{
SetLoggingLevelHandler = SetLoggingLevelHandler,
} :
loggingCapability with
{
SetLoggingLevelHandler = SetLoggingLevelHandler ?? loggingCapability.SetLoggingLevelHandler,
};
}
options.Capabilities = options.Capabilities is null ?
new()
{