1
1
import logging
2
+ from typing import Any
2
3
3
4
import click
4
5
import mcp .types as mt
@@ -29,30 +30,39 @@ async def on_call_tool(
29
30
context : MiddlewareContext [mt .CallToolRequestParams ],
30
31
call_next : CallNext [mt .CallToolRequestParams , mt .CallToolResult ],
31
32
) -> mt .CallToolResult :
33
+ telemetry_data : dict [str , Any ] = {}
32
34
with PerfTimer () as timer :
33
- result = await call_next (context )
34
-
35
- try :
36
- telemetry .telemetry_instance .ping (
37
- "mcp-server-tool-call" ,
38
- {
39
- "tool" : context .message .name ,
40
- "source" : context .source ,
41
- "type" : context .type ,
42
- "method" : context .method ,
43
- "duration_seconds" : timer .elapsed_seconds (),
44
- "tool_result_is_error" : result .isError ,
45
- "tool_result_length" : sum (
35
+ telemetry_data = {
36
+ "tool" : context .message .name ,
37
+ "source" : context .source ,
38
+ "type" : context .type ,
39
+ "method" : context .method ,
40
+ }
41
+ try :
42
+ result = await call_next (context )
43
+
44
+ # BUG: The FastMCP type annotations seem to be incorrect.
45
+ # This method typically returns fastmcp.tools.tool.ToolResult.
46
+ if isinstance (result , mt .CallToolResult ):
47
+ telemetry_data ["tool_result_is_error" ] = result .isError
48
+ telemetry_data ["tool_result_length" ] = (
49
+ sum (
46
50
len (block .text )
47
51
for block in result .content
48
52
if isinstance (block , mt .TextContent )
49
53
),
50
- },
51
- )
52
- except Exception :
53
- logger .info ("Error generating telemetry" , exc_info = True )
54
+ )
55
+
56
+ return result
54
57
55
- return result
58
+ except Exception as e :
59
+ telemetry_data ["tool_call_error" ] = e .__class__ .__name__
60
+ raise
61
+ finally :
62
+ telemetry_data ["duration_seconds" ] = timer .elapsed_seconds ()
63
+ telemetry .telemetry_instance .ping (
64
+ "mcp-server-tool-call" , telemetry_data
65
+ )
56
66
57
67
58
68
@click .command ()
@@ -77,6 +87,7 @@ def main(transport: Literal["stdio", "sse", "http"], debug: bool) -> None:
77
87
)
78
88
79
89
if debug :
90
+ # logging.getLogger("datahub").setLevel(logging.DEBUG)
80
91
mcp .add_middleware (LoggingMiddleware (include_payloads = True ))
81
92
mcp .add_middleware (TelemetryMiddleware ())
82
93
0 commit comments