You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
feat: add message middleware support for ClientSession and ServerSession
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
0 commit comments