-
Notifications
You must be signed in to change notification settings - Fork 545
Description
I was asked the following question:
[Them]: is there a way to pass a callback function to the streamablehttp handler to get the tool response (content body and IsError boolean flag)?
...
And also is there an easier way to track latency of each tool call? I know AOP can do it, but would be happy if sdk side has an easier way to achieve that.
To which I replied:
[Me]: This is probably best currently achieved with a custom ILoggerProvider. We added a test verifying you can observe this here. You don't have to new up a LoggerFactory like the test does. You can just call builder.Logging.AddProvider(myCustomProvider), and retain all your other logger providers (e.g. console, ETW). And the tool name is a parameter to structured logging, so you can reliably retrieve that from the TState which is IReadOnlyList<KeyValuePair<string, object?>>.
csharp-sdk/tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs at c560f47ee6d439beb38619222af3f97b7aa529af · modelcontextprotocol/csharp-sdk
Logging providers - .NET | Microsoft LearnYou could also listen to the "mcp.server.operation.duration" otel metric. Like the similar otel metrics for HTTP request duration, it captures a lot more than just the "duration". As you can see here, we add a lot of relevant tags.
But it turns out we don't have an ILogger log whith the tool name in the message (or LoggerMessage.LogValues struct) for successful invocations the way we do for errors since #447.
[Them]: thanks a lot for the pointer, however I can't see the real mcp tool name in the "state" param, am I missing something?
I think the problem is the sdk doesn't add the tool name in logging. https://github.com/modelcontextprotocol/csharp-sdk/blob/c560f47ee6d439beb38619222af3f97b7aa529af/src/ModelContextProtocol.Core/McpSession.cs#L315C36-L315C48, but just the endpoint name and request method(e.g. 'tools/call')
[Me]: My bad. If you're willing to go the otel route and write an ActivityListener instead, that does include the mcp.tool.name as a tag for the mcp.server.operation.duration metric, so you could use that. I filed an issue to include this in an ILogger log as well. We should be able to ship an update with that to NuGet next week.