[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時間
- マージ済み PR(30日)
- 180
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- 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 が 2 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
メンテナーはふだん 1 日以内に返信
-
[BUG] Native Azure provider ignores the seed setting対応中かも @basil-k-aji-dev が 2 日前に担当しました。 オープン
難易度 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 が 2 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
crewAIInc/crewAI の issue をすべて見る
似ている 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 件 ·