-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Description
I am using this example from adk doc of mcp tool, https://google.github.io/adk-docs/tools/mcp-tools/#mcptoolset-class
Initially, I understood that create_agent() is a coroutine, which means it should be awaited if called within another async function, or run using asyncio.run() if called from a synchronous context.
So, I tried using:
'root_agent, exit_stack = asyncio.run(create_agent())'
However, this raised an error: 'asyncio.run() cannot be called from a running event loop.' This made me realize that FastAPI must already be running an event loop under the hood. If an event loop is already active, trying to create another causes a conflict.
To resolve this, I used the nest_asyncio module, which patches the running event loop to allow nesting:
import nest_asyncio
nest_asyncio.apply()
root_agent, exit_stack = asyncio.run(create_agent())
This workaround allowed me to run the coroutine without hitting the event loop error but this is not an ideal solution. Is there a better or more proper way to handle this situation? Did I make any mistakes?
# ./adk_agent_samples/mcp_agent/agent.py
from google.adk.agents.llm_agent import LlmAgent
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters
import asyncio
import nest_asyncio
nest_asyncio.apply()
async def create_agent():
"""Gets tools from MCP Server."""
tools, exit_stack = await MCPToolset.from_server(
connection_params=StdioServerParameters(
command='npx',
args=["-y", # Arguments for the command
"@modelcontextprotocol/server-filesystem",
# TODO: IMPORTANT! Change the path below to an ABSOLUTE path on your system.
"~/Sample/sample_agents2/MCP_Agent",
],
)
)
agent = LlmAgent(
model='gemini-2.0-flash',
name='enterprise_assistant',
instruction=(
'Help user accessing their file systems'
),
tools=tools,
)
return agent, exit_stack
root_agent, exit_stack = asyncio.run(create_agent())