Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(mcp): probe SSE with streaming GET

guozirui1ef70ab583800
diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.py
index e29c8c8a35..60d3cbba2b 100644
--- a/jiuwenswarm/common/mcp_config.py
+++ b/jiuwenswarm/common/mcp_config.py
@@ -240,10 +240,12 @@ async def preflight_mcp_server_reachable(
pool=5.0,
)
- headers = {
- "Content-Type": "application/json",
- "Accept": "application/json, text/event-stream",
- }
+ headers = {"Accept": "text/event-stream"}
+ if transport != "sse":
+ headers.update({
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ })
param_headers = params.get("headers") if isinstance(params, dict) else None
if isinstance(param_headers, dict):
headers.update({str(key): str(value) for key, value in param_headers.items()})
@@ -274,7 +276,19 @@ async def preflight_mcp_server_reachable(
try:
async with httpx.AsyncClient(timeout=http_timeout, follow_redirects=False) as client:
- response = await client.post(url, headers=headers, params=query_params, json=body)
+ if transport == "sse":
+ # Legacy MCP SSE establishes the event stream with GET. Only
+ # wait for response headers here; consuming the stream would
+ # block until the configured read timeout.
+ async with client.stream(
+ "GET", url, headers=headers, params=query_params
+ ) as response:
+ status_code = response.status_code
+ else:
+ response = await client.post(
+ url, headers=headers, params=query_params, json=body
+ )
+ status_code = response.status_code
except httpx.TimeoutException as exc:
return False, f"http probe timed out after {read_timeout}s: {type(exc).__name__}"
except (httpx.ConnectError, httpx.NetworkError, httpx.UnsupportedProtocol) as exc:
@@ -284,9 +298,9 @@ async def preflight_mcp_server_reachable(
except Exception as exc: # noqa: BLE001 - preflight must never break startup
return False, f"probe failed: {type(exc).__name__}: {exc}"
- if response.status_code >= 400:
- return False, f"http {response.status_code} from server"
- return True, f"ok (http {response.status_code})"
+ if status_code >= 400:
+ return False, f"http {status_code} from server"
+ return True, f"ok (http {status_code})"
def is_asyncio_outer_cancellation() -> bool:
diff --git a/tests/unit_tests/common/test_mcp_preflight.py b/tests/unit_tests/common/test_mcp_preflight.py
new file mode 100644
index 0000000000..703e795792
--- /dev/null
+++ b/tests/unit_tests/common/test_mcp_preflight.py
@@ -0,0 +1,93 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import httpx
+import pytest
+
+from openjiuwen.core.foundation.tool import McpServerConfig
+
+from jiuwenswarm.common.mcp_config import preflight_mcp_server_reachable
+
+
+class _FakeStreamResponse:
+ def __init__(self, status_code: int) -> None:
+ self.status_code = status_code
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, _exc_type, _exc, _tb) -> None:
+ return None
+
+
+class _FakeAsyncClient:
+ calls: list[tuple[str, str, dict]] = []
+ status_code = 200
+
+ def __init__(self, **_kwargs) -> None:
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, _exc_type, _exc, _tb) -> None:
+ return None
+
+ def stream(self, method: str, url: str, **kwargs):
+ self.calls.append((method, url, kwargs))
+ return _FakeStreamResponse(self.status_code)
+
+ async def post(self, url: str, **kwargs):
+ self.calls.append(("POST", url, kwargs))
+ return SimpleNamespace(status_code=self.status_code)
+
+
+def _config(client_type: str) -> McpServerConfig:
+ return McpServerConfig(
+ server_name="demo",
+ client_type=client_type,
+ server_path="https://example.com/mcp",
+ auth_headers={"Authorization": "Bearer token"},
+ )
+
+
[email protected](autouse=True)
+def _patch_http_client(monkeypatch):
+ _FakeAsyncClient.calls = []
+ _FakeAsyncClient.status_code = 200
+ monkeypatch.setattr(httpx, "AsyncClient", _FakeAsyncClient)
+
+
+async def test_sse_preflight_uses_get_stream_with_auth_header():
+ ok, _reason = await preflight_mcp_server_reachable(_config("sse"))
+
+ assert ok is True
+ method, _url, kwargs = _FakeAsyncClient.calls[0]
+ assert method == "GET"
+ assert kwargs["headers"]["Accept"] == "text/event-stream"
+ assert kwargs["headers"]["Authorization"] == "Bearer token"
+
+
+async def test_streamable_http_preflight_posts_initialize_payload():
+ ok, _reason = await preflight_mcp_server_reachable(
+ _config("streamable-http")
+ )
+
+ assert ok is True
+ method, _url, kwargs = _FakeAsyncClient.calls[0]
+ assert method == "POST"
+ assert kwargs["json"]["method"] == "initialize"
+ assert kwargs["headers"]["Authorization"] == "Bearer token"
+
+
+async def test_sse_preflight_rejects_auth_failure():
+ _FakeAsyncClient.status_code = 401
+
+ ok, reason = await preflight_mcp_server_reachable(_config("sse"))
+
+ assert ok is False
+ assert reason == "http 401 from server"