feat(mcp): log tool call (HTTP headers) (#221)

Signed-off-by: Marc Nuri <marc@marcnuri.com>
This commit is contained in:
Marc Nuri
2025-07-30 15:25:07 +02:00
committed by GitHub
parent 94f7055c0c
commit 49dcff3f21
3 changed files with 21 additions and 2 deletions

View File

@@ -6,8 +6,6 @@ import (
"encoding/json"
"flag"
"fmt"
"k8s.io/klog/v2"
"k8s.io/klog/v2/textlogger"
"net/http/httptest"
"os"
"path/filepath"
@@ -36,6 +34,8 @@ import (
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
toolswatch "k8s.io/client-go/tools/watch"
"k8s.io/klog/v2"
"k8s.io/klog/v2/textlogger"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/envtest"
"sigs.k8s.io/controller-runtime/tools/setup-envtest/env"

View File

@@ -1,6 +1,7 @@
package mcp
import (
"bytes"
"context"
"fmt"
"k8s.io/klog/v2"
@@ -171,6 +172,12 @@ func contextFunc(ctx context.Context, r *http.Request) context.Context {
func toolCallLoggingMiddleware(next server.ToolHandlerFunc) server.ToolHandlerFunc {
return func(ctx context.Context, ctr mcp.CallToolRequest) (*mcp.CallToolResult, error) {
klog.V(5).Infof("mcp tool call: %s(%v)", ctr.Params.Name, ctr.Params.Arguments)
if ctr.Header != nil {
buffer := bytes.NewBuffer(make([]byte, 0))
if err := ctr.Header.Write(buffer); err == nil {
klog.V(7).Infof("mcp tool call headers: %s", buffer)
}
}
return next(ctx, ctr)
}
}

View File

@@ -140,4 +140,16 @@ func TestToolCallLogging(t *testing.T) {
}
})
})
testCaseWithContext(t, &mcpContext{logLevel: 7}, func(c *mcpContext) {
_, _ = c.callTool("configuration_view", map[string]interface{}{
"minified": false,
})
t.Run("Logs tool call headers", func(t *testing.T) {
expectedLog := "mcp tool call headers: Accept-Encoding: gzip"
if !strings.Contains(c.logBuffer.String(), expectedLog) {
t.Errorf("Expected log to contain '%s', got: %s", expectedLog, c.logBuffer.String())
}
})
})
}