-
Notifications
You must be signed in to change notification settings - Fork 586
Capture tool call name in ILogger logs on success and not just failure #859
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
Closed
+127
−14
Closed
Changes from 7 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
359bbc9
Initial plan
Copilot 4197c8f
Add tool name to structured logging for tool calls
Copilot c7db00a
Clean up test and add helpful comments
Copilot 1dbda9c
Add test for tool error case with structured logging
Copilot 836730e
Merge main to resolve conflicts with McpProtocolException changes
Copilot b8e3d9f
Merge main to resolve conflicts with latest changes
Copilot c2f6132
Merge branch 'main' into copilot/capture-tool-call-name-logging
stephentoub 7b2faf0
Update src/ModelContextProtocol.Core/McpSessionHandler.cs
stephentoub b20d1f2
Merge branch 'main' into copilot/capture-tool-call-name-logging
stephentoub 57cca95
Merge branch 'main' into copilot/capture-tool-call-name-logging
stephentoub 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
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 |
|---|---|---|
|
|
@@ -20,13 +20,20 @@ namespace ModelContextProtocol.Tests.Configuration; | |
|
|
||
| public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase | ||
| { | ||
| private MockLoggerProvider _mockLoggerProvider = new(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This test could be updated to use the MockLoggerProvider in the base class if #1054 gets merged first. |
||
|
|
||
| public McpServerBuilderExtensionsToolsTests(ITestOutputHelper testOutputHelper) | ||
| : base(testOutputHelper) | ||
| { | ||
| // Configure LoggerFactory to use Debug level and add MockLoggerProvider | ||
| LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder => | ||
| { | ||
| builder.AddProvider(XunitLoggerProvider); | ||
| builder.AddProvider(_mockLoggerProvider); | ||
| builder.SetMinimumLevel(LogLevel.Debug); | ||
| }); | ||
| } | ||
|
|
||
| private MockLoggerProvider _mockLoggerProvider = new(); | ||
|
|
||
| protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder) | ||
| { | ||
| mcpServerBuilder | ||
|
|
@@ -733,6 +740,86 @@ await client.SendNotificationAsync( | |
| await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await invokeTask); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ToolName_Captured_In_Structured_Logging() | ||
| { | ||
| await using McpClient client = await CreateMcpClientForServer(); | ||
|
|
||
| // Call a tool that will succeed | ||
| var result = await client.CallToolAsync( | ||
| "echo", | ||
| new Dictionary<string, object?> { ["message"] = "test" }, | ||
| cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| Assert.NotNull(result); | ||
|
|
||
| // Verify that the tool name is captured in structured logging | ||
| // The LogMessagesWithState should contain log entries with tool name in the state | ||
| var relevantLogs = _mockLoggerProvider.LogMessagesWithState | ||
| .Where(m => m.Category == "ModelContextProtocol.Client.McpClient" && | ||
| m.Message.Contains("tools/call")) | ||
| .ToList(); | ||
|
|
||
| Assert.NotEmpty(relevantLogs); | ||
|
|
||
| // Check that at least one log entry has the tool name in its structured state | ||
| // This demonstrates how users can extract the tool name from TState in a custom ILoggerProvider | ||
| // The State object is IReadOnlyList<KeyValuePair<string, object?>> which contains | ||
| // structured logging parameters like "ToolName", "Method", "EndpointName", etc. | ||
| bool foundToolName = relevantLogs.Any(log => | ||
| { | ||
| if (log.State is IReadOnlyList<KeyValuePair<string, object?>> stateList) | ||
| { | ||
| return stateList.Any(kvp => | ||
| kvp.Key == "ToolName" && | ||
| kvp.Value?.ToString() == "echo"); | ||
| } | ||
| return false; | ||
| }); | ||
|
|
||
| Assert.True(foundToolName, "Tool name 'echo' was not found in structured logging state"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ToolName_Captured_In_Structured_Logging_OnToolError() | ||
| { | ||
| await using McpClient client = await CreateMcpClientForServer(); | ||
|
|
||
| // Call a tool that will error - note that tool errors are returned as CallToolResult with IsError=true, | ||
| // not thrown as exceptions per the MCP spec | ||
| var result = await client.CallToolAsync( | ||
| "throw_exception", | ||
| cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| // Verify the tool error was returned properly | ||
| Assert.NotNull(result); | ||
| Assert.True(result.IsError); | ||
|
|
||
| // Verify that the tool name is captured in structured logging | ||
| // even when the tool encounters an error | ||
| var relevantLogs = _mockLoggerProvider.LogMessagesWithState | ||
| .Where(m => m.LogLevel == LogLevel.Debug && | ||
| (m.Message.Contains("waiting for response") || m.Message.Contains("response received")) && | ||
| m.Message.Contains("tools/call")) | ||
| .ToList(); | ||
|
|
||
| Assert.NotEmpty(relevantLogs); | ||
|
|
||
| // Check that at least one log entry has the tool name in its structured state | ||
| bool foundToolName = relevantLogs.Any(log => | ||
| { | ||
| if (log.State is IReadOnlyList<KeyValuePair<string, object?>> stateList) | ||
| { | ||
| return stateList.Any(kvp => | ||
| kvp.Key == "ToolName" && | ||
| kvp.Value?.ToString() == "throw_exception"); | ||
| } | ||
| return false; | ||
| }); | ||
|
|
||
| Assert.True(foundToolName, "Tool name 'throw_exception' was not found in structured logging state"); | ||
| } | ||
|
|
||
| [McpServerToolType] | ||
| public sealed class EchoTool(ObjectWithId objectFromDI) | ||
| { | ||
|
|
||
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.