[BUG] MCPToolResolver cleanup, failure disconnect, and external schema discovery fail inside running asyncio event loops
维护者通常 1 天内回复
评估
调研方向
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:
MCPToolResolver.cleanup()callsasyncio.run(_disconnect_all())directly. Inside an active event loop (e.g.,akickoff(), async Flows, async web services, orpytest-asyncio),asyncio.run()raisesRuntimeError: asyncio.run() cannot be called from a running event loop.cleanup()catches theRuntimeError, logs it, clearsself._clients, and leaves connected MCP clients undisconnected. Additionally,_disconnect_all()iteratesself._clientswithout per-client error isolation, so an exception on an earlier client skips disconnecting remaining clients.MCPToolResolver._get_mcp_tool_schemas()callsasyncio.run(self._get_mcp_tool_schemas_async(server_params))directly. When resolving HTTPS MCP server URLs (resolve(["https://..."])) inside a running loop,asyncio.run()hitsRuntimeError, is caught byexcept Exception, logs a warning, and silently returns{}(zero tools discovered).MCPToolResolver._resolve_native()exception unwinding (except Exception as e: if discovery_client.connected:) callsasyncio.run(discovery_client.disconnect())directly when a failure occurs after discovery whilediscovery_client.connectedis stillTrue.
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 logsRuntimeError: asyncio.run() cannot be called from a running event loopand awaitsdisconnect()0 times._get_mcp_tool_schemas()inside an active loop logs theRuntimeErrorwarning 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
环境准备
- 没有 Dockerfile 或 Docker Compose 文件
- 有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
crewAIInc/crewAI 的其他 Issue
-
难度 2/5 1-3 小时 新手友好度 76/100
维护者通常 1 天内回复
-
[FEATURE] Add Straitly as a native OpenAI-compatible LLM provider可能已有人在做 @HashimSyedUBC 于 2 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 78/100
维护者通常 1 天内回复
-
[BUG] Native OpenAI sync streaming with response_model returns an empty string and emits no completed event when the parse is missing可能已有人在做 @basil-k-aji-dev 于 3 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 82/100
维护者通常 1 天内回复
-
[BUG] Native Azure provider ignores the seed setting可能已有人在做 @basil-k-aji-dev 于 3 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 82/100
crewAIInc/crewAI#9787 · 1 条评论 ·
维护者通常 1 天内回复
-
[BUG] LiteLLM path reports 0 cached and reasoning tokens in the usage summary可能已有人在做 @basil-k-aji-dev 于 3 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 78/100
维护者通常 1 天内回复
相似的 Issue
-
bug harness
难度 2/5 1-3 小时 新手友好度 72/100
mruangutai/harness#2687 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 68/100
modal-labs/modal-client#4158 ·
-
good first issue
难度 1/5 1 小时以内 新手友好度 72/100
维护者通常 1 天内回复
-
难度 2/5 半天 新手友好度 72/100
The-Swarm-Corporation/swarms-rs#168 ·
维护者通常 1 天内回复
-
[BUG] SMTP listener now binds to EMAIL_PORT instead of 2525 since the gunicorn switch 5.0.3-ls373未关闭
难度 2/5 1-3 小时 新手友好度 72/100
linuxserver/docker-healthchecks#137 · 1 条评论 ·