|
| 1 | +import json |
| 2 | +import logging |
| 3 | +from contextlib import asynccontextmanager |
| 4 | +from typing import AsyncGenerator |
| 5 | + |
| 6 | +import anyio |
| 7 | +import websockets |
| 8 | +from anyio.streams.memory import ( |
| 9 | + MemoryObjectReceiveStream, |
| 10 | + MemoryObjectSendStream, |
| 11 | + create_memory_object_stream, |
| 12 | +) |
| 13 | + |
| 14 | +import mcp.types as types |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | +@asynccontextmanager |
| 19 | +async def websocket_client( |
| 20 | + url: str |
| 21 | +) -> AsyncGenerator[ |
| 22 | + tuple[ |
| 23 | + MemoryObjectReceiveStream[types.JSONRPCMessage | Exception], |
| 24 | + MemoryObjectSendStream[types.JSONRPCMessage], |
| 25 | + ], |
| 26 | + None |
| 27 | +]: |
| 28 | + """ |
| 29 | + WebSocket client transport for MCP, symmetrical to the server version. |
| 30 | +
|
| 31 | + Connects to 'url' using the 'mcp' subprotocol, then yields: |
| 32 | + (read_stream, write_stream) |
| 33 | +
|
| 34 | + - read_stream: As you read from this stream, you'll receive either valid |
| 35 | + JSONRPCMessage objects or Exception objects (when validation fails). |
| 36 | + - write_stream: Write JSONRPCMessage objects to this stream to send them |
| 37 | + over the WebSocket to the server. |
| 38 | + """ |
| 39 | + |
| 40 | + # Create two in-memory streams: |
| 41 | + # - One for incoming messages (read_stream_recv, written by ws_reader) |
| 42 | + # - One for outgoing messages (write_stream_send, read by ws_writer) |
| 43 | + read_stream_send, read_stream_recv = create_memory_object_stream(0) |
| 44 | + write_stream_send, write_stream_recv = create_memory_object_stream(0) |
| 45 | + |
| 46 | + # Connect using websockets, requesting the "mcp" subprotocol |
| 47 | + async with websockets.connect(url, subprotocols=["mcp"]) as ws: |
| 48 | + # Optional check to ensure the server actually accepted "mcp" |
| 49 | + if ws.subprotocol != "mcp": |
| 50 | + raise ValueError( |
| 51 | + f"Server did not accept subprotocol 'mcp'. Actual subprotocol: {ws.subprotocol}" |
| 52 | + ) |
| 53 | + |
| 54 | + async def ws_reader(): |
| 55 | + """ |
| 56 | + Reads text messages from the WebSocket, parses them as JSON-RPC messages, |
| 57 | + and sends them into read_stream_send. |
| 58 | + """ |
| 59 | + try: |
| 60 | + async for raw_text in ws: |
| 61 | + try: |
| 62 | + data = json.loads(raw_text) |
| 63 | + message = types.JSONRPCMessage.model_validate(data) |
| 64 | + await read_stream_send.send(message) |
| 65 | + except Exception as exc: |
| 66 | + # If JSON parse or model validation fails, send the exception |
| 67 | + await read_stream_send.send(exc) |
| 68 | + except (anyio.ClosedResourceError, websockets.ConnectionClosed): |
| 69 | + pass |
| 70 | + finally: |
| 71 | + # Ensure our read stream is closed |
| 72 | + await read_stream_send.aclose() |
| 73 | + |
| 74 | + async def ws_writer(): |
| 75 | + """ |
| 76 | + Reads JSON-RPC messages from write_stream_recv and sends them to the server. |
| 77 | + """ |
| 78 | + try: |
| 79 | + async for message in write_stream_recv: |
| 80 | + # Convert to a dict, then to JSON |
| 81 | + msg_dict = message.model_dump( |
| 82 | + by_alias=True, mode="json", exclude_none=True |
| 83 | + ) |
| 84 | + await ws.send(json.dumps(msg_dict)) |
| 85 | + except (anyio.ClosedResourceError, websockets.ConnectionClosed): |
| 86 | + pass |
| 87 | + finally: |
| 88 | + # Ensure our write stream is closed |
| 89 | + await write_stream_recv.aclose() |
| 90 | + |
| 91 | + async with anyio.create_task_group() as tg: |
| 92 | + # Start reader and writer tasks |
| 93 | + tg.start_soon(ws_reader) |
| 94 | + tg.start_soon(ws_writer) |
| 95 | + |
| 96 | + # Yield the receive/send streams |
| 97 | + yield (read_stream_recv, write_stream_send) |
| 98 | + |
| 99 | + # Once the caller's 'async with' block exits, we shut down |
| 100 | + tg.cancel_scope.cancel() |
0 commit comments