Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

renvins
Copy link
Contributor

@renvins renvins commented Sep 19, 2025

Pull Request Description

Changes

This PR introduces a new middleware system for mcp-use. This system provides a flexible way to intercept and process MCP requests and responses, enabling features like logging, metrics, performance monitoring, and custom request/response handling.

A default logging middleware has been added and is enabled by default to provide basic request/response visibility. Additionally, a comprehensive set of metrics and analytics middleware is included for advanced monitoring.

Implementation Details

  1. Core Middleware Architecture (mcp_use/middleware/middleware.py):

    • A new Middleware base class allows for creating custom middleware with strongly-typed hooks for different MCP methods (e.g., on_call_tool, on_initialize).
    • MiddlewareContext provides a unified, typed context for all middleware operations.
    • MiddlewareManager orchestrates the execution of the middleware chain.
    • CallbackClientSession acts as an adapter to integrate the middleware system with the existing ClientSession without requiring changes to upstream callers.
  2. Built-in Middleware:

    • LoggingMiddleware (mcp_use/middleware/logging.py): Provides default debug-level logging for all MCP requests and responses.
    • MetricsMiddleware, PerformanceMetricsMiddleware, ErrorTrackingMiddleware, and CombinedAnalyticsMiddleware (mcp_use/middleware/metrics.py): A suite of middleware for collecting detailed metrics, performance data, and error analytics.
  3. Integration:

    • MCPClient has been updated to accept a middleware argument in its constructor.
    • The default_logging_middleware is automatically included.
    • The middleware is passed down to the connectors and applied via the CallbackClientSession.

Example Usage

# After, you can pass custom middleware to the client.
# A default logging middleware is always active.
from mcp_use import MCPClient
from mcp_use.middleware import Middleware, MiddlewareContext, NextFunctionT
from mcp.types import CallToolRequestParams, CallToolResult

# Define a custom middleware
class CustomToolLogger(Middleware):
    async def on_call_tool(
        self, context: MiddlewareContext[CallToolRequestParams], call_next: NextFunctionT
    ) -> CallToolResult:
        params: CallToolRequestParams = context.params
        print(f"Intercepted tool call: {params.name} with args {params.arguments}")
        return await call_next(context)

# Initialize client with custom middleware
client = MCPClient(config=config, middleware=[CustomToolLogger()])

# ... now when a tool is called, the custom middleware will print the message.

The new examples/example_middleware.py provides a runnable example of this.

Backwards Compatibility

These changes are fully backwards compatible. The middleware argument in MCPClient is optional. Existing code that does not use middleware will continue to work as before, with the only change being the addition of default debug logging for MCP requests.

pietrozullo and others added 2 commits September 8, 2025 17:46
- Add context to middleware with mcp types
- Update logging middleware with new implementation
- Add hooks for every type of action
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants