-
Notifications
You must be signed in to change notification settings - Fork 587
Add request duration to LogRequestHandlerCompleted and LogRequestHandlerException log messages #1092
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
Open
Copilot
wants to merge
7
commits into
main
Choose a base branch
from
copilot/improve-log-request-duration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+17
−10
Open
Add request duration to LogRequestHandlerCompleted and LogRequestHandlerException log messages #1092
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
092f328
Initial plan
Copilot 08315a9
Add duration logging to LogRequestHandlerCompleted
Copilot b9c408e
Address code review feedback: use static regex and culture-invariant …
Copilot 54dad60
Apply code review feedback: inline duration calculation and remove lo…
Copilot 75bfca5
Add duration logging to LogRequestHandlerException and consolidate ti…
Copilot 7b01775
Colocate LogRequestHandlerCalled with completion/failure logs in Hand…
Copilot 46becf2
Merge branch 'main' into copilot/improve-log-request-duration
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
121 changes: 121 additions & 0 deletions
121
tests/ModelContextProtocol.Tests/Server/McpServerRequestDurationLoggingTests.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,121 @@ | ||
| using Microsoft.Extensions.DependencyInjection; | ||
stephentoub marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| using Microsoft.Extensions.Logging; | ||
| using ModelContextProtocol.Client; | ||
| using ModelContextProtocol.Protocol; | ||
| using ModelContextProtocol.Server; | ||
| using System.ComponentModel; | ||
| using System.Globalization; | ||
| using System.Text.RegularExpressions; | ||
|
|
||
| namespace ModelContextProtocol.Tests.Server; | ||
|
|
||
| public class McpServerRequestDurationLoggingTests : ClientServerTestBase | ||
| { | ||
| private static readonly Regex DurationRegex = new(@"completed in (\d+(?:\.\d+)?)ms", RegexOptions.Compiled); | ||
|
|
||
| public McpServerRequestDurationLoggingTests(ITestOutputHelper testOutputHelper) | ||
| : base(testOutputHelper) | ||
| { | ||
| } | ||
|
|
||
| protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder) | ||
| { | ||
| mcpServerBuilder.WithTools<TestTools>(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task RequestHandlerCompleted_LogsElapsedTime() | ||
| { | ||
| // Arrange | ||
| await using McpClient client = await CreateMcpClientForServer(); | ||
|
|
||
| // Act | ||
| var result = await client.CallToolAsync( | ||
| "delayed_tool", | ||
| new Dictionary<string, object?> { ["delayMs"] = 50 }, | ||
| cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| // Assert | ||
| Assert.NotNull(result); | ||
|
|
||
| // Verify the log message contains duration in milliseconds | ||
| Assert.Contains(MockLoggerProvider.LogMessages, log => | ||
| { | ||
| if (log.LogLevel != LogLevel.Information || | ||
| !log.Message.Contains("request handler completed") || | ||
| !log.Message.Contains("ms")) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| // Extract duration from log message (should be in format "...completed in XXXms.") | ||
| var match = DurationRegex.Match(log.Message); | ||
| if (!match.Success) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| double elapsedMs = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); | ||
|
|
||
| // Duration should be at least 50ms (the delay we introduced) | ||
| // and less than 5 seconds | ||
| return elapsedMs >= 50 && elapsedMs < 5000; | ||
| }); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task RequestHandlerCompleted_LogsForQuickRequests() | ||
| { | ||
| // Arrange | ||
| await using McpClient client = await CreateMcpClientForServer(); | ||
|
|
||
| // Act | ||
| var result = await client.CallToolAsync("quick_tool", cancellationToken: TestContext.Current.CancellationToken); | ||
|
|
||
| // Assert | ||
| Assert.NotNull(result); | ||
|
|
||
| // Verify the log message contains duration in milliseconds | ||
| Assert.Contains(MockLoggerProvider.LogMessages, log => | ||
| { | ||
| if (log.LogLevel != LogLevel.Information || | ||
| !log.Message.Contains("request handler completed") || | ||
| !log.Message.Contains("ms")) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| // Extract duration from log message | ||
| var match = DurationRegex.Match(log.Message); | ||
| if (!match.Success) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| double elapsedMs = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); | ||
|
|
||
| // Even quick requests should log some duration (should be very small) | ||
| // Should complete quickly (less than 1 second) | ||
| return elapsedMs >= 0 && elapsedMs < 1000; | ||
| }); | ||
| } | ||
|
|
||
| [McpServerToolType] | ||
| private sealed class TestTools | ||
| { | ||
| [McpServerTool, Description("A tool that delays for a specified time")] | ||
| public static async Task<string> DelayedTool( | ||
| [Description("Delay in milliseconds")] int delayMs, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| await Task.Delay(delayMs, cancellationToken); | ||
| return $"Delayed for {delayMs}ms"; | ||
| } | ||
|
|
||
| [McpServerTool, Description("A tool that completes quickly")] | ||
| public static string QuickTool() | ||
| { | ||
| return "Quick result"; | ||
| } | ||
| } | ||
| } | ||
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.