AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

[Bug][Fixed] mcp服务异常mcp.shared.exceptions.McpError: Session terminated

Open jiangxiaoxuan0721 opened this issue 3 months ago • 2 comments

问题描述

docker使用镜像源部署,添加https://mcpmarket.cn的mcp服务的时候发现mcp.shared.exceptions.McpError: Session terminated。 临时修复:容器内运行

cd /tmp && cat > fix_mcp.py << 'PYEOF'
import io

path = "/AstrBot/astrbot/core/agent/mcp_client.py"
src = io.open(path, encoding="utf-8").read()

# 1. 顶部加 import
if "from mcp.shared.exceptions import McpError" not in src:
    assert "import httpx\n" in src, "import anchor not found"
    src = src.replace(
        "import httpx\n",
        "import httpx\nfrom mcp.shared.exceptions import McpError\n",
        1,
    )

# 2. 扩大重试条件
old_retry = "retry=retry_if_exception_type(anyio.ClosedResourceError),"
new_retry = "retry=retry_if_exception_type((anyio.ClosedResourceError, TimeoutError, McpError)),"
assert src.count(old_retry) == 1, "retry anchor not found"
src = src.replace(old_retry, new_retry)

# 3. 扩大异常捕获并加重连保护
old_exc = """            except anyio.ClosedResourceError:
                logger.warning(
                    f"MCP tool {tool_name} call failed (ClosedResourceError), attempting to reconnect..."
                )
                # Attempt to reconnect
                await self._reconnect()
                # Reraise the exception to trigger tenacity retry
                raise"""
new_exc = """            except (anyio.ClosedResourceError, TimeoutError, McpError) as e:
                logger.warning(
                    f"MCP tool {tool_name} call failed ({type(e).__name__}: {e}), attempting to reconnect..."
                )
                # Attempt to reconnect (best effort, don't mask the original error)
                try:
                    await self._reconnect()
                except Exception as re:
                    logger.error(f"Reconnect failed: {re}")
                # Reraise the exception to trigger tenacity retry
                raise"""
assert src.count(old_exc) == 1, "except anchor not found"
src = src.replace(old_exc, new_exc)

io.open(path, "w", encoding="utf-8").write(src)
print("OK: 三处修改全部完成")
PYEOF
python fix_mcp.py

重启容器后得到解决

如何复现?

正常docker部署,用镜像源m.daocloud.io/docker.io/soulter/astrbot:latest+m.daocloud.io/docker.io/mlikiowa/napcat-docker:latest(版本对应为4.27.4),添加配置: root@663fab43182d:/AstrBot/data# cat mcp_server.json { "mcpServers": { "高德地图": { "active": true, "transport": "streamable_http", "url": "https://mcpmarket.cn/mcp/688537b7d00f731bbe02e03e", "headers": {}, "timeout": 5, "sse_read_timeout": 300 }, "天气查询": { "active": true, "transport": "streamable_http", "url": "https://mcpmarket.cn/mcp/5b3f77de1dac10ca4f373352", "headers": {}, "timeout": 5, "sse_read_timeout": 300 }, "12306服务": { "active": true, "transport": "streamable_http", "url": "https://mcpmarket.cn/mcp/6e628a618abaac31b04789e4", "headers": {}, "timeout": 5, "sse_read_timeout": 300 }, "MarkitDown": { "active": true, "transport": "streamable_http", "url": "https://mcpmarket.cn/mcp/bfd0296c9522e068abfc6178", "headers": {}, "timeout": 5, "sse_read_timeout": 300 }, "百度搜索": { "active": true, "transport": "streamable_http", "url": "https://mcpmarket.cn/mcp/559f4b2ecdd8d3b2efd477fa", "headers": {}, "timeout": 5, "sse_read_timeout": 300 } } } 在对话中服务不可用。

AstrBot 版本

v4.27.4

操作系统

Linux

部署方式

docker

使用的消息平台适配器

Onebot v11

错误日志

[2026-08-27 07:00:07.922] [Core]
[INFO]
[runners.tool_loop_agent_runner:1152]: 使用工具:get_weather_forecast,参数:{'latitude': 31.4914, 'longitude': 120.3119, 'days': 1, 'hourly_vars': 'temperature_2m,precipitation,windspeed_10m,weathercode,relative_humidity_2m'}
[2026-08-27 07:00:08.078] [Core]
[WARN]
[v4.27.4] [runners.tool_loop_agent_runner:1324]: Traceback (most recent call last):
  File "/AstrBot/astrbot/core/agent/runners/tool_loop_agent_runner.py", line 1206, in _handle_function_tools
    async for resp in self._iter_tool_executor_results(executor):  # type: ignore
  File "/AstrBot/astrbot/core/agent/runners/tool_loop_agent_runner.py", line 1561, in _iter_tool_executor_results
    yield next_result_task.result()
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/agent/runners/tool_loop_agent_runner.py", line 1531, in _next_executor_result
    return await anext(executor)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/astr_agent_tool_exec.py", line 185, in execute
    async for r in cls._execute_local(tool, run_context, **tool_args):
  File "/AstrBot/astrbot/core/astr_agent_tool_exec.py", line 666, in _execute_local
    resp = await asyncio.wait_for(
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/asyncio/tasks.py", line 520, in wait_for
    return await fut
           ^^^^^^^^^
  File "/AstrBot/astrbot/core/astr_agent_tool_exec.py", line 807, in call_local_llm_tool
    ret = await ready_to_call
          ^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/provider/func_tool_manager.py", line 269, in call
    return await self._wrapped.call(context, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/agent/mcp_client.py", line 817, in call
    return await self.mcp_client.call_tool_with_reconnect(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/agent/mcp_client.py", line 774, in call_tool_with_reconnect
    return await _call_with_retry()
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/asyncio/__init__.py", line 193, in async_wrapped
    return await copy(fn, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/asyncio/__init__.py", line 112, in __call__
    do = await self.iter(retry_state=retry_state)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/asyncio/__init__.py", line 157, in iter
    result = await action(retry_state)
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/_utils.py", line 111, in inner
    return call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/__init__.py", line 393, in <lambda>
    self._add_action_func(lambda rs: rs.outcome.result())
                                     ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/concurrent/futures/_base.py", line 449, in result
    return self.__get_result()
           ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/concurrent/futures/_base.py", line 401, in __get_result
    raise self._exception
  File "/usr/local/lib/python3.12/site-packages/tenacity/asyncio/__init__.py", line 116, in __call__
    result = await fn(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/agent/mcp_client.py", line 760, in _call_with_retry
    return await self.session.call_tool(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/mcp/client/session.py", line 401, in call_tool
    result = await self.send_request(
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/mcp/shared/session.py", line 306, in send_request
    raise McpError(response_or_error.error)
mcp.shared.exceptions.McpError: Session terminated
[2026-08-27 07:00:08.079] [Core]
[INFO]
[runners.tool_loop_agent_runner:1349]: Tool `get_weather_forecast` Result: error: Session terminated
[2026-08-28 07:00:05.933] [Core]
[INFO]
[runners.tool_loop_agent_runner:1096]: Agent 使用工具: ['get-current-date', 'get_weather_forecast']
[2026-08-28 07:00:05.933] [Core]
[INFO]
[runners.tool_loop_agent_runner:1152]: 使用工具:get-current-date,参数:{}
[2026-08-28 07:02:05.975] [Core]
[WARN]
[v4.27.4] [runners.tool_loop_agent_runner:1324]: Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/anyio/streams/memory.py", line 118, in receive
    return self.receive_nowait()
           ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/streams/memory.py", line 113, in receive_nowait
    raise WouldBlock
anyio.WouldBlock

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.12/asyncio/tasks.py", line 520, in wait_for
    return await fut
           ^^^^^^^^^
  File "/AstrBot/astrbot/core/astr_agent_tool_exec.py", line 807, in call_local_llm_tool
    ret = await ready_to_call
          ^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/provider/func_tool_manager.py", line 269, in call
    return await self._wrapped.call(context, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/agent/mcp_client.py", line 817, in call
    return await self.mcp_client.call_tool_with_reconnect(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/agent/mcp_client.py", line 774, in call_tool_with_reconnect
    return await _call_with_retry()
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/asyncio/__init__.py", line 193, in async_wrapped
    return await copy(fn, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/asyncio/__init__.py", line 112, in __call__
    do = await self.iter(retry_state=retry_state)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/asyncio/__init__.py", line 157, in iter
    result = await action(retry_state)
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/_utils.py", line 111, in inner
    return call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/__init__.py", line 393, in <lambda>
    self._add_action_func(lambda rs: rs.outcome.result())
                                     ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/concurrent/futures/_base.py", line 449, in result
    return self.__get_result()
           ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/concurrent/futures/_base.py", line 401, in __get_result
    raise self._exception
  File "/usr/local/lib/python3.12/site-packages/tenacity/asyncio/__init__.py", line 116, in __call__
    result = await fn(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/agent/mcp_client.py", line 760, in _call_with_retry
    return await self.session.call_tool(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/mcp/client/session.py", line 401, in call_tool
    result = await self.send_request(
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/mcp/shared/session.py", line 292, in send_request
    response_or_error = await response_stream_reader.receive()
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/streams/memory.py", line 126, in receive
    await receive_event.wait()
  File "/usr/local/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 1866, in wait
    await self._event.wait()
  File "/usr/local/lib/python3.12/asyncio/locks.py", line 212, in wait
    await fut
asyncio.exceptions.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/AstrBot/astrbot/core/astr_agent_tool_exec.py", line 666, in _execute_local
    resp = await asyncio.wait_for(
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/asyncio/tasks.py", line 519, in wait_for
    async with timeouts.timeout(timeout):
               ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/asyncio/timeouts.py", line 115, in __aexit__
    raise TimeoutError from exc_val
TimeoutError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/AstrBot/astrbot/core/agent/runners/tool_loop_agent_runner.py", line 1206, in _handle_function_tools
    async for resp in self._iter_tool_executor_results(executor):  # type: ignore
  File "/AstrBot/astrbot/core/agent/runners/tool_loop_agent_runner.py", line 1561, in _iter_tool_executor_results
    yield next_result_task.result()
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/agent/runners/tool_loop_agent_runner.py", line 1531, in _next_executor_result
    return await anext(executor)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/AstrBot/astrbot/core/astr_agent_tool_exec.py", line 185, in execute
    async for r in cls._execute_local(tool, run_context, **tool_args):
  File "/AstrBot/astrbot/core/astr_agent_tool_exec.py", line 699, in _execute_local
    raise Exception(
Exception: tool get-current-date execution timeout after 120 seconds.
[2026-08-28 07:02:05.976] [Core]
[INFO]
[runners.tool_loop_agent_runner:1349]: Tool `get-current-date` Result: error: tool get-current-date execution timeout after 120 seconds.
[2026-08-28 07:02:05.992] [Core]
[INFO]

辅助信息

No response

检查清单

  • [x] 我已在 Issue 列表中搜索过相关问题仍无法解决,或该问题从未被报告过。
  • [x] 我已尝试过禁用所有插件,排除了可能是因插件导致的问题。
  • [x] 我报告的问题与 AstrBot 本体相关,而非在报告某一插件的问题。
  • [x] 我已阅读并同意本项目的贡献者行为准则。
  • [x] (可选)我愿意提交 PR 以帮助修复该问题。

jiangxiaoxuan0721 avatar Aug 28 '26 08:08 jiangxiaoxuan0721

Issue #9859 修复报告

📋 问题概述

MCP 服务连接异常导致工具调用失败。

  • 报错: mcp.shared.exceptions.McpError: Session terminated
  • 环境: Docker 部署,v4.27.4
  • 触发: 连接第三方 MCP 服务(如 mcpmarket.cn)

🔍 根因分析

MCP 客户端缺乏对会话终止和超时异常的重试与重连机制,导致服务直接中断。

🛠️ 修复方案

修改 astrbot/core/agent/mcp_client.py:

  1. 导入异常: 增加 from mcp.shared.exceptions import McpError
  2. 扩大重试: 重试配置增加 TimeoutError 和 McpError
  3. 增加重连: 在异常捕获块中增加 await self._reconnect()

由 AI 生成 | 2026-09-13 来源:https://github.com/AstrBotDevs/AstrBot/issues/9859

silvaling avatar Sep 13 '26 13:09 silvaling

我按当前 master@95e98b8 重新核对了这份“临时修复”。结论是:“会话终止后需要重建连接”这个方向成立,但不建议把所有 McpError 和 TimeoutError 都直接加入自动重试。 现有 AI 评论遗漏了两个会造成回归的关键点。

已确认的代码路径

  • astrbot/core/agent/mcp_client.py::MCPClient.call_tool_with_reconnect() 当前只对 anyio.ClosedResourceError 做“重连 + 最多再调用一次”。
  • MCPTool.call() 能拿到完整的 self.mcp_tool,但调用 call_tool_with_reconnect() 时只传了工具名和参数,工具的 annotations(例如只读提示)没有参与重放决策。
  • 日志里的第二个超时并不是在 call_tool_with_reconnect() 内部抛出的:astrbot/core/astr_agent_tool_exec.py::_execute_local() 用 asyncio.wait_for(anext(wrapper), timeout=effective_timeout) 包住整个工具调用。超时发生时,内层先收到取消,随后外层把 asyncio.TimeoutError 转成普通 Exception("tool ... execution timeout")。因此仅在 _call_with_retry() 中增加 except TimeoutError,并不能覆盖这条实际调用链。

风险原因链

McpError 不只表示 “Session terminated”,也可能是 MCP 服务端对某次具体工具调用返回的业务错误;而超时/断线发生时,客户端通常无法确定服务端是否已经执行了操作。如果无条件重放写入类工具(发消息、创建任务、下单等),可能产生重复副作用。并发调用同时发现旧 session 失效时,当前 _reconnect_lock 只能串行执行重连;第二个等待者进入锁后仍可能再次重连,因为没有比较“自己失败时看到的 session 是否仍是当前 session”。

建议修改

  1. 在 mcp_client.py 中只把明确的会话/传输失效归类为可重连,例如检查 McpError 的结构化错误码/消息确实表示 session terminated;普通 MCP 业务错误原样返回,不重连、不重放。
  2. 将“恢复连接”和“是否自动重放工具”拆开:
    • 捕获失效时始终可以 best-effort 恢复连接,保证下一次调用可用;
    • 只有工具明确标记为只读/幂等时才自动重放。可由 MCPTool.call() 根据 self.mcp_tool.annotations.readOnlyHint(兼容 annotations 缺失)传入 allow_replay;
    • 对非只读工具,返回“连接已恢复,但本次执行结果不确定,请确认后重试”的明确错误,避免重复副作用。
  3. 重连方法接收失败时捕获的 failed_session(或 generation)。进入锁后若 self.session is not failed_session,说明其他调用已完成重连,应直接复用新 session。
  4. 外层 _execute_local() 超时时,在取消完成后通知 MCP client 废弃/重连该 session,但不要自动重放这次工具;否则超时路径仍会留下不可用连接。

伪代码思路:

failed_session = self.session
try:
    return await failed_session.call_tool(...)
except SessionTerminated:
    await self._reconnect_if_current(failed_session)
    if not allow_replay:
        raise ToolOutcomeUnknown(...)
    return await self.session.call_tool(...)

修改后的效果

只读查询遇到真正的 session terminated 时可自动恢复;有副作用的工具不会因超时或断线被悄悄执行两次;多个并发调用只会为同一代失效 session 建立一次新连接。普通服务端参数/业务错误也不会被误判为连接故障。

建议测试

  • McpError("Session terminated") + 只读工具:重连一次、重放一次并成功。
  • 同样错误 + 非只读/annotations 缺失:重连但不重放,返回结果不确定错误。
  • 普通 McpError:不重连、不重试。
  • 外层 tool_call_timeout:取消旧调用、恢复后续调用,但本次不重放。
  • 两个并发调用共享同一失效 session:断言只创建一个新连接,两者不会依次把新连接再次关闭。
  • 重连失败时保留原始异常为 cause,且 cleanup 后没有遗留 connection task。

LIghtJUNction avatar Sep 23 '26 07:09 LIghtJUNction