|
| 1 | +""" |
| 2 | +Collection of base utils for MCP servers. |
| 3 | +""" |
| 4 | + |
| 5 | +import contextlib |
| 6 | +import logging |
| 7 | +from collections import deque |
| 8 | +from dataclasses import dataclass |
| 9 | +from typing import AsyncIterator |
| 10 | +from uuid import uuid4 |
| 11 | +from starlette.applications import Starlette |
| 12 | +from starlette.routing import Mount |
| 13 | +from starlette.types import Receive, Scope, Send |
| 14 | +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager |
| 15 | + |
| 16 | +from mcp.server import Server |
| 17 | + |
| 18 | +from mcp.server.streamable_http import ( |
| 19 | + EventCallback, |
| 20 | + EventId, |
| 21 | + EventMessage, |
| 22 | + EventStore, |
| 23 | + StreamId, |
| 24 | +) |
| 25 | +from mcp.types import JSONRPCMessage |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | + |
| 30 | +@dataclass |
| 31 | +class EventEntry: |
| 32 | + """ |
| 33 | + Represents an event entry in the event store. |
| 34 | + """ |
| 35 | + |
| 36 | + event_id: EventId |
| 37 | + stream_id: StreamId |
| 38 | + message: JSONRPCMessage |
| 39 | + |
| 40 | + |
| 41 | +class InMemoryEventStore(EventStore): |
| 42 | + """ |
| 43 | + Simple in-memory implementation of the EventStore interface for resumability. |
| 44 | + This is primarily intended for examples and testing, not for production use |
| 45 | + where a persistent storage solution would be more appropriate. |
| 46 | +
|
| 47 | + This implementation keeps only the last N events per stream for memory efficiency. |
| 48 | + """ |
| 49 | + |
| 50 | + def __init__(self, max_events_per_stream: int = 100): |
| 51 | + """Initialize the event store. |
| 52 | +
|
| 53 | + Args: |
| 54 | + max_events_per_stream: Maximum number of events to keep per stream |
| 55 | + """ |
| 56 | + self.max_events_per_stream = max_events_per_stream |
| 57 | + # for maintaining last N events per stream |
| 58 | + self.streams: dict[StreamId, deque[EventEntry]] = {} |
| 59 | + # event_id -> EventEntry for quick lookup |
| 60 | + self.event_index: dict[EventId, EventEntry] = {} |
| 61 | + |
| 62 | + async def store_event( |
| 63 | + self, stream_id: StreamId, message: JSONRPCMessage |
| 64 | + ) -> EventId: |
| 65 | + """Stores an event with a generated event ID.""" |
| 66 | + event_id = str(uuid4()) |
| 67 | + event_entry = EventEntry( |
| 68 | + event_id=event_id, stream_id=stream_id, message=message |
| 69 | + ) |
| 70 | + |
| 71 | + # Get or create deque for this stream |
| 72 | + if stream_id not in self.streams: |
| 73 | + self.streams[stream_id] = deque(maxlen=self.max_events_per_stream) |
| 74 | + |
| 75 | + # If deque is full, the oldest event will be automatically removed |
| 76 | + # We need to remove it from the event_index as well |
| 77 | + if len(self.streams[stream_id]) == self.max_events_per_stream: |
| 78 | + oldest_event = self.streams[stream_id][0] |
| 79 | + self.event_index.pop(oldest_event.event_id, None) |
| 80 | + |
| 81 | + # Add new event |
| 82 | + self.streams[stream_id].append(event_entry) |
| 83 | + self.event_index[event_id] = event_entry |
| 84 | + |
| 85 | + return event_id |
| 86 | + |
| 87 | + async def replay_events_after( |
| 88 | + self, |
| 89 | + last_event_id: EventId, |
| 90 | + send_callback: EventCallback, |
| 91 | + ) -> StreamId | None: |
| 92 | + """Replays events that occurred after the specified event ID.""" |
| 93 | + if last_event_id not in self.event_index: |
| 94 | + logger.warning(f"Event ID {last_event_id} not found in store") |
| 95 | + return None |
| 96 | + |
| 97 | + # Get the stream and find events after the last one |
| 98 | + last_event = self.event_index[last_event_id] |
| 99 | + stream_id = last_event.stream_id |
| 100 | + stream_events = self.streams.get(last_event.stream_id, deque()) |
| 101 | + |
| 102 | + # Events in deque are already in chronological order |
| 103 | + found_last = False |
| 104 | + for event in stream_events: |
| 105 | + if found_last: |
| 106 | + await send_callback(EventMessage(event.message, event.event_id)) |
| 107 | + elif event.event_id == last_event_id: |
| 108 | + found_last = True |
| 109 | + |
| 110 | + return stream_id |
| 111 | + |
| 112 | + |
| 113 | +async def get_serveable_app(app: Server, json_response: bool = True) -> Starlette: |
| 114 | + |
| 115 | + event_store = InMemoryEventStore() |
| 116 | + |
| 117 | + # Create the session manager with our app and event store |
| 118 | + session_manager = StreamableHTTPSessionManager( |
| 119 | + app=app, |
| 120 | + event_store=event_store, # Enable resumability |
| 121 | + json_response=json_response, |
| 122 | + ) |
| 123 | + |
| 124 | + # ASGI handler for streamable HTTP connections |
| 125 | + async def handle_streamable_http( |
| 126 | + scope: Scope, receive: Receive, send: Send |
| 127 | + ) -> None: |
| 128 | + await session_manager.handle_request(scope, receive, send) |
| 129 | + |
| 130 | + @contextlib.asynccontextmanager |
| 131 | + async def lifespan(app: Starlette) -> AsyncIterator[None]: |
| 132 | + """Context manager for managing session manager lifecycle.""" |
| 133 | + async with session_manager.run(): |
| 134 | + logger.info("Application started with StreamableHTTP session manager!") |
| 135 | + try: |
| 136 | + yield |
| 137 | + finally: |
| 138 | + logger.info("Application shutting down...") |
| 139 | + |
| 140 | + # Create an ASGI application using the transport |
| 141 | + return Starlette( |
| 142 | + debug=True, |
| 143 | + routes=[ |
| 144 | + Mount("/mcp", app=handle_streamable_http), |
| 145 | + ], |
| 146 | + lifespan=lifespan, |
| 147 | + ) |
0 commit comments