go-sdk/examples/http/logging_middleware.go
Spring_MT 35dfcf21c9
examples: Fix SSE streaming issue by moving logging from HTTP to MCP middlewarre (#614)
In `examples/http`, previous HTTP-level logging middleware blocked SSE
streaming because `handler.ServeHTTP()` does not return until the
connection closes for GET requests (SSE streams).
This prevented response headers from being sent to the client.

Changes:
- Replace HTTP-level logging handler with MCP middleware pattern
- Implement logging at the MCP protocol layer using mcp.Middleware
- Add middleware to server using AddReceivingMiddleware()
- Simplify main.go by removing HTTP handler wrapping

This allows SSE streams to work properly while still providing detailed
logging for all MCP protocol-level method calls.

Fixes #632
2025-11-11 11:56:52 -05:00

53 lines
1.2 KiB
Go

// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"log"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// createLoggingMiddleware creates an MCP middleware that logs method calls.
func createLoggingMiddleware() mcp.Middleware {
return func(next mcp.MethodHandler) mcp.MethodHandler {
return func(
ctx context.Context,
method string,
req mcp.Request,
) (mcp.Result, error) {
start := time.Now()
sessionID := req.GetSession().ID()
// Log request details.
log.Printf("[REQUEST] Session: %s | Method: %s",
sessionID,
method)
// Call the actual handler.
result, err := next(ctx, method, req)
// Log response details.
duration := time.Since(start)
if err != nil {
log.Printf("[RESPONSE] Session: %s | Method: %s | Status: ERROR | Duration: %v | Error: %v",
sessionID,
method,
duration,
err)
} else {
log.Printf("[RESPONSE] Session: %s | Method: %s | Status: OK | Duration: %v",
sessionID,
method,
duration)
}
return result, err
}
}
}