|
| 1 | +import logging |
| 2 | +from collections.abc import Awaitable, Callable |
| 3 | +from contextlib import asynccontextmanager |
| 4 | +from typing import Protocol, runtime_checkable |
| 5 | +from uuid import UUID |
| 6 | + |
| 7 | +from pydantic import ValidationError |
| 8 | + |
| 9 | +from mcp.shared.message import SessionMessage |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | +MessageCallback = Callable[[SessionMessage | Exception], Awaitable[None]] |
| 14 | + |
| 15 | + |
| 16 | +@runtime_checkable |
| 17 | +class MessageDispatch(Protocol): |
| 18 | + """Abstract interface for SSE message dispatching. |
| 19 | +
|
| 20 | + This interface allows messages to be published to sessions and callbacks to be |
| 21 | + registered for message handling, enabling multiple servers to handle requests. |
| 22 | + """ |
| 23 | + |
| 24 | + async def publish_message( |
| 25 | + self, session_id: UUID, message: SessionMessage | str |
| 26 | + ) -> bool: |
| 27 | + """Publish a message for the specified session. |
| 28 | +
|
| 29 | + Args: |
| 30 | + session_id: The UUID of the session this message is for |
| 31 | + message: The message to publish (SessionMessage or str for invalid JSON) |
| 32 | +
|
| 33 | + Returns: |
| 34 | + bool: True if message was published, False if session not found |
| 35 | + """ |
| 36 | + ... |
| 37 | + |
| 38 | + @asynccontextmanager |
| 39 | + async def subscribe(self, session_id: UUID, callback: MessageCallback): |
| 40 | + """Request-scoped context manager that subscribes to messages for a session. |
| 41 | +
|
| 42 | + Args: |
| 43 | + session_id: The UUID of the session to subscribe to |
| 44 | + callback: Async callback function to handle messages for this session |
| 45 | + """ |
| 46 | + yield |
| 47 | + |
| 48 | + async def session_exists(self, session_id: UUID) -> bool: |
| 49 | + """Check if a session exists. |
| 50 | +
|
| 51 | + Args: |
| 52 | + session_id: The UUID of the session to check |
| 53 | +
|
| 54 | + Returns: |
| 55 | + bool: True if the session is active, False otherwise |
| 56 | + """ |
| 57 | + ... |
| 58 | + |
| 59 | + async def close(self) -> None: |
| 60 | + """Close the message dispatch.""" |
| 61 | + ... |
| 62 | + |
| 63 | + |
| 64 | +class InMemoryMessageDispatch: |
| 65 | + """Default in-memory implementation of the MessageDispatch interface. |
| 66 | +
|
| 67 | + This implementation immediately dispatches messages to registered callbacks when |
| 68 | + messages are received without any queuing behavior. |
| 69 | + """ |
| 70 | + |
| 71 | + def __init__(self) -> None: |
| 72 | + self._callbacks: dict[UUID, MessageCallback] = {} |
| 73 | + |
| 74 | + async def publish_message( |
| 75 | + self, session_id: UUID, message: SessionMessage | str |
| 76 | + ) -> bool: |
| 77 | + """Publish a message for the specified session.""" |
| 78 | + if session_id not in self._callbacks: |
| 79 | + logger.warning(f"Message dropped: unknown session {session_id}") |
| 80 | + return False |
| 81 | + |
| 82 | + # Parse string messages or recreate original ValidationError |
| 83 | + if isinstance(message, str): |
| 84 | + try: |
| 85 | + callback_argument = SessionMessage.model_validate_json(message) |
| 86 | + except ValidationError as exc: |
| 87 | + callback_argument = exc |
| 88 | + else: |
| 89 | + callback_argument = message |
| 90 | + |
| 91 | + # Call the callback with either valid message or recreated ValidationError |
| 92 | + await self._callbacks[session_id](callback_argument) |
| 93 | + |
| 94 | + logger.debug(f"Message dispatched to session {session_id}") |
| 95 | + return True |
| 96 | + |
| 97 | + @asynccontextmanager |
| 98 | + async def subscribe(self, session_id: UUID, callback: MessageCallback): |
| 99 | + """Request-scoped context manager that subscribes to messages for a session.""" |
| 100 | + self._callbacks[session_id] = callback |
| 101 | + logger.debug(f"Subscribing to messages for session {session_id}") |
| 102 | + |
| 103 | + try: |
| 104 | + yield |
| 105 | + finally: |
| 106 | + if session_id in self._callbacks: |
| 107 | + del self._callbacks[session_id] |
| 108 | + logger.debug(f"Unsubscribed from session {session_id}") |
| 109 | + |
| 110 | + async def session_exists(self, session_id: UUID) -> bool: |
| 111 | + """Check if a session exists.""" |
| 112 | + return session_id in self._callbacks |
| 113 | + |
| 114 | + async def close(self) -> None: |
| 115 | + """Close the message dispatch.""" |
| 116 | + pass |
0 commit comments