Skip to content

Commit b891d95

Browse files
authored
mcp: example middleware wrapping ToolHandler (#351)
Add to the middleware example to show how to wrap a ToolHandler. This middleware is very close to, but not the same as, wrapping a ToolHandler directly. The only difference is that the middleware wraps Server.callTool, which looks up the tool by name in the server's list and then calls the handler. That lookup (plus other intervening middleware, of course) is all that distinguishes this way of wrapping from a more direct wrapping.
1 parent 18c96d6 commit b891d95

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

mcp/example_middleware_test.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,16 @@ func Example_loggingMiddleware() {
4040
"session_id", req.GetSession().ID(),
4141
"has_params", req.GetParams() != nil,
4242
)
43+
// Log more for tool calls.
44+
if ctr, ok := req.(*mcp.CallToolRequest); ok {
45+
logger.Info("Calling tool",
46+
"name", ctr.Params.Name,
47+
"args", ctr.Params.Arguments)
48+
}
4349

4450
start := time.Now()
45-
4651
result, err := next(ctx, method, req)
47-
4852
duration := time.Since(start)
49-
5053
if err != nil {
5154
logger.Error("MCP method failed",
5255
"method", method,
@@ -62,7 +65,6 @@ func Example_loggingMiddleware() {
6265
"has_result", result != nil,
6366
)
6467
}
65-
6668
return result, err
6769
}
6870
}
@@ -134,6 +136,7 @@ func Example_loggingMiddleware() {
134136
// time=2025-01-01T00:00:00Z level=INFO msg="MCP method started" method=notifications/initialized session_id="" has_params=true
135137
// time=2025-01-01T00:00:00Z level=INFO msg="MCP method completed" method=notifications/initialized session_id="" duration_ms=0 has_result=false
136138
// time=2025-01-01T00:00:00Z level=INFO msg="MCP method started" method=tools/call session_id="" has_params=true
139+
// time=2025-01-01T00:00:00Z level=INFO msg="Calling tool" name=greet args="{\"name\":\"World\"}"
137140
// time=2025-01-01T00:00:00Z level=INFO msg="MCP method completed" method=tools/call session_id="" duration_ms=0 has_result=true
138141
// Tool result: Hello, World!
139142
}

0 commit comments

Comments
 (0)