agent-zero icon indicating copy to clipboard operation
agent-zero copied to clipboard

MCP client initialization fails silently when called from DeferredTask async context (asyncio.run() inside running event loop)

Open stoeff99 opened this issue 8 months ago • 2 comments

Bug Description

MCP servers consistently fail to initialize in Agent Zero — 0 tools are loaded and the MCP server appears broken — despite the server being reachable and credentials being valid.

Root Cause

The bug is in python/helpers/mcp_handler.py in MCPConfig.__init__(). The server initialization block calls asyncio.run(_init_all()) but this is invoked from within an already-running async event loop (DeferredTask's EventLoopThread), causing a silent RuntimeError.

Call Chain

initialize_mcp_async in initialize.py is an async coroutine running on DeferredTask's persistent EventLoopThread. When it calls the synchronous _initialize_mcp(), which eventually calls asyncio.run(), Python raises:

This error is silently caught in update_tools(), which sets self.tools = [] — so the MCP server appears to connect but has no tools.

Reproduction

import asyncio

async def simulate():
    def sync_that_calls_asyncio_run():
        async def inner(): pass
        asyncio.run(inner())  # Raises RuntimeError
    sync_that_calls_asyncio_run()

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

Fix

In python/helpers/mcp_handler.py, replace asyncio.run(_init_all()) with:


# asyncio.run() fails if called from within a running event loop
# (e.g. when MCPConfig.__init__ is called from an async DeferredTask).
_running_loop = None
try:
    _running_loop = asyncio.get_running_loop()
except RuntimeError:
    pass  # No running loop - safe to use asyncio.run()

if _running_loop is not None:
    _exc: list[BaseException] = []
    def _run_in_new_loop():
        _new_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(_new_loop)
        try:
            _new_loop.run_until_complete(_init_all())
        except Exception as _e:
            _exc.append(_e)
        finally:
            _new_loop.close()
    _t = threading.Thread(target=_run_in_new_loop, daemon=True, name="mcp-init")
    _t.start()
    _t.join()
    if _exc:
        raise _exc[0]
else:
    asyncio.run(_init_all())

Environment

Agent Zero version: v0.9.8.2 Python: 3.12.4 MCP SDK: 1.22.0 Platform: Docker container

Impact

All MCP servers silently fail to initialize on startup. This affects all users who configure MCP servers, since initialize_mcp() always uses DeferredTask.

stoeff99 avatar Mar 12 '26 19:03 stoeff99

When u say "despite the server working" do you mean the docker server or the mcp server? Are you connecting locally? And are you using traefik or some other docker network? If using traefik try adding in docker_compose.yml or .env file) Like this exposes web --entrypoints.web.address=:80" maybe "--entrypoints.mcp.adress=:80" I might be dumb here, and that this is not the correct way to open it, but if not u should find it easily..

But i would recommend using traefik either way for networking, for your docker instances.. Gives u a hole lot more control, and u dont need to use ports if you want, you can just use subdomains ( Like test.localhost, or test.yourhostname if it is accessible to the web)

I havent tried using a0 as a mcp server yet, but i imagine it needs to be exposed to the web at least.. Can u tell a bit more about your setup? (or just ask agent0, lol ) :D

DoThatKarma avatar Mar 26 '26 17:03 DoThatKarma

Closing due to inactivity of 90 days.

github-actions[bot] avatar Jun 25 '26 04:06 github-actions[bot]