adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

A problem in "adk web" when running agent with mcp tools : RuntimeError: error getting root agent

Open YangZH1997 opened this issue 1 year ago • 12 comments

I built an agent containing the mcp tools by referring to the example in the document, but a bug occurred when running it with adk web: RuntimeError: error getting root agent. //////////////////////////////////////////////////////////////////////////////////////////////////////////////// Operation Environment: Windows 11 24H2 64bit Python version 3.13.2 google-adk version 0.3.0

aiohappyeyeballs 2.6.1 aiohttp 3.11.18 aiosignal 1.3.2 annotated-types 0.7.0 anyio 4.9.0 attrs 25.3.0 authlib 1.5.2 cachetools 5.5.2 certifi 2025.1.31 cffi 1.17.1 charset-normalizer 3.4.1 click 8.1.8 colorama 0.4.6 cryptography 44.0.2 deprecated 1.2.18 distro 1.9.0 docstring-parser 0.16 fastapi 0.115.12 filelock 3.18.0 frozenlist 1.6.0 fsspec 2025.3.2 google-adk 0.3.0 google-api-core 2.24.2 google-api-python-client 2.168.0 google-auth 2.39.0 google-auth-httplib2 0.2.0 google-cloud-aiplatform 1.90.0 google-cloud-bigquery 3.31.0 google-cloud-core 2.4.3 google-cloud-resource-manager 1.14.2 google-cloud-secret-manager 2.23.3 google-cloud-speech 2.32.0 google-cloud-storage 2.19.0 google-cloud-trace 1.16.1 google-crc32c 1.7.1 google-genai 1.12.1 google-resumable-media 2.7.2 googleapis-common-protos 1.70.0 graphviz 0.20.3 greenlet 3.2.1 grpc-google-iam-v1 0.14.2 grpcio 1.71.0 grpcio-status 1.71.0 h11 0.16.0 httpcore 1.0.9 httplib2 0.22.0 httpx 0.28.1 httpx-sse 0.4.0 huggingface-hub 0.30.2 idna 3.10 importlib-metadata 8.6.1 jinja2 3.1.6 jiter 0.9.0 jsonschema 4.23.0 jsonschema-specifications 2024.10.1 litellm 1.67.0.post1 markupsafe 3.0.2 mcp 1.6.0 multidict 6.4.3 numpy 2.2.5 openai 1.75.0 opentelemetry-api 1.32.1 opentelemetry-exporter-gcp-trace 1.9.0 opentelemetry-resourcedetector-gcp 1.9.0a0 opentelemetry-sdk 1.32.1 opentelemetry-semantic-conventions 0.53b1 packaging 25.0 propcache 0.3.1 proto-plus 1.26.1 protobuf 5.29.4 pyasn1 0.6.1 pyasn1-modules 0.4.2 pycparser 2.22 pydantic 2.11.3 pydantic-core 2.33.1 pydantic-settings 2.9.1 pyparsing 3.2.3 python-dateutil 2.9.0.post0 python-dotenv 1.1.0 pyyaml 6.0.2 referencing 0.36.2 regex 2024.11.6 requests 2.32.3 rpds-py 0.24.0 rsa 4.9.1 shapely 2.1.0 six 1.17.0 sniffio 1.3.1 sqlalchemy 2.0.40 sse-starlette 2.3.3 starlette 0.46.2 tiktoken 0.9.0 tokenizers 0.21.1 tqdm 4.67.1 typing-extensions 4.13.2 typing-inspection 0.4.0 tzdata 2025.2 tzlocal 5.3.1 uritemplate 4.1.1 urllib3 2.4.0 uvicorn 0.34.2 websockets 15.0.1 wrapt 1.17.2 yarl 1.20.0 zipp 3.21.0

The detailed code is as follows: //////////////////////////////////////////////////////////////////////////////////////////////////////////////// init.py:

from . import agent

//////////////////////////////////////////////////////////////////////////////////////////////////////////////// agent.py:

import os
from dotenv import load_dotenv
from google.adk.models.lite_llm import LiteLlm
from google.adk.agents.llm_agent import LlmAgent
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, SseServerParams, StdioServerParameters

load_dotenv()

async def get_tools_async():
  """Gets tools from the File System MCP Server."""
  print("Attempting to connect to MCP Filesystem server...")
  tools, exit_stack = await MCPToolset.from_server(
      # Use StdioServerParameters for local process communication
      connection_params=StdioServerParameters(
          command='npx.cmd', 
          args=["-y",   
                "@modelcontextprotocol/server-filesystem",
                "E:/sandbox"],
      )
  )
  print("MCP Toolset created successfully.")
  # MCP requires maintaining a connection to the local MCP Server.
  # exit_stack manages the cleanup of this connection.
  return tools, exit_stack

# LiteLLM uses different ENV variables for OpenAI and OpenTelemetry fields.
os.environ["OPENAI_API_BASE"] = os.getenv("SILI_BASE_URL")  
os.environ["OPENAI_API_KEY"] = os.getenv("SILI_API_KEY")

async def create_agent():
  """Gets tools from MCP Server."""
  tools, exit_stack = await get_tools_async()
  
  agent = LlmAgent(
      model=LiteLlm(model="openai/Pro/deepseek-ai/DeepSeek-V3-1226"), 
      name='filesystem_assistant',
      instruction='Help user interact with the local filesystem using available tools.',
      tools=tools, # Provide the MCP tools to the ADK agent
  )
  return agent, exit_stack

root_agent = create_agent()

//////////////////////////////////////////////////////////////////////////////////////////////////////////////// Error information:

2025-04-25 11:37:54,069 - INFO - _client.py:1025 - HTTP Request: GET https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json "HTTP/1.1 200 OK" Attempting to connect to MCP Filesystem server... 2025-04-25 11:37:56,002 - ERROR - fast_api.py:637 - Error in event_generator: error getting root agent, Traceback (most recent call last): File "E:\uv_venv2\google_ai.venv\Lib\site-packages\mcp\client\stdio\win32.py", line 72, in create_windows_process process = await anyio.open_process( ^^^^^^^^^^^^^^^^^^^^^^^^^ ...<8 lines>... ) ^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\anyio_core_subprocesses.py", line 190, in open_process return await get_async_backend().open_process( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<11 lines>... ) ^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\anyio_backends_asyncio.py", line 2561, in open_process process = await asyncio.create_subprocess_exec( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<5 lines>... ) ^ File "E:\Application11\Python\Python313\Lib\asyncio\subprocess.py", line 224, in create_subprocess_exec transport, protocol = await loop.subprocess_exec( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<3 lines>... stderr=stderr, **kwds) ^^^^^^^^^^^^^^^^^^^^^^ File "E:\Application11\Python\Python313\Lib\asyncio\base_events.py", line 1794, in subprocess_exec transport = await self._make_subprocess_transport( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ protocol, popen_args, False, stdin, stdout, stderr, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ bufsize, **kwargs) ^^^^^^^^^^^^^^^^^^ File "E:\Application11\Python\Python313\Lib\asyncio\base_events.py", line 539, in _make_subprocess_transport raise NotImplementedError NotImplementedError

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "E:\uv_venv2\google_ai.venv\Lib\site-packages\google\adk\cli\fast_api.py", line 782, in _get_root_agent_async agent, exit_stack = await root_agent ^^^^^^^^^^^^^^^^ File "E:\uv_venv2\google_ai\multi_tool_agent\filesystem_agent\agent.py", line 41, in create_agent tools, exit_stack = await get_tools_async() ^^^^^^^^^^^^^^^^^^^^^^^ File "E:\uv_venv2\google_ai\multi_tool_agent\filesystem_agent\agent.py", line 18, in get_tools_async tools, exit_stack = await MCPToolset.from_server( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<10 lines>... ) ^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\google\adk\tools\mcp_tool\mcp_toolset.py", line 223, in from_server await async_exit_stack.enter_async_context(toolset) File "E:\Application11\Python\Python313\Lib\contextlib.py", line 668, in enter_async_context result = await _enter(cm) ^^^^^^^^^^^^^^^^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\google\adk\tools\mcp_tool\mcp_toolset.py", line 258, in aenter raise e File "E:\uv_venv2\google_ai.venv\Lib\site-packages\google\adk\tools\mcp_tool\mcp_toolset.py", line 255, in aenter await self._initialize() File "E:\uv_venv2\google_ai.venv\Lib\site-packages\google\adk\tools\mcp_tool\mcp_toolset.py", line 229, in _initialize self.session = await self.session_manager.create_session() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\google\adk\tools\mcp_tool\mcp_session_manager.py", line 132, in create_session return await MCPSessionManager.initialize_session( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<3 lines>... ) ^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\google\adk\tools\mcp_tool\mcp_session_manager.py", line 173, in initialize_session transports = await exit_stack.enter_async_context(client) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\Application11\Python\Python313\Lib\contextlib.py", line 668, in enter_async_context result = await enter(cm) ^^^^^^^^^^^^^^^^ File "E:\Application11\Python\Python313\Lib\contextlib.py", line 214, in aenter return await anext(self.gen) ^^^^^^^^^^^^^^^^^^^^^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\mcp\client\stdio_init.py", line 113, in stdio_client process = await create_platform_compatible_process( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<9 lines>... ) ^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\mcp\client\stdio_init.py", line 210, in _create_platform_compatible_process process = await create_windows_process(command, args, env, errlog, cwd) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\mcp\client\stdio\win32.py", line 85, in create_windows_process process = await anyio.open_process( ^^^^^^^^^^^^^^^^^^^^^^^^^ [command, *args], env=env, stderr=errlog, cwd=cwd ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\anyio_core_subprocesses.py", line 190, in open_process return await get_async_backend().open_process( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<11 lines>... ) ^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\anyio_backends_asyncio.py", line 2561, in open_process process = await asyncio.create_subprocess_exec( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<5 lines>... ) ^ File "E:\Application11\Python\Python313\Lib\asyncio\subprocess.py", line 224, in create_subprocess_exec transport, protocol = await loop.subprocess_exec( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...<3 lines>... stderr=stderr, **kwds) ^^^^^^^^^^^^^^^^^^^^^^ File "E:\Application11\Python\Python313\Lib\asyncio\base_events.py", line 1794, in subprocess_exec transport = await self._make_subprocess_transport( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ protocol, popen_args, False, stdin, stdout, stderr, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ bufsize, **kwargs) ^^^^^^^^^^^^^^^^^^ File "E:\Application11\Python\Python313\Lib\asyncio\base_events.py", line 539, in _make_subprocess_transport raise NotImplementedError NotImplementedError

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "E:\uv_venv2\google_ai.venv\Lib\site-packages\google\adk\cli\fast_api.py", line 625, in event_generator runner = await _get_runner_async(req.app_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\google\adk\cli\fast_api.py", line 796, in _get_runner_async root_agent = await _get_root_agent_async(app_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\uv_venv2\google_ai.venv\Lib\site-packages\google\adk\cli\fast_api.py", line 786, in _get_root_agent_async raise RuntimeError(f"error getting root agent, {e}") from e RuntimeError: error getting root agent,

YangZH1997 avatar Apr 25 '25 07:04 YangZH1997

I have exactly the same isue, 0.2.0 release and setting up like the tutorial (albeit with my mcp server). I read elsewhere could be timeout.

satyaloka93 avatar Apr 25 '25 11:04 satyaloka93

I think you need 0.3.0 to make it work, could you try?

boyangsvl avatar Apr 25 '25 23:04 boyangsvl

I'm using the latest 0.3.0, and the problem is occurring on that version. My Operation Environment: Windows 11 24H2 64bit Python version 3.13.2 google-adk version 0.3.0

YangZH1997 avatar Apr 26 '25 01:04 YangZH1997

I've looked into some resources and think it might be a conflict between the Windows platform and FastAPI's reload feature. Here are my observations that might help with bug fixing:

After Python 3.8, on Windows platforms, the default event loop ProactorEventLoop supports subprocesses, while SelectorEventLoop does not. However, when uvicorn starts with reload enabled, it forces the default event loop to be SelectorEventLoop. Therefore, if "adk web" has "reload" enabled, it might encounter subprocess-related errors on Windows platforms. The error message includes "File 'D:\Applications\Python\Python313\Lib\asyncio\base_events.py', line 539, in _make_subprocess_transport raise NotImplementedError". This leads me to believe the issue might be related to FastAPI's reload functionality.

Here are some relevant references:

https://docs.python.org/3.13/library/asyncio-platforms.html#windows https://github.com/fastapi/fastapi/issues/4361

Hope it helps!

YangZH1997 avatar Apr 26 '25 03:04 YangZH1997

I think MCPToolset.from_server() is async, we have no way to do

root_agent = create_agent()

because you have to await it,

root_agent = await create_agent()

but we cannot simply do it here, because we can only do it in async function, so this is a dilemma, and we need sync version of MCPToolset.from_server() in order to use adk web to test it

hkbb2014 avatar Apr 27 '25 08:04 hkbb2014

I am also facing the same issue and the main error message is:

Input should be a valid dictionary or instance of BaseAgent [type=model_type, input_value=<coroutine object get_agent at 0x144fab440>, input_type=coroutine]

Here root_agent is expected to be BaseAgent, but since we are not awaiting root_agent = create_agent() it is returning as coroutine.

Shrijeeth avatar Apr 27 '25 08:04 Shrijeeth

Tried changing reload to false in the cli_tools_click.py . While it doesn't throw error after this, it simply gets stuck at tool initialization. tools, exit_stack = await MCPToolset.from_server( # Use StdioServerParameters for local process communication connection_params=StdioServerParameters( command='npx.cmd', args=["-y", "@modelcontextprotocol/server-filesystem", "/path/to/folder"], ) )

Seems similar to #https://github.com/modelcontextprotocol/python-sdk/issues/382

B-SRIKRISHNAN avatar Apr 29 '25 11:04 B-SRIKRISHNAN

Tried changing reload to false in the cli_tools_click.py . While it doesn't throw error after this, it simply gets stuck at tool initialization. tools, exit_stack = await MCPToolset.from_server( # Use StdioServerParameters for local process communication connection_params=StdioServerParameters( command='npx.cmd', args=["-y", "@modelcontextprotocol/server-filesystem", "/path/to/folder"], ) )

Seems similar to #modelcontextprotocol/python-sdk#382

Thank you for your reply! Indeed, after commenting out "reload = True" in cli_tools_click.py, the "adk web" command can now correctly run agents with mcp tools. I hope future versions of adk will add Windows platform detection when configuring the fastapi reload functionality.

YangZH1997 avatar Apr 30 '25 03:04 YangZH1997

Thank you for your reply! Indeed, after commenting out "reload = True" in cli_tools_click.py, the "adk web" command can now correctly run agents with mcp tools. I hope future versions of adk will add Windows platform detection when configuring the fastapi reload functionality.

Thank you :). Yes, it seems that issue is being worked on. by the way, is it connecting to stdio mcp servers?. I find mine just gets stuck at the server tool call without continuing.

B-SRIKRISHNAN avatar Apr 30 '25 10:04 B-SRIKRISHNAN

Thank you for your reply! Indeed, after commenting out "reload = True" in cli_tools_click.py, the "adk web" command can now correctly run agents with mcp tools. I hope future versions of adk will add Windows platform detection when configuring the fastapi reload functionality.

Thank you :). Yes, it seems that issue is being worked on. by the way, is it connecting to stdio mcp servers?. I find mine just gets stuck at the server tool call without continuing.

Yes, it is connecting to studio mcp servers. When testing the mcp server, I sometimes experience it getting stuck, too. There are many possible causes. Here are some of my debugging methods that might help you:

(1) In some cases, specifying only "npx" as the command cannot effectively execute npx instructions. It's recommended to fill in the complete npx path, for example: path\to\npx.cmd. The same applies to uvx and python commands.

(2) You can try using npm install to download the mcp server locally, modify the args to the installed local path, and then call it from the local environment.

(3) Check if the llm you're using supports tool calling, some llms don't have the functionality to call tools.

(4) After ruling out the above factors, the mcp server might be stuck due to server initialization failure or failure to retrieve tools. Here is a script to check if the mcp server can be called normally, which can be used to identify exactly where the problem is occurring in the mcp server. The script is as follows:

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

server_params = StdioServerParameters(
    command="npx.cmd",
    args=[
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "E:/sandbox", 
    ], 
    env=None,
)

async def run():
    # connecting
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # initialization
            await session.initialize()

            # list tools
            tools = await session.list_tools()
            print("Tools:", tools)

            # call tools
            indices = await session.call_tool("list_allowed_directories")
            print("Indices:", indices)

if __name__ == "__main__":
    import asyncio
    asyncio.run(run())

Hope it helps!

YangZH1997 avatar May 02 '25 16:05 YangZH1997

Yes, It is working now. It was not working due to surrounding path with double quotes like "/my_path" 😕. Thank you so much for your help 😀.

B-SRIKRISHNAN avatar May 06 '25 09:05 B-SRIKRISHNAN

it's fixed in latest wheel. Please retry. Closing the ticket and feel free to re-open if you still see the issues.

hangfei avatar May 31 '25 18:05 hangfei