Error in using Multiple MCP server tools in different ADK agents (code implementation) #342
Unanswered
Karthik-Manne
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Pre-submission Checklist
Question Category
Your Question
I am working on creating a multi agent system using google ADK agents and MCP servers for tools.
I have a sample code with two agents and each agent using tools from different MCP servers.
Here is the code I have, implementing the multi agent system.
`from google.adk.agents.llm_agent import LlmAgent
from google.adk.agents import SequentialAgent, LoopAgent, ParallelAgent
from google.genai import types
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters
from google.adk.tools import transfer_to_agent
import os
import asyncio
os.environ["GOOGLE_API_KEY"]=".........."
async def get_tools_async(run_command, arguments):
print(f"Connecting to MCP tool: command={run_command}, args={arguments}")
tools, exit_stack = await MCPToolset.from_server(
connection_params=StdioServerParameters(command=run_command, args=arguments),
# async_exit_stack=self.common_exit_stack
)
print(f"Connected and received {len(tools)} tools.")
return tools, exit_stack
async def create_agent(command, args, agent_name, agent_instruction):
"""Gets tools from MCP Server."""
tools, exit_stack = await get_tools_async(command, args)
agent = LlmAgent(
model='gemini-2.0-flash',
name=agent_name,
instruction=agent_instruction,
tools=tools,
)
return agent, exit_stack
async def main():
itinerary, exit_stack1 = await create_agent("npx", ["@gongrzhe/server-travelplanner-mcp"], "ItineraryPlannerAgent", "Generate a travel itinerary with popular spots, optimized travel time, and meal breaks based on destination and duration. Return the plan in a daily breakdown in the response itself.")
airbnb, exit_stack2 = await create_agent("npx", ["-y","@openbnb/mcp-server-airbnb"], "StayBookingAgent", "Search for suitable Airbnb stays based on the travel query or the planned travel Itinerary. Return details like name, price, and availability in the response itself.")
if name == "main":
asyncio.run(main())`
Here is the error I am facing,
an error occurred during closing of asynchronous generator <async_generator object stdio_client at 0x...>
asyncgen: <async_generator object stdio_client at 0x...>
| File "anyio/_backends/_asyncio.py", line 772, in aexit
| raise BaseExceptionGroup(
| exceptiongroup.BaseExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "mcp/client/stdio/init.py", line 173, in stdio_client
| yield read_stream, write_stream
| GeneratorExit
+------------------------------------
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "mcp/client/stdio/init.py", line 166, in stdio_client
async with (
File "anyio/_backends/_asyncio.py", line 778, in aexit
if self.cancel_scope.exit(type(exc), exc, exc.traceback):
File "anyio/_backends/_asyncio.py", line 457, in exit
raise RuntimeError(
RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
Traceback (most recent call last):
File "anyio/_backends/_asyncio.py", line 776, in aexit
raise exc_val
File "mcp/client/stdio/init.py", line 166, in stdio_client
async with (
File "anyio/abc/_resources.py", line 29, in aexit
await self.aclose()
File "anyio/_backends/_asyncio.py", line 1074, in aclose
await self.wait()
File "anyio/_backends/_asyncio.py", line 1082, in wait
return await self._process.wait()
File "asyncio/subprocess.py", line 134, in wait
return await self._transport._wait()
File "asyncio/base_subprocess.py", line 235, in _wait
return await waiter
asyncio.exceptions.CancelledError: Cancelled by cancel scope ...
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test_agent.py", line 65, in
asyncio.run(main())
File "asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "test_agent.py", line 60, in main
await exit_stack1.aclose()
File "contextlib.py", line 656, in aclose
await self.aexit(None, None, None)
File "contextlib.py", line 714, in aexit
raise exc_details[1]
File "contextlib.py", line 697, in aexit
cb_suppress = await cb(*exc_details)
File "mcp_tool/mcp_toolset.py", line 266, in aexit
await self._exit()
File "mcp_tool/mcp_toolset.py", line 234, in _exit
await self.exit_stack.aclose()
File "contextlib.py", line 656, in aclose
await self.aexit(None, None, None)
File "contextlib.py", line 714, in aexit
raise exc_details[1]
File "contextlib.py", line 697, in aexit
cb_suppress = await cb(*exc_details)
File "contextlib.py", line 217, in aexit
await self.gen.athrow(typ, value, traceback)
File "mcp/client/stdio/init.py", line 166, in stdio_client
async with (
File "anyio/_backends/_asyncio.py", line 778, in aexit
if self.cancel_scope.exit(type(exc), exc, exc.traceback):
File "anyio/_backends/_asyncio.py", line 465, in exit
raise RuntimeError(
RuntimeError: Attempted to exit a cancel scope that isn't the current tasks's current cancel scope
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x...>
Traceback (most recent call last):
File "asyncio/proactor_events.py", line 116, in del
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
File "asyncio/proactor_events.py", line 80, in repr
info.append(f'fd={self._sock.fileno()}')
File "asyncio/windows_utils.py", line 102, in fileno
raise ValueError("I/O operation on closed pipe")
ValueError: I/O operation on closed pipe
Exception ignored in: <function BaseSubprocessTransport.del at 0x...>
Traceback (most recent call last):
File "asyncio/base_subprocess.py", line 125, in del
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
File "asyncio/base_subprocess.py", line 78, in repr
info.append(f'stdout={stdout.pipe}')
File "asyncio/proactor_events.py", line 80, in repr
info.append(f'fd={self._sock.fileno()}')
File "asyncio/windows_utils.py", line 102, in fileno
raise ValueError("I/O operation on closed pipe")
ValueError: I/O operation on closed pipe
I am not able to understand the whole error and where the error is occurring.
Please, suggest what can be done here.
Thanks
Beta Was this translation helpful? Give feedback.
All reactions