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
+15 -4
View File
@@ -3,6 +3,17 @@ let _agentBusy = false;
let _agentStream = null; // EventSource
let _agentCfgLoaded = false;
// 后端异常文案兜底:MCP 客户端在工具服务不可达时只抛
// "Server returned an error response" 这类含糊字样,这里映射成明确指引。
function _friendlyAgentError(msg){
const raw = String(msg || '');
const s = raw.replace(/^[A-Za-z_]*Error:\s*/, ''); // 去掉 "RuntimeError: " 之类前缀
if(/不可达|连接中断/.test(s)) return s; // 后端已给出明确文案,直接用
if(/mcp_server|server returned an error response|connecterror|connection refused|all connection attempts failed|server disconnected|network is unreachable|connect timeout/i.test(s))
return 'MCP server(8033) 不可达:AI 无法连接设备工具服务,请确认 MCP server 已启动(本机可运行 python -m mcp_server.mcp_server)';
return raw;
}
// ================== 初始化 ==================
let _agentDefaultSerial = '';
function initAgentChat(){
@@ -46,7 +57,7 @@ function restoreRunningFlow(){
const chat = document.getElementById('agent-chat');
if(chat && !chat.children.length){
const div = newAssistantMsg();
div.querySelector('.agent-text').textContent = '⚠ ' + r.error;
div.querySelector('.agent-text').textContent = '⚠ ' + _friendlyAgentError(r.error);
}
}
});
@@ -313,8 +324,8 @@ function sendAgentMsg(){
if(!r||!r.ok){
const msg = r ? (r.error||'启动失败') : '请求失败';
const div = newAssistantMsg();
div.querySelector('.agent-text').textContent = '⚠ ' + msg;
showToast(msg,'error');
div.querySelector('.agent-text').textContent = '⚠ ' + _friendlyAgentError(msg);
showToast(_friendlyAgentError(msg),'error');
return;
}
setRunning(true);
@@ -399,7 +410,7 @@ function listenStream(runId){
if(ev.data) msg = JSON.parse(ev.data).message || msg;
}catch(e){}
if(!msgEl) msgEl = newAssistantMsg();
msgEl.querySelector('.agent-text').textContent = '⚠ ' + msg;
msgEl.querySelector('.agent-text').textContent = '⚠ ' + _friendlyAgentError(msg);
endRun();
});