-
Notifications
You must be signed in to change notification settings - Fork 3.3k
feat: Add message middleware support for session message transformation #1911
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+275
−8
Closed
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
90e8720
feat: add message middleware support for ClientSession and ServerSession
jerome3o-anthropic ac97195
fix: address review feedback and add receive middleware test
jerome3o-anthropic 0f3edd4
fix: add pragma comments for test branch coverage
jerome3o-anthropic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| import logging | ||
| from collections.abc import Callable | ||
| from collections.abc import Awaitable, Callable | ||
| from contextlib import AsyncExitStack | ||
| from datetime import timedelta | ||
| from types import TracebackType | ||
|
|
@@ -43,6 +43,10 @@ | |
|
|
||
| RequestId = str | int | ||
|
|
||
| # Middleware type for transforming messages before sending or after receiving. | ||
| # Can be sync (returns JSONRPCMessage) or async (returns Awaitable[JSONRPCMessage]). | ||
| MessageMiddleware = Callable[[JSONRPCMessage], JSONRPCMessage | Awaitable[JSONRPCMessage]] | ||
|
|
||
|
|
||
| class ProgressFnT(Protocol): | ||
| """Protocol for progress notification callbacks.""" | ||
|
|
@@ -190,6 +194,9 @@ def __init__( | |
| receive_notification_type: type[ReceiveNotificationT], | ||
| # If none, reading will never time out | ||
| read_timeout_seconds: timedelta | None = None, | ||
| *, | ||
| send_middleware: list[MessageMiddleware] | None = None, | ||
| receive_middleware: list[MessageMiddleware] | None = None, | ||
| ) -> None: | ||
| self._read_stream = read_stream | ||
| self._write_stream = write_stream | ||
|
|
@@ -202,6 +209,22 @@ def __init__( | |
| self._progress_callbacks = {} | ||
| self._response_routers = [] | ||
| self._exit_stack = AsyncExitStack() | ||
| self._send_middleware = send_middleware or [] | ||
| self._receive_middleware = receive_middleware or [] | ||
|
|
||
| async def _apply_middleware( | ||
| self, message: JSONRPCMessage, middleware_list: list[MessageMiddleware] | ||
| ) -> JSONRPCMessage: | ||
| """Apply a list of middleware functions to a message.""" | ||
| import inspect | ||
|
|
||
| for middleware in middleware_list: | ||
| result = middleware(message) | ||
| if inspect.isawaitable(result): | ||
|
||
| message = await result | ||
| else: | ||
| message = result # type: ignore[assignment] | ||
| return message | ||
|
|
||
| def add_response_router(self, router: ResponseRouter) -> None: | ||
| """ | ||
|
|
@@ -278,7 +301,9 @@ async def send_request( | |
| **request_data, | ||
| ) | ||
|
|
||
| await self._write_stream.send(SessionMessage(message=JSONRPCMessage(jsonrpc_request), metadata=metadata)) | ||
| message = JSONRPCMessage(jsonrpc_request) | ||
| message = await self._apply_middleware(message, self._send_middleware) | ||
| await self._write_stream.send(SessionMessage(message=message, metadata=metadata)) | ||
|
|
||
| # request read timeout takes precedence over session read timeout | ||
| timeout = None | ||
|
|
@@ -328,24 +353,30 @@ async def send_notification( | |
| jsonrpc="2.0", | ||
| **notification.model_dump(by_alias=True, mode="json", exclude_none=True), | ||
| ) | ||
| message = JSONRPCMessage(jsonrpc_notification) | ||
| message = await self._apply_middleware(message, self._send_middleware) | ||
| session_message = SessionMessage( # pragma: no cover | ||
| message=JSONRPCMessage(jsonrpc_notification), | ||
| message=message, | ||
| metadata=ServerMessageMetadata(related_request_id=related_request_id) if related_request_id else None, | ||
| ) | ||
| await self._write_stream.send(session_message) | ||
|
|
||
| async def _send_response(self, request_id: RequestId, response: SendResultT | ErrorData) -> None: | ||
| if isinstance(response, ErrorData): | ||
| jsonrpc_error = JSONRPCError(jsonrpc="2.0", id=request_id, error=response) | ||
| session_message = SessionMessage(message=JSONRPCMessage(jsonrpc_error)) | ||
| message = JSONRPCMessage(jsonrpc_error) | ||
| message = await self._apply_middleware(message, self._send_middleware) | ||
| session_message = SessionMessage(message=message) | ||
| await self._write_stream.send(session_message) | ||
| else: | ||
| jsonrpc_response = JSONRPCResponse( | ||
| jsonrpc="2.0", | ||
| id=request_id, | ||
| result=response.model_dump(by_alias=True, mode="json", exclude_none=True), | ||
| ) | ||
| session_message = SessionMessage(message=JSONRPCMessage(jsonrpc_response)) | ||
| message = JSONRPCMessage(jsonrpc_response) | ||
| message = await self._apply_middleware(message, self._send_middleware) | ||
| session_message = SessionMessage(message=message) | ||
| await self._write_stream.send(session_message) | ||
|
|
||
| async def _receive_loop(self) -> None: | ||
|
|
@@ -357,7 +388,14 @@ async def _receive_loop(self) -> None: | |
| async for message in self._read_stream: | ||
| if isinstance(message, Exception): # pragma: no cover | ||
| await self._handle_incoming(message) | ||
| elif isinstance(message.message.root, JSONRPCRequest): | ||
| continue | ||
|
|
||
| # Apply receive middleware to transform the message | ||
| if self._receive_middleware: | ||
| transformed_msg = await self._apply_middleware(message.message, self._receive_middleware) | ||
| message = SessionMessage(message=transformed_msg, metadata=message.metadata) # noqa: PLW2901 | ||
|
|
||
| if isinstance(message.message.root, JSONRPCRequest): | ||
| try: | ||
| validated_request = self._receive_request_type.model_validate( | ||
| message.message.root.model_dump(by_alias=True, mode="json", exclude_none=True) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
move to top