Skip to content

Commit 2cfe428

Browse files
committed
fix: prevent initialized MCP clients from being cleaned up on timeout
- Do not cancel pending tasks on timeout; let them continue running in the background waiting for the termination signal (event.set()), so successfully initialized services remain available - Track initialization state with a flag to distinguish init failures from post-init cancellations in _init_mcp_client_task_wrapper
1 parent 4924739 commit 2cfe428

1 file changed

Lines changed: 7 additions & 7 deletions

File tree

astrbot/core/provider/func_tool_manager.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -234,8 +234,6 @@ async def init_mcp_clients(self) -> None:
234234
"MCP 服务初始化超时(20秒),部分服务可能未完全加载。"
235235
"建议检查 MCP 服务器配置和网络连接。"
236236
)
237-
for task in pending:
238-
task.cancel()
239237

240238
success_count = 0
241239
failed_services: list[str] = []
@@ -277,17 +275,19 @@ async def _init_mcp_client_task_wrapper(
277275
event: asyncio.Event,
278276
) -> None:
279277
"""初始化 MCP 客户端的包装函数,用于捕获异常"""
278+
initialized = False
280279
try:
281280
await self._init_mcp_client(name, cfg)
282-
tools = await self.mcp_client_dict[name].list_tools_and_save()
283-
logger.debug(f"MCP 服务 {name} 初始化完成,工具: {tools}")
281+
initialized = True
284282
await event.wait()
285283
logger.info(f"收到 MCP 客户端 {name} 终止信号")
286284
except Exception:
287-
logger.error(f"初始化 MCP 客户端 {name} 失败", exc_info=True)
288-
raise
285+
if not initialized:
286+
# 初始化阶段失败,记录错误并向上抛出让 task.exception() 捕获
287+
logger.error(f"初始化 MCP 客户端 {name} 失败", exc_info=True)
288+
raise
289+
# 初始化已成功,此处异常来自 event.wait() 被取消,属于正常终止流程
289290
finally:
290-
# 无论如何都能清理
291291
await self._terminate_mcp_client(name)
292292

293293
async def _init_mcp_client(self, name: str, config: dict) -> None:

0 commit comments

Comments
 (0)