[BUG] MCPToolResolver cleanup, failure disconnect, and external schema discovery fail inside running asyncio event loops

未关闭
#9,846 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

@iridite 已经在做这个了。

开始于 2026年11月27日。

  • #9845 来自 @iridite —— 已关闭,未合并
  • #9847 来自 @iridite —— 未关闭

评估

难度
3/5
预计耗时
1-2 天
新手友好度
35/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
停滞
技术栈
python
领域
ai, backend

调研方向

Start with lib/crewai/src/crewai/mcp/tool_resolver.py and trace _resolve_native(), cleanup(), and _get_mcp_tool_schemas() alongside the existing event loop bridge. Reproduce the failures inside a running asyncio loop, including a client whose disconnect raises. Done when all three paths work in that context and cleanup attempts each client; the issue links open pull request #9847.

由索引模型根据 Issue 内容生成。

描述

Description

MCPToolResolver._resolve_native() checks asyncio.get_running_loop() and bridges execution through a ThreadPoolExecutor + contextvars.copy_context() when called from an active asyncio event loop. However, three other call sites in MCPToolResolver (lib/crewai/src/crewai/mcp/tool_resolver.py) still invoke asyncio.run(...) directly:

  1. MCPToolResolver.cleanup() calls asyncio.run(_disconnect_all()) directly. Inside an active event loop (e.g., akickoff(), async Flows, async web services, or pytest-asyncio), asyncio.run() raises RuntimeError: asyncio.run() cannot be called from a running event loop. cleanup() catches the RuntimeError, logs it, clears self._clients, and leaves connected MCP clients undisconnected. Additionally, _disconnect_all() iterates self._clients without per-client error isolation, so an exception on an earlier client skips disconnecting remaining clients.
  2. MCPToolResolver._get_mcp_tool_schemas() calls asyncio.run(self._get_mcp_tool_schemas_async(server_params)) directly. When resolving HTTPS MCP server URLs (resolve(["https://..."])) inside a running loop, asyncio.run() hits RuntimeError, is caught by except Exception, logs a warning, and silently returns {} (zero tools discovered).
  3. MCPToolResolver._resolve_native() exception unwinding (except Exception as e: if discovery_client.connected:) calls asyncio.run(discovery_client.disconnect()) directly when a failure occurs after discovery while discovery_client.connected is still True.
Steps to Reproduce
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
from crewai.agent.core import Agent
from crewai.mcp.tool_resolver import MCPToolResolver

async def main() -> None:
    agent = Agent(role="Test", goal="Test", backstory="Test")
    resolver = MCPToolResolver(agent=agent, logger=agent._logger)

    client = MagicMock()
    client.connected = True
    client.disconnect = AsyncMock()
    resolver._clients.append(client)

    resolver.cleanup()
    print("disconnected calls:", client.disconnect.await_count)  # Prints 0 instead of 1

    with patch.object(
        resolver,
        "_get_mcp_tool_schemas_async",
        new=AsyncMock(return_value={"search": {"description": "Search", "args_schema": None}}),
    ):
        print("schemas:", resolver._get_mcp_tool_schemas({"url": "https://mcp.example.com/api"}))
        # Prints {} instead of {"search": ...}

asyncio.run(main())
Expected behavior

cleanup(), _get_mcp_tool_schemas(), and _resolve_native() failure cleanup should work safely when called inside an already-running asyncio event loop (via the same ThreadPoolExecutor + contextvars.copy_context() bridge already used for native discovery), and cleanup() should attempt disconnecting every client even if one client raises.

Screenshots/Code snippets

See minimal reproduction script above.

Operating System

macOS Sonoma

Python Version

3.12

crewAI Version

1.15.45

crewAI Tools Version

N/A

Virtual Environment

Venv

Evidence

Reproduced locally on main (77237ae):

  • cleanup() inside an active loop logs RuntimeError: asyncio.run() cannot be called from a running event loop and awaits disconnect() 0 times.
  • _get_mcp_tool_schemas() inside an active loop logs the RuntimeError warning and returns {}.
Possible Solution

Extract a shared _run_async helper on MCPToolResolver that delegates to asyncio.run() inside a ThreadPoolExecutor with copied contextvars whenever an event loop is already running, use it across cleanup(), _resolve_native(), and _get_mcp_tool_schemas(), and wrap per-client disconnect() inside cleanup() with individual try/except.

Additional context

Note: AI-assisted diagnosis and regression test verification (labeled llm-generated per CONTRIBUTING.md).

主要语言
Python
星标
61.2k
派生
9.2k
平均合并
1 天 14 小时
30 天内合并 PR
180

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

crewAIInc/crewAI 的其他 Issue

查看 crewAIInc/crewAI 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。