Skip to content

Commit d3e3763

Browse files
committedMar 13, 2025
refactor: update websocket client to use MessageFrame
Modified the websocket client to work with the new MessageFrame type, preserving raw message text and properly extracting the root JSON-RPC message when sending. Github-Issue:#204
1 parent 898b3a4 commit d3e3763

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed
 

‎src/mcp/client/websocket.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import json
22
import logging
33
from contextlib import asynccontextmanager
4-
from typing import AsyncGenerator
4+
from typing import Any, AsyncGenerator
55

66
import anyio
77
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
@@ -10,6 +10,7 @@
1010
from websockets.typing import Subprotocol
1111

1212
import mcp.types as types
13+
from mcp.types import MessageFrame
1314

1415
logger = logging.getLogger(__name__)
1516

@@ -19,8 +20,8 @@ async def websocket_client(
1920
url: str,
2021
) -> AsyncGenerator[
2122
tuple[
22-
MemoryObjectReceiveStream[types.JSONRPCMessage | Exception],
23-
MemoryObjectSendStream[types.JSONRPCMessage],
23+
MemoryObjectReceiveStream[MessageFrame[Any] | Exception],
24+
MemoryObjectSendStream[MessageFrame[Any]],
2425
],
2526
None,
2627
]:
@@ -53,7 +54,11 @@ async def ws_reader():
5354
async with read_stream_writer:
5455
async for raw_text in ws:
5556
try:
56-
message = types.JSONRPCMessage.model_validate_json(raw_text)
57+
json_message = types.JSONRPCMessage.model_validate_json(
58+
raw_text
59+
)
60+
# Create MessageFrame with JSON message as root
61+
message = MessageFrame(root=json_message, raw=raw_text)
5762
await read_stream_writer.send(message)
5863
except ValidationError as exc:
5964
# If JSON parse or model validation fails, send the exception
@@ -66,8 +71,8 @@ async def ws_writer():
6671
"""
6772
async with write_stream_reader:
6873
async for message in write_stream_reader:
69-
# Convert to a dict, then to JSON
70-
msg_dict = message.model_dump(
74+
# Extract the JSON-RPC message from MessageFrame and convert to JSON
75+
msg_dict = message.root.model_dump(
7176
by_alias=True, mode="json", exclude_none=True
7277
)
7378
await ws.send(json.dumps(msg_dict))

0 commit comments

Comments
 (0)