fix(runtime): avoid RuntimeError when calling get_tool_specs with MCP tools from running event loop

Đang mở Phù hợp với người mới
#709 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

Chưa có ai nhận issue này.

Đánh giá

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

Hướng nghiên cứu

Bắt đầu từ runtime/node/agent/tool/tool_manager.py, nơi có hai lệnh gọi asyncio.run() gần dòng 198-204 (việc lấy MCP qua HTTP) và dòng 227 (việc lấy MCP qua stdio), được gọi tới từ get_tool_specs. Tái hiện lỗi bằng ví dụ tối giản trong issue, gọi get_tool_specs từ bên trong một hàm async. Hoàn thành khi lệnh gọi đó trả về đặc tả công cụ MCP mà không có RuntimeError, cả khi chạy bên ngoài lẫn bên trong một event loop đang chạy.

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

Mô tả

Summary & Context

In runtime/node/agent/tool/tool_manager.py, ToolManager.get_tool_specs() provides synchronous tool specification discovery for agent nodes (runtime/node/executor/agent_executor.py:77).

When configuring MCP tools (mcp_remote or mcp_local), _build_mcp_remote_specs() and _build_mcp_local_specs() invoke asyncio.run() to execute coroutines synchronously:

# Lines 198-204:
tools = asyncio.run(
    self._fetch_mcp_tools_http(
        config.server,
        headers=config.headers,
        timeout=config.timeout,
    )
)

# Line 227:
tools = asyncio.run(self._fetch_mcp_tools_stdio(config, launch_key))
Problem & Impact

When an agent node with MCP tools is executed inside an asynchronous environment—such as FastAPI routes (server/routes/websocket.py, server/routes/execute.py), an async workflow executor, or an async test—an asyncio event loop is already active in the current thread.

Calling asyncio.run() while an event loop is active immediately raises:

RuntimeError: asyncio.run() cannot be called from a running event loop

This crashes the node execution and prevents MCP tools from being fetched or registered.

Minimal Reproducible Example
import asyncio
from runtime.node.agent.tool.tool_manager import ToolManager
from entity.configs.node.tooling import McpRemoteConfig, ToolingConfig

tool_manager = ToolManager()
mcp_cfg = ToolingConfig(
    type="mcp_remote",
    config=McpRemoteConfig(server="http://localhost:8000/sse", path="node.tooling.mcp_remote"),
    path="node.tooling"
)

# Inside any async function (e.g. FastAPI endpoint or async runner):
async def run_step():
    # Calling get_tool_specs invokes asyncio.run() internally:
    return tool_manager.get_tool_specs([mcp_cfg])

asyncio.run(run_step())
# Result: RuntimeError: asyncio.run() cannot be called from a running event loop
Proposed Fix

Implement a thread-safe coroutine runner helper that detects if an event loop is already active in the current thread. If an event loop is running, delegate the coroutine execution to a worker thread via concurrent.futures.ThreadPoolExecutor to avoid RuntimeError:

import concurrent.futures

def _run_sync(coro):
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = None

    if loop is not None and loop.is_running():
        with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
            return pool.submit(asyncio.run, coro).result()
    return asyncio.run(coro)

And update lines 198 and 227 in tool_manager.py to use _run_sync(...).

Empirical Verification

Tested with local reproduction script:

  • Gate 1 (Outside event loop): Tools retrieved synchronously with 100% success.
  • Gate 2 (Inside running event loop): Successfully executes coroutine in worker thread and returns tool specs without raising RuntimeError.
Ngôn ngữ chính
Python
Star
34.7k
Fork
4.3k
Merge trung bình
3 giờ 23 phút
Pull request đã merge (30 ngày)
3

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

  • Có Dockerfile hoặc tệp Docker Compose
  • Không có mẫu pull request
  • Không có hướng dẫn đóng góp

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 OpenBMB/ChatDev

Tất cả issue của OpenBMB/ChatDev

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.