Skip to content

Commit a73fc7d

Browse files
committed
fix: improve error handling and request cancellation for issue #88
1 parent 827e494 commit a73fc7d

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

src/mcp/shared/session.py

+22-12
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
from contextlib import AbstractAsyncContextManager
23
from datetime import timedelta
34
from typing import Any, Callable, Generic, TypeVar
@@ -273,19 +274,28 @@ async def _receive_loop(self) -> None:
273274
await self._incoming_message_stream_writer.send(responder)
274275

275276
elif isinstance(message.root, JSONRPCNotification):
276-
notification = self._receive_notification_type.model_validate(
277-
message.root.model_dump(
278-
by_alias=True, mode="json", exclude_none=True
277+
try:
278+
notification = self._receive_notification_type.model_validate(
279+
message.root.model_dump(
280+
by_alias=True, mode="json", exclude_none=True
281+
)
282+
)
283+
# Handle cancellation notifications
284+
if isinstance(notification.root, CancelledNotification):
285+
cancelled_id = notification.root.params.requestId
286+
if cancelled_id in self._in_flight:
287+
await self._in_flight[cancelled_id].cancel()
288+
else:
289+
await self._received_notification(notification)
290+
await self._incoming_message_stream_writer.send(
291+
notification
292+
)
293+
except Exception as e:
294+
# For other validation errors, log and continue
295+
logging.warning(
296+
f"Failed to validate notification: {e}. "
297+
f"Message was: {message.root}"
279298
)
280-
)
281-
# Handle cancellation notifications
282-
if isinstance(notification.root, CancelledNotification):
283-
cancelled_id = notification.root.params.requestId
284-
if cancelled_id in self._in_flight:
285-
await self._in_flight[cancelled_id].cancel()
286-
else:
287-
await self._received_notification(notification)
288-
await self._incoming_message_stream_writer.send(notification)
289299
else: # Response or error
290300
stream = self._response_streams.pop(message.root.id, None)
291301
if stream:

0 commit comments

Comments
 (0)