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

Đang mở
#9,846 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

@iridite đang làm issue này rồi.

Từ ngày 27/11/2026.

  • #9845 của @iridite — đã đóng, không merge
  • #9847 của @iridite — đang mở

Đánh giá

Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức phù hợp với người mới
35/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Đình trệ
Công nghệ
python
Lĩnh vực
ai, backend

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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).

Ngôn ngữ chính
Python
Star
61.2k
Fork
9.2k
Merge trung bình
1 ngày 14 giờ
Pull request đã merge (30 ngày)
180

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của crewAIInc/crewAI

Tất cả issue của crewAIInc/crewAI

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.