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

How to write agent code for multiple MCP calls? When starting the project with "adk web", it can use MCP normally

Open ITMeow opened this issue 1 year ago • 18 comments

How to write agent code for multiple MCP calls? When starting the project with "adk web", it can use MCP normally

ITMeow avatar Apr 17 '25 02:04 ITMeow

Please check out this documentation: https://google.github.io/adk-docs/tools/mcp-tools/.

hangfei avatar Apr 17 '25 04:04 hangfei

Similar error for me. How to normally use MCP when starting a project with "adk web"

ayu-asd avatar Apr 17 '25 09:04 ayu-asd

I have the same question. In both documentation examples, the agents are executed via command line to ensure the necessary asynchrony during the loading of MCP tools. Is there a way to test agents that use MCP tools through the 'adk web'? That approach is very useful in the development process.

bravoy93 avatar Apr 18 '25 20:04 bravoy93

+1

con-fucius avatar Apr 19 '25 23:04 con-fucius

We just updated our documentation to talk about adk web + mcp here: https://google.github.io/adk-docs/tools/mcp-tools/#mcp-with-adk-web

This is only supported in latest ADK.

hangfei avatar Apr 19 '25 23:04 hangfei

I just use the sample code completely same with documentation, then notice me these error:

2025-04-21 13:37:20,137 - ERROR - fast_api.py:616 - Error in event_generator: 1 validation error for InvocationContext agent Input should be a valid dictionary or instance of BaseAgent [type=model_type, input_value=<coroutine object create_agent at 0x1489b96c0>, input_type=coroutine] For further information visit https://errors.pydantic.dev/2.11/v/model_type Traceback (most recent call last): File "/Users/summerkiwa/Codes/ec_9_adk/.venv/lib/python3.12/site-packages/google/adk/cli/fast_api.py", line 605, in event_generator async for event in runner.run_async( File "/Users/summerkiwa/Codes/ec_9_adk/.venv/lib/python3.12/site-packages/google/adk/runners.py", line 181, in run_async invocation_context = self._new_invocation_context( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/summerkiwa/Codes/ec_9_adk/.venv/lib/python3.12/site-packages/google/adk/runners.py", line 397, in _new_invocation_context return InvocationContext( ^^^^^^^^^^^^^^^^^^ File "/Users/summerkiwa/Codes/ec_9_adk/.venv/lib/python3.12/site-packages/pydantic/main.py", line 253, in init validated_self = self.pydantic_validator.validate_python(data, self_instance=self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pydantic_core._pydantic_core.ValidationError: 1 validation error for InvocationContext agent Input should be a valid dictionary or instance of BaseAgent [type=model_type, input_value=<coroutine object create_agent at 0x1489b96c0>, input_type=coroutine] For further information visit https://errors.pydantic.dev/2.11/v/model_type

We just updated our documentation to talk about adk web + mcp here: https://google.github.io/adk-docs/tools/mcp-tools/#mcp-with-adk-web

summerkiwa avatar Apr 21 '25 05:04 summerkiwa

Please install latest ADK

hangfei avatar Apr 21 '25 05:04 hangfei

Please install latest ADK

Using the latest ADK still doesn't work

from google.adk.agents import LlmAgent
from google.adk.models.lite_llm import LiteLlm
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters

from app.core.config import MODEL


async def get_tools_async():
    tools, exit_stack = await MCPToolset.from_server(
        connection_params=StdioServerParameters(
            command=r'python',
            args=[r"C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\mcp_agent\mcp\data_export_mcp.py"],
        )
    )
    return tools, exit_stack


async def create_agent():
    tools, exit_stack = await get_tools_async()

    agent = LlmAgent(
        name="assistant",
        model=LiteLlm(model=MODEL),
        instruction="Help user by using available tools.",
        tools=tools
    )
    return agent, exit_stack


root_agent = create_agent()

The following is a detailed console output:

INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     127.0.0.1:55790 - "GET / HTTP/1.1" 307 Temporary Redirect
INFO:     127.0.0.1:55790 - "GET /list-apps?relative_path=./ HTTP/1.1" 200 OK
2025-04-21 14:29:50,637 - INFO - fast_api.py:313 - New session created
INFO:     127.0.0.1:55789 - "GET /apps/mcp_agent/eval_sets HTTP/1.1" 200 OK
INFO:     127.0.0.1:55790 - "POST /apps/mcp_agent/users/user/sessions HTTP/1.1" 200 OK
INFO:     127.0.0.1:55790 - "GET /apps/mcp_agent/users/user/sessions HTTP/1.1" 200 OK
INFO:     127.0.0.1:55790 - "GET /apps/mcp_agent/users/user/sessions HTTP/1.1" 200 OK
INFO:     127.0.0.1:55790 - "POST /run_sse HTTP/1.1" 200 OK
2025-04-21 14:29:53,879 - INFO - envs.py:47 - Loaded .env file for mcp_agent at C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.env
2025-04-21 14:29:56,525 - 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"
2025-04-21 14:29:59,009 - ERROR - fast_api.py:637 - Error in event_generator: error getting root agent, 
Traceback (most recent call last):
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\mcp\client\stdio\win32.py", line 72, in create_windows_process
    process = await anyio.open_process(
              ^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<8 lines>...
    )
    ^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\anyio\_core\_subprocesses.py", line 190, in open_process
    return await get_async_backend().open_process(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<11 lines>...
    )
    ^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\anyio\_backends\_asyncio.py", line 2561, in open_process
    process = await asyncio.create_subprocess_exec(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<5 lines>...
    )
    ^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\asyncio\subprocess.py", line 224, in create_subprocess_exec
    transport, protocol = await loop.subprocess_exec(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<3 lines>...
        stderr=stderr, **kwds)
        ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 1788, in subprocess_exec
    transport = await self._make_subprocess_transport(
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        protocol, popen_args, False, stdin, stdout, stderr,
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        bufsize, **kwargs)
        ^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 533, in _make_subprocess_transport
    raise NotImplementedError
NotImplementedError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\google\adk\cli\fast_api.py", line 776, in _get_root_agent_async
    agent, exit_stack = await root_agent
                        ^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\mcp_agent\agent.py", line 19, in create_agent
    tools, exit_stack = await get_tools_async()
                        ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\mcp_agent\agent.py", line 9, in get_tools_async
    tools, exit_stack = await MCPToolset.from_server(
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<4 lines>...
    )
    ^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.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 "C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\contextlib.py", line 668, in enter_async_context
    result = await _enter(cm)
             ^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\google\adk\tools\mcp_tool\mcp_toolset.py", line 258, in __aenter__
    raise e
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\google\adk\tools\mcp_tool\mcp_toolset.py", line 255, in __aenter__
    await self._initialize()
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.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 "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.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 "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.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 "C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\contextlib.py", line 668, in enter_async_context
    result = await _enter(cm)
             ^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\contextlib.py", line 214, in __aenter__
    return await anext(self.gen)
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\mcp\client\stdio\__init__.py", line 113, in stdio_client
    process = await _create_platform_compatible_process(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<9 lines>...
    )
    ^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.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 "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.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 "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\anyio\_core\_subprocesses.py", line 190, in open_process
    return await get_async_backend().open_process(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<11 lines>...
    )
    ^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\anyio\_backends\_asyncio.py", line 2561, in open_process
    process = await asyncio.create_subprocess_exec(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<5 lines>...
    )
    ^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\asyncio\subprocess.py", line 224, in create_subprocess_exec
    transport, protocol = await loop.subprocess_exec(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<3 lines>...
        stderr=stderr, **kwds)
        ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 1788, in subprocess_exec
    transport = await self._make_subprocess_transport(
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        protocol, popen_args, False, stdin, stdout, stderr,
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        bufsize, **kwargs)
        ^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 533, in _make_subprocess_transport
    raise NotImplementedError
NotImplementedError

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

Traceback (most recent call last):
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\google\adk\cli\fast_api.py", line 625, in event_generator
    runner = await _get_runner_async(req.app_name)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\google\adk\cli\fast_api.py", line 790, in _get_runner_async
    root_agent = await _get_root_agent_async(app_name)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\.venv\Lib\site-packages\google\adk\cli\fast_api.py", line 780, in _get_root_agent_async
    raise RuntimeError(f"error getting root agent, {e}") from e
RuntimeError: error getting root agent,
INFO:     127.0.0.1:55790 - "GET /apps/mcp_agent/users/user/sessions/c8fff47b-d912-4cf3-9ca6-f6ab7c4f9746 HTTP/1.1" 200 OK

The following is the environment: Operating System: Windows 10,64 bit Python version: 3.13

aiohappyeyeballs 2.6.1 aiohttp 3.11.16 aiosignal 1.3.2 annotated-types 0.7.0 anyio 4.9.0 attrs 25.3.0 Authlib 1.5.2 bcrypt 4.0.1 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.5.0 fsspec 2025.3.2 google-adk 0.2.0 google-api-core 2.24.2 google-api-python-client 2.167.0 google-auth 2.39.0 google-auth-httplib2 0.2.0 google-cloud-aiplatform 1.89.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 3.1.0 google-cloud-trace 1.16.1 google-crc32c 1.7.1 google-genai 1.11.0 google-resumable-media 2.7.2 googleapis-common-protos 1.70.0 graphviz 0.20.3 greenlet 3.2.0 grpc-google-iam-v1 0.14.2 grpcio 1.72.0rc1 grpcio-status 1.71.0 h11 0.14.0 httpcore 1.0.8 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 jwcrypto 1.5.6 litellm 1.67.0 MarkupSafe 3.0.2 mcp 1.6.0 multidict 6.4.3 numpy 2.2.4 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 24.2 passlib 1.7.4 pip 25.0.1 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.8.1 PyJWT 2.10.1 PyMySQL 1.1.1 pyparsing 3.2.3 pysolr 3.10.0 python-dateutil 2.9.0.post0 python-dotenv 1.1.0 python-multipart 0.0.20 PyYAML 6.0.2 referencing 0.36.2 regex 2024.11.6 requests 2.32.3 rpds-py 0.24.0 rsa 4.9 setuptools 79.0.0 shapely 2.1.0 six 1.17.0 sniffio 1.3.1 SQLAlchemy 2.0.40 sse-starlette 2.2.1 starlette 0.46.2 tika 3.1.0 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

sleepMoreEarly avatar Apr 21 '25 06:04 sleepMoreEarly

+1

596192804 avatar Apr 21 '25 06:04 596192804

Please install latest ADK

Thanks! The MCP agent works great now after I upgraded the SDK.

summerkiwa avatar Apr 21 '25 07:04 summerkiwa

I'm facing a similar issue, but I believe Im doing something wrong in the way that im exporting it

@summerkiwa @hangfei Would really appreciate if you could have a look at Issue #304

Thank you in advance!

kanlanc avatar Apr 21 '25 17:04 kanlanc

Please install latest ADK

Thanks! The MCP agent works great now after I upgraded the SDK.

May I ask what your system environment is? Windows or Linux? What is the version of Python?

sleepMoreEarly avatar Apr 22 '25 01:04 sleepMoreEarly

import os

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


# load_dotenv()

# os.environ["OPENAI_API_BASE"] = os.getenv("OPENAI_BASE_URL")
os.environ["OPENAI_API_BASE"] = 'http://192.0.0.15:11434/v1'
# model = "openai/" + os.getenv("CHAT_MODEL")
model = "openai/qwen2.5-14b-q4km:latest"

async def get_tools_async():
    tools, exit_stack = await MCPToolset.from_server(
        connection_params=StdioServerParameters(
            command=r'python',
            args=[r"C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\mcp_agent\mcp\data_export_mcp.py"],
        )
    )
    return tools, exit_stack


async def create_agent():
    tools, exit_stack = await get_tools_async()

    agent = LlmAgent(
        name="assistant",
        model=LiteLlm(model=model),
        instruction="Help user by using available tools.",
        tools=tools
    )
    return agent, exit_stack


root_agent = create_agent()

I tried Python 3.13 and 3.10 on the Windows 10 operating system, reinstalled the latest packages, but it still didn't work

2025-04-22 10:38:56,786 - ERROR - fast_api.py:637 - Error in event_generator: error getting root agent, Traceback (most recent call last): File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\mcp\client\stdio\win32.py", line 72, in create_windows_process process = await anyio.open_process( File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\anyio_core_subprocesses.py", line 190, in open_process return await get_async_backend().open_process( File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\anyio_backends_asyncio.py", line 2561, in open_process process = await asyncio.create_subprocess_exec( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\subprocess.py", line 218, in create_subprocess_exec transport, protocol = await loop.subprocess_exec( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 1681, in subprocess_exec transport = await self._make_subprocess_transport( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 498, in _make_subprocess_transport raise NotImplementedError NotImplementedError

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\cli\fast_api.py", line 776, in _get_root_agent_async agent, exit_stack = await root_agent File "C:\Users\Administrator\PycharmProjects\test\demo_agent\agent.py", line 27, in create_agent tools, exit_stack = await get_tools_async() File "C:\Users\Administrator\PycharmProjects\test\demo_agent\agent.py", line 17, in get_tools_async tools, exit_stack = await MCPToolset.from_server( File "C:\Users\Administrator\PycharmProjects\test.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 "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\contextlib.py", line 619, in enter_async_context result = await _cm_type.aenter(cm) File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\tools\mcp_tool\mcp_toolset.py", line 258, in aenter raise e File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\tools\mcp_tool\mcp_toolset.py", line 255, in aenter await self._initialize() File "C:\Users\Administrator\PycharmProjects\test.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 "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\tools\mcp_tool\mcp_session_manager.py", line 132, in create_session return await MCPSessionManager.initialize_session( File "C:\Users\Administrator\PycharmProjects\test.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 "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\contextlib.py", line 619, in enter_async_context result = await cm_type.aenter(cm) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\contextlib.py", line 199, in aenter return await anext(self.gen) File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\mcp\client\stdio_init.py", line 113, in stdio_client process = await create_platform_compatible_process( File "C:\Users\Administrator\PycharmProjects\test.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 "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\mcp\client\stdio\win32.py", line 85, in create_windows_process process = await anyio.open_process( File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\anyio_core_subprocesses.py", line 190, in open_process return await get_async_backend().open_process( File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\anyio_backends_asyncio.py", line 2561, in open_process process = await asyncio.create_subprocess_exec( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\subprocess.py", line 218, in create_subprocess_exec transport, protocol = await loop.subprocess_exec( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 1681, in subprocess_exec transport = await self._make_subprocess_transport( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 498, in _make_subprocess_transport raise NotImplementedError NotImplementedError

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

Traceback (most recent call last): File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\cli\fast_api.py", line 625, in event_generator runner = await _get_runner_async(req.app_name) File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\cli\fast_api.py", line 790, in _get_runner_async root_agent = await _get_root_agent_async(app_name) File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\cli\fast_api.py", line 780, in _get_root_agent_async raise RuntimeError(f"error getting root agent, {e}") from e RuntimeError: error getting root agent,

sleepMoreEarly avatar Apr 22 '25 02:04 sleepMoreEarly

It's not just MCP part but even openapitoolset doesn't work for me

kanlanc avatar Apr 22 '25 04:04 kanlanc

import os

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


# load_dotenv()

# os.environ["OPENAI_API_BASE"] = os.getenv("OPENAI_BASE_URL")
os.environ["OPENAI_API_BASE"] = 'http://192.0.0.15:11434/v1'
# model = "openai/" + os.getenv("CHAT_MODEL")
model = "openai/qwen2.5-14b-q4km:latest"

async def get_tools_async():
    tools, exit_stack = await MCPToolset.from_server(
        connection_params=StdioServerParameters(
            command=r'python',
            args=[r"C:\Users\Administrator\PycharmProjects\fastapi_yunzhi\mcp_agent\mcp\data_export_mcp.py"],
        )
    )
    return tools, exit_stack


async def create_agent():
    tools, exit_stack = await get_tools_async()

    agent = LlmAgent(
        name="assistant",
        model=LiteLlm(model=model),
        instruction="Help user by using available tools.",
        tools=tools
    )
    return agent, exit_stack


root_agent = create_agent()

I tried Python 3.13 and 3.10 on the Windows 10 operating system, reinstalled the latest packages, but it still didn't work

2025-04-22 10:38:56,786 - ERROR - fast_api.py:637 - Error in event_generator: error getting root agent, Traceback (most recent call last): File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\mcp\client\stdio\win32.py", line 72, in create_windows_process process = await anyio.open_process( File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\anyio_core_subprocesses.py", line 190, in open_process return await get_async_backend().open_process( File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\anyio_backends_asyncio.py", line 2561, in open_process process = await asyncio.create_subprocess_exec( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\subprocess.py", line 218, in create_subprocess_exec transport, protocol = await loop.subprocess_exec( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 1681, in subprocess_exec transport = await self._make_subprocess_transport( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 498, in _make_subprocess_transport raise NotImplementedError NotImplementedError

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\cli\fast_api.py", line 776, in _get_root_agent_async agent, exit_stack = await root_agent File "C:\Users\Administrator\PycharmProjects\test\demo_agent\agent.py", line 27, in create_agent tools, exit_stack = await get_tools_async() File "C:\Users\Administrator\PycharmProjects\test\demo_agent\agent.py", line 17, in get_tools_async tools, exit_stack = await MCPToolset.from_server( File "C:\Users\Administrator\PycharmProjects\test.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 "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\contextlib.py", line 619, in enter_async_context result = await _cm_type.aenter(cm) File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\tools\mcp_tool\mcp_toolset.py", line 258, in aenter raise e File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\tools\mcp_tool\mcp_toolset.py", line 255, in aenter await self.initialize() File "C:\Users\Administrator\PycharmProjects\test.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 "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\tools\mcp_tool\mcp_session_manager.py", line 132, in create_session return await MCPSessionManager.initialize_session( File "C:\Users\Administrator\PycharmProjects\test.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 "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\contextlib.py", line 619, in enter_async_context result = await cm_type.aenter(cm) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\contextlib.py", line 199, in aenter return await anext(self.gen) File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\mcp\client\stdio__init.py", line 113, in stdio_client process = await create_platform_compatible_process( File "C:\Users\Administrator\PycharmProjects\test.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 "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\mcp\client\stdio\win32.py", line 85, in create_windows_process process = await anyio.open_process( File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\anyio_core_subprocesses.py", line 190, in open_process return await get_async_backend().open_process( File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\anyio_backends_asyncio.py", line 2561, in open_process process = await asyncio.create_subprocess_exec( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\subprocess.py", line 218, in create_subprocess_exec transport, protocol = await loop.subprocess_exec( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 1681, in subprocess_exec transport = await self._make_subprocess_transport( File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 498, in _make_subprocess_transport raise NotImplementedError NotImplementedError

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

Traceback (most recent call last): File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\cli\fast_api.py", line 625, in event_generator runner = await _get_runner_async(req.app_name) File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\cli\fast_api.py", line 790, in _get_runner_async root_agent = await _get_root_agent_async(app_name) File "C:\Users\Administrator\PycharmProjects\test.venv\lib\site-packages\google\adk\cli\fast_api.py", line 780, in _get_root_agent_async raise RuntimeError(f"error getting root agent, {e}") from e RuntimeError: error getting root agent,

this is an issue with windows, anyio, and fastapi. not with mcp in adk.

this should fix it

.venv\Lib\site-packages\mcp\client\stdio\__init__.py https://github.com/modelcontextprotocol/python-sdk/pull/555 also addresses this fix

import os
import sys
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Literal, TextIO

import anyio
import anyio.lowlevel
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
from anyio.streams.text import TextReceiveStream
from pydantic import BaseModel, Field

import mcp.types as types

from .win32 import (
    create_windows_process,
    get_windows_executable_command,
    terminate_windows_process,
)

# Environment variables to inherit by default
DEFAULT_INHERITED_ENV_VARS = (
    [
        "APPDATA",
        "HOMEDRIVE",
        "HOMEPATH",
        "LOCALAPPDATA",
        "PATH",
        "PROCESSOR_ARCHITECTURE",
        "SYSTEMDRIVE",
        "SYSTEMROOT",
        "TEMP",
        "USERNAME",
        "USERPROFILE",
    ]
    if sys.platform == "win32"
    else ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"]
)
print( sys.platform)

def get_default_environment() -> dict[str, str]:
    """
    Returns a default environment object including only environment variables deemed
    safe to inherit.
    """
    env: dict[str, str] = {}

    for key in DEFAULT_INHERITED_ENV_VARS:
        value = os.environ.get(key)
        if value is None:
            continue

        if value.startswith("()"):
            # Skip functions, which are a security risk
            continue

        env[key] = value

    return env


class StdioServerParameters(BaseModel):
    command: str
    """The executable to run to start the server."""

    args: list[str] = Field(default_factory=list)
    """Command line arguments to pass to the executable."""

    env: dict[str, str] | None = None
    """
    The environment to use when spawning the process.

    If not specified, the result of get_default_environment() will be used.
    """

    cwd: str | Path | None = None
    """The working directory to use when spawning the process."""

    encoding: str = "utf-8"
    """
    The text encoding used when sending/receiving messages to the server

    defaults to utf-8
    """

    encoding_error_handler: Literal["strict", "ignore", "replace"] = "strict"
    """
    The text encoding error handler.

    See https://docs.python.org/3/library/codecs.html#codec-base-classes for
    explanations of possible values
    """


@asynccontextmanager
async def stdio_client(server: StdioServerParameters, errlog: TextIO = sys.stderr):
    """
    Client transport for stdio: this will connect to a server by spawning a
    process and communicating with it over stdin/stdout.
    """
    read_stream: MemoryObjectReceiveStream[types.JSONRPCMessage | Exception]
    read_stream_writer: MemoryObjectSendStream[types.JSONRPCMessage | Exception]

    write_stream: MemoryObjectSendStream[types.JSONRPCMessage]
    write_stream_reader: MemoryObjectReceiveStream[types.JSONRPCMessage]

    read_stream_writer, read_stream = anyio.create_memory_object_stream(0)
    write_stream, write_stream_reader = anyio.create_memory_object_stream(0)

    command = _get_executable_command(server.command)

    # Open process with stderr piped for capture
    process = await _create_platform_compatible_process(
        command=command,
        args=server.args,
        env=(
            {**get_default_environment(), **server.env}
            if server.env is not None
            else get_default_environment()
        ),
        errlog=errlog,
        cwd=server.cwd,
    )

    async def stdout_reader():
        assert process.stdout, "Opened process is missing stdout"

        try:
            async with read_stream_writer:
                buffer = ""
                async for chunk in TextReceiveStream(
                    process.stdout,
                    encoding=server.encoding,
                    errors=server.encoding_error_handler,
                ):
                    lines = (buffer + chunk).split("\n")
                    buffer = lines.pop()

                    for line in lines:
                        try:
                            message = types.JSONRPCMessage.model_validate_json(line)
                        except Exception as exc:
                            await read_stream_writer.send(exc)
                            continue

                        await read_stream_writer.send(message)
        except anyio.ClosedResourceError:
            await anyio.lowlevel.checkpoint()

    async def stdin_writer():
        assert process.stdin, "Opened process is missing stdin"

        try:
            async with write_stream_reader:
                async for message in write_stream_reader:
                    json = message.model_dump_json(by_alias=True, exclude_none=True)
                    await process.stdin.send(
                        (json + "\n").encode(
                            encoding=server.encoding,
                            errors=server.encoding_error_handler,
                        )
                    )
        except anyio.ClosedResourceError:
            await anyio.lowlevel.checkpoint()

    async with (
        anyio.create_task_group() as tg,
        process,
    ):
        tg.start_soon(stdout_reader)
        tg.start_soon(stdin_writer)
        try:
            yield read_stream, write_stream
        finally:
            # Clean up process to prevent any dangling orphaned processes
            # if sys.platform == "win32":
            #     await terminate_windows_process(process)
            # else:
                process.terminate()


def _get_executable_command(command: str) -> str:
    """
    Get the correct executable command normalized for the current platform.

    Args:
        command: Base command (e.g., 'uvx', 'npx')

    Returns:
        str: Platform-appropriate command
    """
        # if sys.platform == "win32":
        #     return get_windows_executable_command(command)
        # else:
    return command


async def _create_platform_compatible_process(
    command: str,
    args: list[str],
    env: dict[str, str] | None = None,
    errlog: TextIO = sys.stderr,
    cwd: Path | str | None = None,
):
    """
    Creates a subprocess in a platform-compatible way.
    Returns a process handle.
    """
    # if sys.platform == "win32":
    #     print('attempting create windows process')
    #     process = await create_windows_process(command, args, env, errlog, cwd)
    #     print('created windows process')
    # else:
    process = await anyio.open_process(
        [command, *args], env=env, stderr=errlog, cwd=cwd
    )

    return process

.venv\Lib\site-packages\mcp\client\session.py, .venv\Lib\site-packages\google\adk\cli\fast_api.py

asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())

.venv\Lib\site-packages\google\adk\cli\cli_tools_click.py line 354

  config = uvicorn.Config(
      app,
      host="0.0.0.0",
      port=port,
      # reload=True,
  )

BenMawnMahlauNBTC avatar Apr 23 '25 18:04 BenMawnMahlauNBTC

Please install latest ADK

Thanks! The MCP agent works great now after I upgraded the SDK.

May I ask what your system environment is? Windows or Linux? What is the version of Python?

I'm running on MACOS. ADK version is 0.3.0 ,Python version 3.12.9

summerkiwa avatar Apr 27 '25 13:04 summerkiwa

i am usig latest adk 0.5.0 but no luck

SparshCoolApps avatar May 11 '25 10:05 SparshCoolApps

Shoot, I was hoping to test this out rn and hope it works

kanlanc avatar May 11 '25 16:05 kanlanc