Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(mcp): detect SSE transport by URL path so query strings work (#2311)
GodYaob6e6906e5ff7
diff --git a/src/agentscope/mcp/_mcp_client.py b/src/agentscope/mcp/_mcp_client.pyindex 761d5265c..c3d448dbc 100644--- a/src/agentscope/mcp/_mcp_client.py+++ b/src/agentscope/mcp/_mcp_client.py@@ -3,6 +3,7 @@import refrom contextlib import AsyncExitStack, _AsyncGeneratorContextManagerfrom typing import Any, TYPE_CHECKING+from urllib.parse import urlsplitimport httpximport mcp.types@@ -184,8 +185,14 @@ class MCPClient(BaseModel):"""Create an HTTP MCP client (SSE or streamable HTTP)."""config = self.mcp_config- # Determine transport from URL- if config.url.endswith("/sse") or config.url.endswith("/messages/"):+ # Determine transport from the URL *path* only. Inspecting the full+ # URL with endswith would misdetect SSE endpoints whose URL carries+ # a query string (e.g. https://mcp.amap.com/sse?key=API_KEY): such+ # URLs no longer end with '/sse' and would fall through to the+ # streamable HTTP transport, which then fails to handshake against+ # an SSE server with 'Session terminated'.+ path = urlsplit(config.url).path+ if path.endswith("/sse") or path.endswith("/messages/"):return sse_client(url=config.url,headers=config.headers,diff --git a/tests/mcp_sse_client_test.py b/tests/mcp_sse_client_test.pyindex f7df7106a..cc8715d58 100644--- a/tests/mcp_sse_client_test.py+++ b/tests/mcp_sse_client_test.py@@ -279,6 +279,36 @@ class SseMCPClientTest(IsolatedAsyncioTestCase):await stateful_client.close()self.assertFalse(stateful_client.is_connected)+ async def test_stateless_client_with_query_string_in_url(self) -> None:+ """An SSE URL carrying a query string must still be detected as SSE.++ Regression test: ``_create_http_client`` used to detect the transport+ with ``url.endswith('/sse')``, which fails for URLs that carry a query+ string such as ``http://host:port/sse?key=API_KEY`` (a very common+ shape for key-based SSE MCP servers, e.g. the Amap MCP at+ https://mcp.amap.com/sse?key=API_KEY). Such URLs were misdetected as+ streamable HTTP, and the client then failed to handshake against the+ SSE server with ``McpError: Session terminated``.++ After the fix, only the URL path is inspected, so the query string no+ longer affects transport detection.+ """+ client = MCPClient(+ name="test_sse_query_client",+ is_stateful=False,+ mcp_config=HttpMCPConfig(+ type="http_mcp",+ url=f"http://127.0.0.1:{self.port}/sse?key=API_KEY",+ ),+ )++ mcp_tool_1 = await client.get_tool("tool_1")+ res: ToolChunk = await mcp_tool_1(arg1="123", arg2=[1, 2, 3])+ self.assertEqual(+ res.content[0].text,+ "arg1: 123, arg2: [1, 2, 3]",+ )+class SseSchemaDefsPreservationTest(IsolatedAsyncioTestCase):"""End-to-end tests for $defs preservation in MCP tool schemas.