|
2 | 2 |
|
3 | 3 | import pytest
|
4 | 4 |
|
5 |
| -from mcp.client.stdio import StdioServerParameters, stdio_client |
| 5 | +from mcp.client.session import ClientSession |
| 6 | +from mcp.client.stdio import ( |
| 7 | + StdioServerParameters, |
| 8 | + stdio_client, |
| 9 | +) |
| 10 | +from mcp.shared.exceptions import McpError |
6 | 11 | from mcp.shared.message import SessionMessage
|
7 |
| -from mcp.types import JSONRPCMessage, JSONRPCRequest, JSONRPCResponse |
| 12 | +from mcp.types import CONNECTION_CLOSED, JSONRPCMessage, JSONRPCRequest, JSONRPCResponse |
8 | 13 |
|
9 | 14 | tee: str = shutil.which("tee") # type: ignore
|
| 15 | +python: str = shutil.which("python") # type: ignore |
10 | 16 |
|
11 | 17 |
|
12 | 18 | @pytest.mark.anyio
|
@@ -50,3 +56,43 @@ async def test_stdio_client():
|
50 | 56 | assert read_messages[1] == JSONRPCMessage(
|
51 | 57 | root=JSONRPCResponse(jsonrpc="2.0", id=2, result={})
|
52 | 58 | )
|
| 59 | + |
| 60 | + |
| 61 | +@pytest.mark.anyio |
| 62 | +async def test_stdio_client_bad_path(): |
| 63 | + """Check that the connection doesn't hang if process errors.""" |
| 64 | + server_params = StdioServerParameters( |
| 65 | + command="python", args=["-c", "non-existent-file.py"] |
| 66 | + ) |
| 67 | + async with stdio_client(server_params) as (read_stream, write_stream): |
| 68 | + async with ClientSession(read_stream, write_stream) as session: |
| 69 | + # The session should raise an error when the connection closes |
| 70 | + with pytest.raises(McpError) as exc_info: |
| 71 | + await session.initialize() |
| 72 | + |
| 73 | + # Check that we got a connection closed error |
| 74 | + assert exc_info.value.error.code == CONNECTION_CLOSED |
| 75 | + assert "Connection closed" in exc_info.value.error.message |
| 76 | + |
| 77 | + |
| 78 | +@pytest.mark.anyio |
| 79 | +async def test_stdio_client_nonexistent_command(): |
| 80 | + """Test that stdio_client raises an error for non-existent commands.""" |
| 81 | + # Create a server with a non-existent command |
| 82 | + server_params = StdioServerParameters( |
| 83 | + command="/path/to/nonexistent/command", |
| 84 | + args=["--help"], |
| 85 | + ) |
| 86 | + |
| 87 | + # Should raise an error when trying to start the process |
| 88 | + with pytest.raises(Exception) as exc_info: |
| 89 | + async with stdio_client(server_params) as (_, _): |
| 90 | + pass |
| 91 | + |
| 92 | + # The error should indicate the command was not found |
| 93 | + error_message = str(exc_info.value) |
| 94 | + assert ( |
| 95 | + "nonexistent" in error_message |
| 96 | + or "not found" in error_message.lower() |
| 97 | + or "cannot find the file" in error_message.lower() # Windows error message |
| 98 | + ) |
0 commit comments