fix: AI 控制台 MCP 不可达给出明确文案——不再显示 SDK 含糊报错

MCP 客户端(streamable_http)在工具服务不可达/返回非 MCP 响应时只抛
'Server returned an error response',用户无法判断原因。改为:
- 后端 web/agent_api.py:_execute 包裹 _load_tools/run_stream,识别连接类错误
  (Server returned an error response/ConnectError/refused 等)后抛明确文案:
  'MCP server(8033) 不可达:无法加载设备工具(<url>)。请确认 MCP server 已启动…'
- 前端 static/admin/agent.js 加 _friendlyAgentError() 兜底映射并去掉
  'RuntimeError:' 之类前缀,三处错误展示统一使用
- 文档同步:MCP.md(依赖提示+本机启动命令)、API.md(SSE error 文案说明)、
  DEPLOY.md(故障排查新增一行)
实测:停掉 MCP 复现 → 前端显示明确文案;启动 MCP 后 AI 控制台正常完成任务
This commit is contained in:
2026-09-10 10:28:57 +08:00
parent 4e67764589
commit 357fe98e22
5 changed files with 55 additions and 12 deletions
+33 -7
View File
@@ -869,14 +869,40 @@ def _agent_thread(run_id, prompt, serial, cfg):
"args": f"命中 {exp_ctx.count(chr(10) + '- ')} 条同类历史经验,已注入参考",
"image": None}))
mcp_url = getattr(getattr(agent, "s", None), "mcp_url", "")
def _mcp_unreachable(err):
"""MCP 客户端在工具服务不可达/返回非 MCP 响应时只抛含糊字样,
识别出来以便给用户明确指引(默认端口 8033)。"""
m = str(err).lower()
return any(k in m for k in (
"server returned an error response", "connecterror",
"connection refused", "all connection attempts failed",
"connection error", "server disconnected",
"network is unreachable", "connect timeout"))
async def _execute():
await agent._load_tools()
return await agent.run_stream(prompt, target,
history=history,
on_delta=on_delta, on_tool=on_tool,
should_stop=lambda: bool(
stop_evt and stop_evt.is_set()),
extra_context=exp_ctx)
try:
await agent._load_tools()
except Exception as e:
if _mcp_unreachable(e):
raise RuntimeError(
f"MCP server(8033) 不可达:无法加载设备工具({mcp_url})。"
f"请确认 MCP server 已启动(本机可运行 "
f"python -m mcp_server.mcp_server,默认端口 8033)") from e
raise
try:
return await agent.run_stream(prompt, target,
history=history,
on_delta=on_delta, on_tool=on_tool,
should_stop=lambda: bool(
stop_evt and stop_evt.is_set()),
extra_context=exp_ctx)
except Exception as e:
if _mcp_unreachable(e):
raise RuntimeError(
f"MCP server(8033) 连接中断:AI 无法继续操作设备({mcp_url})") from e
raise
# 整体超时保护:卡死时结束,释放单实例
answer = asyncio.run(asyncio.wait_for(_execute(), timeout=900))