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

オープン
#9,846 コメント 0 件 リアクション 0 件 担当者 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時間
マージ済み PR(30日)
180

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

crewAIInc/crewAI のほかの issue

crewAIInc/crewAI の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。