AssertionError in ClientSession.initialize() when writing to anyio stdio stream
Body:
Describe the bug
When using mcp.ClientSession with stdio streams obtained directly from anyio.open_process, calling await session.initialize() fails with an AssertionError. The traceback indicates that the underlying anyio stream's write method (specifically asyncio.unix_events._UnixWritePipeTransport.write) is receiving a mcp.model.JSONRPCMessage object instead of the expected bytes, bytearray, or memoryview.
This suggests that mcp.shared.session.send_request might not be encoding the JSONRPCMessage object into bytes (e.g., JSON string -> UTF-8 bytes + newline) before attempting to send it over the stdio byte stream provided by anyio.
Steps To Reproduce
-
Create a minimal dummy stdio server (e.g.,
dummy_server.py):# dummy_server.py import sys import json import time print(f"Dummy Server: Started", file=sys.stderr) try: for line in sys.stdin: line = line.strip() print(f"Dummy Server: Received line: {line}", file=sys.stderr) if not line: continue try: request = json.loads(line) # Respond to initialize for testing if request.get("method") == "initialize": response = { "jsonrpc": "2.0", "id": request.get("id", None), "result": {"serverInfo": {"name": "dummy"}} } print(json.dumps(response), flush=True) # Respond on stdout print(f"Dummy Server: Sent initialize response", file=sys.stderr) else: # Ignore other methods for this minimal repro print(f"Dummy Server: Ignoring method {request.get('method')}", file=sys.stderr) except json.JSONDecodeError: print(f"Dummy Server: Received non-JSON line: {line}", file=sys.stderr) except Exception as e: print(f"Dummy Server: Error processing input: {e}", file=sys.stderr) except KeyboardInterrupt: print("Dummy Server: Exiting", file=sys.stderr) except Exception as e: print(f"Dummy Server: Top-level error: {e}", file=sys.stderr) finally: print("Dummy Server: Stdin closed or error.", file=sys.stderr) -
Create a client script using
anyioandmcp.ClientSession(e.g.,repro_client.py):# repro_client.py import asyncio import anyio import subprocess import sys import logging from mcp import ClientSession logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger("ReproClient") # Adjust path to your dummy_server.py and python executable PYTHON_EXEC = sys.executable SERVER_SCRIPT = "dummy_server.py" CMD = [PYTHON_EXEC, SERVER_SCRIPT] async def main(): logger.info(f"Starting dummy server process: {CMD}") process = None try: process = await anyio.open_process( CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE # Capture stderr ) logger.info(f"Process started (PID: {process.pid}). Streams: stdin={process.stdin}, stdout={process.stdout}") if process.stdin is None or process.stdout is None: logger.error("Failed to get stdio streams!") return # Start stderr reader task async def log_stderr(stderr): if stderr is None: return async for line in stderr: logger.warning(f"SERVER STDERR: {line.decode().strip()}") stderr_task = asyncio.create_task(log_stderr(process.stderr)) logger.info("Creating ClientSession...") # Create session directly with anyio streams session = ClientSession(process.stdout, process.stdin) logger.info("Calling session.initialize()...") try: # This is where the AssertionError occurs init_result = await session.initialize() logger.info(f"Initialize successful: {init_result}") except AssertionError as ae: logger.exception("Caught AssertionError during initialize!") # Log full traceback except Exception as e: logger.exception(f"Caught other exception during initialize: {e}") except Exception as e: logger.exception(f"Error opening process or creating session: {e}") finally: if process: logger.info("Terminating process...") try: process.terminate() await process.wait() except Exception: pass # Ignore cleanup errors if 'stderr_task' in locals() and stderr_task: stderr_task.cancel() try: await stderr_task except asyncio.CancelledError: pass logger.info("Client finished.") if __name__ == "__main__": asyncio.run(main()) -
Run the client script:
python repro_client.py
Expected behavior
await session.initialize() should successfully send the JSON-RPC "initialize" request (encoded as bytes, likely with a newline) to the server process's stdin. It should then wait for and parse the response from the server's stdout, without raising an AssertionError related to type mismatches during the send operation.
Actual behavior
The script fails during the await session.initialize() call with the following AssertionError:
Traceback (most recent call last):
File "/path/to/your/project/src/meta_agent_pkg/services/mcp_client.py", line 195, in get_mcp_session
await session.initialize()
File "/path/to/your/project/.venv/lib/python3.11/site-packages/mcp/client/session.py", line 102, in initialize
result = await self.send_request(
^^^^^^^^^^^^^^^^^^^^^^^^
File "/path/to/your/project/.venv/lib/python3.11/site-packages/mcp/shared/session.py", line 257, in send_request
await self._write_stream.send(JSONRPCMessage(jsonrpc_request)) # type: ignore[arg-type]
File "/path/to/your/project/.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 1040, in send
self._stream.write(item)
File "/usr/local/lib/python3.11/asyncio/streams.py", line 346, in write
self._transport.write(data)
File "/usr/local/lib/python3.11/asyncio/unix_events.py", line 679, in write
assert isinstance(data, (bytes, bytearray, memoryview)), repr(data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: JSONRPCMessage(root=JSONRPCRequest(method='initialize', params={'protocolVersion': '2024-11-05', 'capabilities': {'sampling': {}, 'roots': {'listChanged': True}}, 'clientInfo': {'name': 'mcp', 'version': '0.1.0'}}, jsonrpc='2.0', id=0))
(Note: Line numbers in the traceback above refer to the user's project, but the key failure is the AssertionError in asyncio/unix_events.py)
Environment:
mcpversion: 1.6.0anyioversion: 4.9.0- Python version: 3.11.x
- Operating System: Linux (Debian/Ubuntu based likely)
Possible Cause / Suggestion
It appears mcp.shared.session.send_request attempts to send the Pydantic model JSONRPCMessage directly to the anyio ByteStream's send method. However, the stream expects bytes-like data.
The send_request function should likely encode the JSONRPCMessage object into a suitable byte format (e.g., message.model_dump_json().encode('utf-8') + b'\n') before calling await self._write_stream.send(...).
Workaround
A temporary workaround involves creating a wrapper class around the anyio write stream that intercepts JSONRPCMessage objects, encodes them to bytes+newline manually, and then calls the underlying stream's send method. This confirms the issue is with encoding before sending.
Thanks for looking into this!
I'm unsure why are you are 're-creating' your own MCP server and then using ClientSession to connect with it.
However, I believe the error stems from how you are connecting to your server. I re-wrote your client script to use MCP's stdio_client to connect to the server, and didn't run into the Assertion Error:
# repro_client.py
import asyncio
import logging
import sys
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("ReproClient")
# Adjust path to your dummy_server.py and python executable
PYTHON_EXEC = sys.executable
SERVER_SCRIPT = "dummy_server.py"
CMD = [PYTHON_EXEC, SERVER_SCRIPT]
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command=PYTHON_EXEC, # Executable
args=[SERVER_SCRIPT], # Optional command line arguments
env=None, # Optional environment variables
)
async def main():
logger.info(f"Starting dummy server process: {CMD}")
try:
async with stdio_client(server_params, sys.stderr) as (read, write):
# Start stderr reader task
async def log_stderr(stderr):
if stderr is None:
return
async for line in stderr:
logger.warning(f"SERVER STDERR: {line.decode().strip()}")
stderr_task = asyncio.create_task(log_stderr(sys.stderr))
logger.info("Creating ClientSession...")
# Create session directly with anyio streams
session = ClientSession(read, write)
logger.info("Calling session.initialize()...")
try:
# This is where the AssertionError occurs
init_result = await session.initialize()
logger.info(f"Initialize successful: {init_result}")
except AssertionError:
logger.exception(
"Caught AssertionError during initialize!"
) # Log full traceback
except Exception as e:
logger.exception(f"Caught other exception during initialize: {e}")
except Exception as e:
logger.exception(f"Error opening process or creating session: {e}")
finally:
if "stderr_task" in locals() and stderr_task:
stderr_task.cancel()
try:
await stderr_task
except asyncio.CancelledError:
pass
logger.info("Client finished.")
if __name__ == "__main__":
asyncio.run(main())
I'm guessing the error stems from how process was handling the read write streams compared to stdio_client which encodes the messages and handles the streams. Hopefully this helps, and if you want to create your own MCP servers/clients at a lower level, I would look into the MCP Server() and Client() base classes.
Hi @aandresalvarez given this has been open a while, is this still an issue?