Skip to content

Conversation

@jerome3o-anthropic
Copy link
Member

Summary

Add a middleware pattern that allows transforming JSON-RPC messages before sending and after receiving. This provides a clean way to extend protocol messages (e.g., adding custom capabilities to initialize requests) without needing to subclass or override session methods.

Motivation

When clients need to add custom fields to MCP messages (like protocol extensions or custom capabilities), they currently have to override the initialize() method and duplicate its internal logic. This is error-prone and creates maintenance burden.

A middleware approach provides a clean escape hatch that:

  • Doesn't require subclassing
  • Works with any message type (requests, responses, notifications)
  • Supports both sync and async transformations
  • Can be composed (multiple middleware functions)

Example Usage

from mcp import ClientSession, JSONRPCMessage, JSONRPCRequest

def add_ui_extension(message: JSONRPCMessage) -> JSONRPCMessage:
    """Add UI extension capabilities to initialize request."""
    if isinstance(message.root, JSONRPCRequest):
        data = message.root.model_dump(by_alias=True, mode="json", exclude_none=True)
        if data.get("method") == "initialize":
            caps = data.setdefault("params", {}).setdefault("capabilities", {})
            caps["extensions"] = {
                "io.modelcontextprotocol/ui": {"mimeTypes": ["text/html"]}
            }
            return JSONRPCMessage(JSONRPCRequest(**data))
    return message

session = ClientSession(
    read_stream,
    write_stream,
    send_middleware=[add_ui_extension],
)

Implementation

  • Added MessageMiddleware type alias: Callable[[JSONRPCMessage], JSONRPCMessage | Awaitable[JSONRPCMessage]]
  • Added send_middleware and receive_middleware parameters to BaseSession, ClientSession, and ServerSession
  • Middleware is applied in send_request(), send_notification(), _send_response() for outgoing messages
  • Middleware is applied in _receive_loop() for incoming messages
  • Both sync and async middleware functions are supported

Testing

Added tests verifying:

  • Sync middleware can transform outgoing messages
  • Async middleware works correctly

Add a middleware pattern that allows transforming JSON-RPC messages before
sending and after receiving. This provides a clean way to extend protocol
messages (e.g., adding custom capabilities to initialize requests) without
needing to subclass or override session methods.

Middleware functions receive a JSONRPCMessage and return a (possibly
transformed) JSONRPCMessage. Both sync and async middleware are supported.

Usage example:
    def add_capabilities(message: JSONRPCMessage) -> JSONRPCMessage:
        if isinstance(message.root, JSONRPCRequest):
            # Transform the message...
            pass
        return message

    session = ClientSession(
        read_stream, write_stream,
        send_middleware=[add_capabilities],
    )

Changes:
- Add MessageMiddleware type alias in mcp.shared.session
- Add send_middleware and receive_middleware parameters to BaseSession
- Apply middleware in send_request, send_notification, _send_response
- Apply middleware in _receive_loop after receiving messages
- Export MessageMiddleware, JSONRPCMessage, JSONRPCNotification from mcp
- Add tests for sync and async middleware
self, message: JSONRPCMessage, middleware_list: list[MessageMiddleware]
) -> JSONRPCMessage:
"""Apply a list of middleware functions to a message."""
import inspect
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move to top


for middleware in middleware_list:
result = middleware(message)
if inspect.isawaitable(result):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should inspect the function first instead of doing it on every single message

@jerome3o-anthropic
Copy link
Member Author

Addressed the review comments:

  1. Moved import inspect to top of file
  2. Now pre-computing whether each middleware is async using inspect.iscoroutinefunction() when middleware is registered, instead of checking isawaitable() on every message
  3. Added test for receive_middleware to fix coverage

Thanks for the feedback!

- Move 'import inspect' to top of file
- Pre-compute whether middleware is async using inspect.iscoroutinefunction()
  instead of checking on every message
- Add test for receive_middleware to fix coverage
@jerome3o-anthropic jerome3o-anthropic force-pushed the jerome/message-middleware branch from f932d9f to ac97195 Compare January 19, 2026 16:17
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.

3 participants