Skip to content

Build and run agents you can see, understand and trust.

fix(mcp): reject overlapping stateful connection attempts (#3795)

creeda4f43a1f0890
diff --git a/src/agentscope/mcp/_mcp_client.py b/src/agentscope/mcp/_mcp_client.py
index b6f1db8f2..849c5304c 100644
--- a/src/agentscope/mcp/_mcp_client.py
+++ b/src/agentscope/mcp/_mcp_client.py
@@ -358,7 +358,7 @@ class MCPClient(BaseModel):
For stateless connections, this method does nothing.
Raises:
- RuntimeError: If already connected.
+ RuntimeError: If already connected or a connection is in progress.
"""
if not self.is_stateful:
logger.debug(
@@ -372,6 +372,10 @@ class MCPClient(BaseModel):
f"MCP '{self.name}' is already connected. "
"Call close() before reconnecting.",
)
+ if self._lifecycle_task is not None:
+ raise RuntimeError(
+ f"MCP '{self.name}' connection is already in progress.",
+ )
client = self._create_sdk_client()
ready = asyncio.Event()
diff --git a/tests/mcp_client_reconnect_test.py b/tests/mcp_client_reconnect_test.py
index a3fe41232..48171071f 100644
--- a/tests/mcp_client_reconnect_test.py
+++ b/tests/mcp_client_reconnect_test.py
@@ -152,6 +152,54 @@ class MCPClientReconnectTest(IsolatedAsyncioTestCase):
self.assertEqual(len(transports), 2)
self.assertTrue(all(_.enter_count == 1 for _ in transports))
+ async def test_rejects_connect_during_handshake(self) -> None:
+ """The first handshake keeps ownership of the only transport."""
+ handshake_started = asyncio.Event()
+ finish_handshake = asyncio.Event()
+ transport = _OneShotTransport()
+
+ class _BlockingClient(_FakeClient):
+ """Hold the first handshake open while another caller connects."""
+
+ async def connect(self) -> None:
+ """Wait for the test to release the first connection."""
+ handshake_started.set()
+ await finish_handshake.wait()
+
+ with patch(
+ "agentscope.mcp._mcp_client.stdio_client",
+ return_value=transport,
+ ) as create_transport, patch(
+ "agentscope.mcp._mcp_client.SDKClient",
+ _BlockingClient,
+ ):
+ client = MCPClient(
+ name="concurrent_connect",
+ is_stateful=True,
+ mcp_config=StdioMCPConfig(command="unused"),
+ )
+ first = asyncio.create_task(client.connect())
+ try:
+ await asyncio.wait_for(handshake_started.wait(), timeout=5)
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "connection is already in progress",
+ ):
+ await asyncio.wait_for(client.connect(), timeout=5)
+
+ self.assertFalse(first.done())
+ finish_handshake.set()
+ await asyncio.wait_for(first, timeout=5)
+ finally:
+ if not first.done():
+ first.cancel()
+ await asyncio.gather(first, return_exceptions=True)
+ if client.is_connected:
+ await client.close()
+
+ create_transport.assert_called_once()
+ self.assertEqual((transport.enter_count, transport.exit_count), (1, 1))
+
async def test_client_context_is_closed_by_its_owner_task(self) -> None:
"""Connect and close requests may run in different caller tasks."""
transport = _OneShotTransport()