jd-opensource/joyagent-jdgenie · error · Exception
网络连接失败
Error message
网络连接失败: {str(e)} What it means
Raised by `_sse_connection` when the underlying HTTP/SSE transport raises a network-class error (per `_is_network_error`), such as connection refused, DNS failure, or timeout while opening the SSE stream. The client wraps it into a friendlier message but preserves the cause via `from e`.
Solutions
- Confirm the MCP server is running and reachable: curl/telnet the server_url host and port
- Check server_url for typos (scheme, host, port) in the client configuration
- Check firewall/proxy rules allow the connection and long-lived streaming responses
- If it's flaky infrastructure, retry with backoff; the finally-block cleans up the half-open connection
Example fix
// before client = SseClient(server_url="http://localhost:8080") # server actually on 8000 // after client = SseClient(server_url="http://localhost:8000")
Defensive patterns
Strategy: retry
Validate before calling
import socket host, port = parse_host_port(server_url) socket.create_connection((host, port), timeout=3).close() # raises if unreachable
Type guard
def server_reachable(url: str) -> bool:
try:
host, port = parse_host_port(url)
socket.create_connection((host, port), timeout=3).close()
return True
except OSError:
return False Try / catch
for attempt in range(3):
try:
return await client.ping_server()
except Exception as e:
if "网络连接失败" in str(e):
await asyncio.sleep(2 ** attempt)
else:
raise Prevention
- Add a startup reachability check before using the client
- Pin the server host/port in one config place and validate it
- Monitor server uptime; alert before clients start failing
When it happens
Trigger: ping_server, list_tools, or call_tool attempts an SSE connection while the server host is unreachable: wrong port, server down, DNS failure, firewall, or TLS/network timeout.
Common situations: MCP server not started; server_url typo (wrong host/port/scheme); docker network isolation; proxy blocking long-lived SSE connections; VPN down.
Understand the failure class
Background: ECONNREFUSED and "connection refused" / "could not connect to server" errors: what they mean and how to fix them — this error's family across 44 libraries.
Related errors
- sse listener failed
- 调用接口" + url + "失败:" + response.message()
- sse nl2sql failed:
- 返回结果为空!
- Network response was not ok
AI-assisted analysis of jd-opensource/joyagent-jdgenie@2417e0b8b6 (2026-09-08).
Data as JSON: /api/errors/ce2d47b20df7b0f5.
Report an issue: GitHub.
Appendix: source
Thrown at genie-client/app/client.py:149
# 创建客户端会话
self._session_context = ClientSession(*streams)
session = await self._session_context.__aenter__()
logger.debug(f"[{connection_id}] 客户端会话已创建")
# 初始化会话,可能触发认证验证
await session.initialize()
logger.info(f"[{connection_id}] SSE连接建立成功")
yield session
except Exception as e:
# 根据异常类型进行不同的处理
if self._is_authentication_error(e):
logger.error(f"[{connection_id}] 认证失败 - 401 未授权")
raise Exception("认证失败 - 无效的凭据") from e
elif self._is_network_error(e):
logger.error(f"[{connection_id}] 网络连接失败: {str(e)}")
raise Exception(f"网络连接失败: {str(e)}") from e
else:
logger.error(f"[{connection_id}] SSE连接失败: {str(e)}")
raise
finally:
# 确保资源被正确清理
await self._cleanup_connection(connection_id)
@staticmethod
def _is_authentication_error(exception: Exception) -> bool:
"""
检查异常是否为认证错误 (401 Unauthorized)
Args:
exception: 待检查的异常对象
Returns:
bool: 如果是认证错误返回True,否则返回False
"""View on GitHub (pinned to 2417e0b8b6)