Support Asynchronous Initialization for `root_model` in ADK Agents
Currently, the ADK documentation for MCP Tools demonstrates an async initialization approach. The MCPToolset tool only provides async methods, while the agents export a synchronous root_model. This creates an inconsistency that forces developers to implement workarounds (using nested event loops or threading) to bridge async MCPToolset initialization with the synchronous export required by the ADK agent framework.
It would be highly beneficial if the framework could support asynchronous initialization directly in the agent’s module. This would allow developers to define root_model as an async function or await the async MCPToolset methods naturally, without extra hacks or patching the event loop.
Could you please provide guidance on the recommended approach to handle this inconsistency? Either by supporting async initialization for the root_model or by updating the documentation with best practices to bridge async and sync code in this context.
yes, this is a blocker issue for ADK + MCP integration, I even tried some workaround to use nested event loops, it also didn't work.
I also encountered this problem. If i use 'adk web' and 'await MCPToolset.from_server', there is a Error in event_generator: module 'xxx_agent.agent' has no attribute 'root_agent'.
@nikhil-pandey could you provide a example to reproduce this error?
I agree this is a major limitation right now. I want to be able to use adk web to run MCP tools.
from google.adk.agents import Agent
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters
async def get_tools_async():
"""Gets tools from the Youtube MCP Server."""
print("Attempting to connect to MCP Youtube server...")
tools, exit_stack = await MCPToolset.from_server(
connection_params=StdioServerParameters(
command='npx',
args=["-y", "@sinco-lab/mcp-youtube-transcript"],
)
)
print("MCP Toolset created successfully.")
return tools, exit_stack
root_agent = Agent(
name="youtube_agent",
model="gemini-2.0-flash-exp",
description=(
"Agent to get youtube transcript"
),
instruction=(
"I can get youtube transcripts"
),
tools=[get_tools_async],
)
yes, this is a blocker issue for ADK + MCP integration, I even tried some workaround to use nested event loops, it also didn't work.
Below is my workaround of the documentation example, bit messy, but it works.
# ./adk_agent_samples/mcp_agent/agent.py
import asyncio
from dotenv import load_dotenv
from google.genai import types
from google.adk.agents.llm_agent import LlmAgent
from google.adk.models.lite_llm import LiteLlm
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, SseServerParams, StdioServerParameters
# Load environment variables from .env file in the parent directory
load_dotenv('../.env')
# Define root_agent at module level for the ADK CLI to find
root_agent = None
# Initialize the agent and tools synchronously for the CLI to use
def init_agent():
global root_agent
# Create a simple non-MCP agent initially
# This will be replaced with the MCP agent when async initialization is complete
root_agent = LlmAgent(
model=LiteLlm(model="openai/qwen2.5:3b"),
name='filesystem_assistant',
instruction='Help user interact with the local filesystem using available tools.',
tools=[], # Empty tools list initially
)
# Start async initialization in background
asyncio.create_task(init_agent_async())
return root_agent
async def init_agent_async():
global root_agent
# Get MCP tools
try:
tools, exit_stack = await get_tools_async()
print(f"Fetched {len(tools)} tools from MCP server.")
# Update the existing agent with tools
root_agent.tools = tools
# Store exit_stack in module to prevent garbage collection
# Note: This needs proper cleanup strategy in production
global _exit_stack
_exit_stack = exit_stack
except Exception as e:
print(f"Error initializing MCP tools: {e}")
# --- Step 1: Import Tools from MCP Server ---
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(
connection_params=StdioServerParameters(
command='npx',
args=["-y",
"@modelcontextprotocol/server-filesystem",
"/path/to/your/folder",] # Replace with your folder path
)
)
print("MCP Toolset created successfully.")
return tools, exit_stack
# --- Step 2: Agent Definition ---
async def get_agent_async():
"""Creates an ADK Agent equipped with tools from the MCP Server."""
tools, exit_stack = await get_tools_async()
print(f"Fetched {len(tools)} tools from MCP server.")
agent = LlmAgent(
model=LiteLlm(model="openai/qwen2.5:3b"),
name='filesystem_assistant',
instruction='Help user interact with the local filesystem using available tools.',
tools=tools,
)
return agent, exit_stack
# Initialize the agent
init_agent()
# --- Step 3: Main Execution Logic ---
async def async_main():
session_service = InMemorySessionService()
artifacts_service = InMemoryArtifactService()
session = session_service.create_session(
state={}, app_name='mcp_filesystem_app', user_id='user_fs'
)
query = "list files in the tests folder"
print(f"User Query: '{query}'")
content = types.Content(role='user', parts=[types.Part(text=query)])
agent, exit_stack = await get_agent_async()
runner = Runner(
app_name='mcp_filesystem_app',
agent=agent,
artifact_service=artifacts_service,
session_service=session_service,
)
print("Running agent...")
events_async = runner.run_async(
session_id=session.id, user_id=session.user_id, new_message=content
)
async for event in events_async:
print(f"Event received: {event}")
print("Closing MCP server connection...")
await exit_stack.aclose()
print("Cleanup complete.")
if __name__ == '__main__':
try:
asyncio.run(async_main())
except Exception as e:
print(f"An error occurred: {e}")
I agree this is a major limitation right now. I want to be able to use adk web to run MCP tools.
from google.adk.agents import Agent from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters
async def get_tools_async(): """Gets tools from the Youtube MCP Server.""" print("Attempting to connect to MCP Youtube server...") tools, exit_stack = await MCPToolset.from_server( connection_params=StdioServerParameters( command='npx', args=["-y", "@sinco-lab/mcp-youtube-transcript"], ) ) print("MCP Toolset created successfully.") return tools, exit_stack
root_agent = Agent( name="youtube_agent", model="gemini-2.0-flash-exp", description=( "Agent to get youtube transcript" ), instruction=( "I can get youtube transcripts" ), tools=[get_tools_async], )
I also want to use mcp with adk web, pls review my pr #42 @thismart595 @hangfei
I think the MCP example in the documentation work.
However, MCP tool doesn't work with adk web.
I really hope ADK Web supports MCP tools.Please check my pr #42 @hangfei thanks.
from contextlib import AsyncExitStack
from google.adk.agents import Agent
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParameters
async def get_tools_async(agent: Agent) -> AsyncExitStack:
"""Gets tools from the Youtube MCP Server."""
print("Attempting to connect to MCP Youtube server...")
stack = AsyncExitStack()
tools, _ = await MCPToolset.from_server(
connection_params=StdioServerParameters(
command='uv',
args=[
"--directory",
"/Users/howard/workspace/mcp-youtube-transcript",
"run",
"mcp-youtube-transcript",
],
),
async_exit_stack=stack
)
print("MCP Toolset created successfully.")
agent.tools.extend(tools)
return stack
root_agent = Agent(
name="youtube_agent",
model="gemini-2.0-flash-exp",
description=(
"Agent to get youtube transcript"
),
instruction=(
"I can get youtube transcripts"
),
async_setup=get_tools_async,
)
the mcp server i used is: mcp-youtube-transcript
yes, this is a blocker issue for ADK + MCP integration, I even tried some workaround to use nested event loops, it also didn't work.
Below is my workaround of the documentation example, bit messy, but it works.
./adk_agent_samples/mcp_agent/agent.py
import asyncio from dotenv import load_dotenv from google.genai import types from google.adk.agents.llm_agent import LlmAgent from google.adk.models.lite_llm import LiteLlm from google.adk.runners import Runner from google.adk.sessions import InMemorySessionService from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, SseServerParams, StdioServerParameters
Load environment variables from .env file in the parent directory
load_dotenv('../.env')
Define root_agent at module level for the ADK CLI to find
root_agent = None
Initialize the agent and tools synchronously for the CLI to use
def init_agent(): global root_agent
# Create a simple non-MCP agent initially # This will be replaced with the MCP agent when async initialization is complete root_agent = LlmAgent( model=LiteLlm(model="openai/qwen2.5:3b"), name='filesystem_assistant', instruction='Help user interact with the local filesystem using available tools.', tools=[], # Empty tools list initially ) # Start async initialization in background asyncio.create_task(init_agent_async()) return root_agentasync def init_agent_async(): global root_agent
# Get MCP tools try: tools, exit_stack = await get_tools_async() print(f"Fetched {len(tools)} tools from MCP server.") # Update the existing agent with tools root_agent.tools = tools # Store exit_stack in module to prevent garbage collection # Note: This needs proper cleanup strategy in production global _exit_stack _exit_stack = exit_stack except Exception as e: print(f"Error initializing MCP tools: {e}")--- Step 1: Import Tools from MCP Server ---
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( connection_params=StdioServerParameters( command='npx', args=["-y", "@modelcontextprotocol/server-filesystem", "/path/to/your/folder", # Replace with your folder path], ) ) print("MCP Toolset created successfully.") return tools, exit_stack
--- Step 2: Agent Definition ---
async def get_agent_async(): """Creates an ADK Agent equipped with tools from the MCP Server.""" tools, exit_stack = await get_tools_async() print(f"Fetched {len(tools)} tools from MCP server.") agent = LlmAgent( model=LiteLlm(model="openai/qwen2.5:3b"), name='filesystem_assistant', instruction='Help user interact with the local filesystem using available tools.', tools=tools, ) return agent, exit_stack
Initialize the agent
init_agent()
--- Step 3: Main Execution Logic ---
async def async_main(): session_service = InMemorySessionService() artifacts_service = InMemoryArtifactService()
session = session_service.create_session( state={}, app_name='mcp_filesystem_app', user_id='user_fs' ) query = "list files in the tests folder" print(f"User Query: '{query}'") content = types.Content(role='user', parts=[types.Part(text=query)]) agent, exit_stack = await get_agent_async() runner = Runner( app_name='mcp_filesystem_app', agent=agent, artifact_service=artifacts_service, session_service=session_service, ) print("Running agent...") events_async = runner.run_async( session_id=session.id, user_id=session.user_id, new_message=content ) async for event in events_async: print(f"Event received: {event}") print("Closing MCP server connection...") await exit_stack.aclose() print("Cleanup complete.")if name == 'main': try: asyncio.run(async_main()) except Exception as e: print(f"An error occurred: {e}")
@JohnEarle 's workaround works for ADK web. (there is a missing closing square bracket here: "/path/to/your/folder", # Replace with your folder path], )
Right now, to unblock you to use MCP with adk web, please use the above approach.
In other case, MCP with ADK should work.
We will discuss the fix as it involves interfaces changes. It will be fixed soon. @Howe829
@hangfei @JohnEarle's workaround isn't working for me. The agent responds with the tool call instead of actually using the tool.
@hangfei @JohnEarle's workaround isn't working for me. The agent responds with the tool call instead of actually using the tool.
This work around lets you load the mcp agent in Web.
Without it you would have a missing root_agent error.
For this behaviour please try changing your model, and if using ollama please review the GitHub issues/workarounds with ollama and tool usage
@thismart595 see issue #49
I've managed to use MCP with sub-agents by just running async mcp tool initialization function as soon as root agent is started and then run something like that
browser_agent.tools.extend(tools)
browser_agent.description = "I can control the browser using following tools: " + ", ".join([tool.name for tool in tools])
It's not stable of course and just a workaround but it allows to work with MCP via adk web
I've managed to use MCP with sub-agents by just running async mcp tool initialization function as soon as root agent is started and then run something like that
browser_agent.tools.extend(tools) browser_agent.description = "I can control the browser using following tools: " + ", ".join([tool.name for tool in tools])It's not stable of course and just a workaround but it allows to work with MCP via
adk web
@AlexRAV
Issue with exit_stack not being called, causing issues when streaming ends?
@JohnEarle, your workaround works for me, thanks! 👍🏽
This is fixed now in the latest version(0.2.0). The instruction is here: https://github.com/google/adk-docs/pull/128 .
Please try it out and let us know if you still see any issues.
This is fixed now in the latest version(0.2.0). The instruction is here: google/adk-docs#128 .
Please try it out and let us know if you still see any issues.
Great to hear that! Closing this issue.
i am trying to run google adk web with the above approach - but it looks like it is impossible to run this. it always says MCP Initiliation Error!
@hangfei this looks broken again, setting the root_agent to an async def method no longer works
You can just pass the toolset in ask 1.0 - no need to run toolset.get_tools(). I didn't test with the YouTube MCP but the following example should work:
from google.adk.agents import Agent
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset,
from google.adk.tools.mcp_tool.mcp_session_manager import StdioServerParameters
toolset = MCPToolset(
connection_params=StdioServerParameters(
command='npx',
args=["-y", "@sinco-lab/mcp-youtube-transcript"],
)
)
root_agent = Agent(
name="youtube_agent",
model="gemini-2.0-flash-exp",
description=(
"Agent to get youtube transcript"
),
instruction=(
"I can get youtube transcripts"
),
tools=[toolset],
)