Skip to content

Commit e592afd

Browse files
committed
refactor: improve notification handling
- Always validate all notifications to ensure proper model structure - Handle cancellation notifications separately (no forwarding to stream) - Simplify notification type checking and error handling - Improve code structure and documentation
1 parent cffdd06 commit e592afd

File tree

1 file changed

+19
-21
lines changed

1 file changed

+19
-21
lines changed

src/mcp/shared/session.py

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -215,15 +215,11 @@ async def _send_response(
215215
)
216216
await self._write_stream.send(JSONRPCMessage(jsonrpc_response))
217217

218-
def _should_validate_notification(self, message_root: JSONRPCNotification) -> bool:
218+
def _is_cancellation_notification(self, message_root: JSONRPCNotification) -> bool:
219219
"""
220-
Determines if a notification should be validated.
221-
Internal notifications (like notifications/cancelled) should be ignored.
220+
Determines if a notification is a cancellation notification.
222221
"""
223-
return (
224-
getattr(message_root, "method", None) != "notifications/cancelled" and
225-
not self._closed
226-
)
222+
return getattr(message_root, "method", None) == "notifications/cancelled"
227223

228224
async def _receive_loop(self) -> None:
229225
async with (
@@ -253,20 +249,22 @@ async def _receive_loop(self) -> None:
253249
if not responder._responded:
254250
await self._incoming_message_stream_writer.send(responder)
255251
elif isinstance(message.root, JSONRPCNotification):
256-
if self._should_validate_notification(message.root):
257-
try:
258-
notification = self._receive_notification_type.model_validate(
259-
message.root.model_dump(
260-
by_alias=True, mode="json", exclude_none=True
261-
)
262-
)
263-
if not self._closed:
264-
await self._received_notification(notification)
265-
await self._incoming_message_stream_writer.send(notification)
266-
except Exception:
267-
# Ignore validation errors for notifications during cleanup
268-
if not self._closed:
269-
raise
252+
# Always validate the notification to ensure it matches our model
253+
notification = self._receive_notification_type.model_validate(
254+
message.root.model_dump(
255+
by_alias=True, mode="json", exclude_none=True
256+
)
257+
)
258+
259+
# Handle notifications differently based on their type
260+
if not self._closed:
261+
# Send internal notifications only to the handler
262+
if self._is_cancellation_notification(message.root):
263+
await self._received_notification(notification)
264+
# Forward other notifications to both handler and stream
265+
else:
266+
await self._received_notification(notification)
267+
await self._incoming_message_stream_writer.send(notification)
270268
else: # Response or error
271269
stream = self._response_streams.pop(message.root.id, None)
272270
if stream:

0 commit comments

Comments
 (0)