MCP on Vertex AI Agent Engine with custom installation scripts
Source notebook
Repo path:
agents/agent_engine/tutorial_mcp_on_agent_engine.ipynb· Open on GitHub · advanced
Deploys a Reddit MCP tool agent to Vertex AI Agent Engine with custom install scripts.
Summary
This notebook teaches how to build a Reddit assistant agent with ADK, connect it to an MCP server over stdio, and test it locally with an ADK Runner. It then packages the agent as a ModuleAgent, uses a custom installation script to install mcp-reddit during the Agent Engine build, deploys it with agent_engines.create, tests the remote app with the same chat loop, and cleans up the Agent Engine and Cloud Storage bucket.
Key code patterns
Vertex AI setup
PROJECT_ID = os.environ.get('GOOGLE_CLOUD_PROJECT')
LOCATION = os.environ.get('GOOGLE_CLOUD_REGION', 'us-central1')
BUCKET_URI = f'gs://{BUCKET_NAME}'
! gsutil mb -l {LOCATION} -p {PROJECT_ID} {BUCKET_URI}
os.environ['GOOGLE_GENAI_USE_VERTEXAI'] = 'TRUE'
os.environ['GOOGLE_CLOUD_PROJECT'] = PROJECT_ID
os.environ['GOOGLE_CLOUD_LOCATION'] = LOCATION
vertexai.init(project=PROJECT_ID, location=LOCATION, staging_bucket=BUCKET_URI)Sets the project, region, staging bucket, and ADK Vertex AI mode before building or deploying the agent.
Custom MCP installer
install_local_mcp_file = '''#!/bin/bash
set -e
apt-get update
apt-get install -y curl
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
uv pip install "git+https://github.com/adhikasp/mcp-reddit.git" --system
'''
with open('installation_scripts/install_local_mcp.sh', 'w') as f:
f.write(install_local_mcp_file)Creates the shell script that installs uv and the mcp-reddit server for local and Agent Engine runtime use.
ADK MCP agent
root_agent = LlmAgent(
model='gemini-2.5-flash',
name='reddit_assistant_agent',
instruction='Help the user fetch reddit info.',
tools=[MCPToolset(
connection_params=StdioConnectionParams(
server_params=StdioServerParameters(command='mcp-reddit')),
errlog=errlog,
)],
)Connects the Gemini-backed ADK agent to the MCP Reddit server through stdio.
Local ADK test
session_service = InMemorySessionService()
session = await session_service.create_session(app_name='MyRunnerApp', user_id=user_id)
errlog = await aiofiles.open('error.log', 'w+')
root_agent = create_agent(errlog)
runner = Runner(agent=root_agent, app_name='MyRunnerApp', session_service=session_service)
chat_loop(runner, user_id, session.id)
await errlog.close()Uses in-memory sessions and an async error log file to test the MCP-backed agent before deployment.
ModuleAgent deployment
remote_app = agent_engines.create(
display_name='reddit_assistant_agent',
agent_engine=agent_engines.ModuleAgent(module_name='root_agent', agent_name='agent_app'),
requirements=['google-cloud-aiplatform[agent_engines,adk]>=1.101.0'],
extra_packages=['root_agent.py', 'installation_scripts/install_local_mcp.sh'],
env_vars={'PROJECT_ID': PROJECT_ID, 'LOCATION': LOCATION,
'REDDIT_CLIENT_ID': REDDIT_CLIENT_ID},
build_options={'installation': ['installation_scripts/install_local_mcp.sh']},
)Packages the module, dependencies, credentials, and installer so Agent Engine can build and host the MCP-enabled app.
Unified chat loop
if isinstance(app, (AdkApp, AgentEngine)):
session = app.create_session(user_id=user_id)
query_fn = lambda msg: app.stream_query(user_id=user_id, session_id=session_id, message=msg)
elif isinstance(app, Runner):
query_fn = lambda msg: app.run(
user_id=user_id,
session_id=session_id,
new_message=types.Content(role='user', parts=[types.Part(text=msg)]),
)Lets the same interactive test harness work against local Runner instances and remote Agent Engine apps.
Models & APIs used
- Models: gemini-2.5-flash
- APIs / services: Vertex AI, Vertex AI Agent Engine, Cloud Storage
- SDKs / libraries:
google-cloud-aiplatform[agent_engines,adk],google-adk,google-genai,vertexai,aiofiles
When to use this
Use this pattern when an ADK agent needs an MCP server or other nonstandard runtime dependency installed during Vertex AI Agent Engine deployment.
Gotchas & caveats
- The notebook says to restart the Colab or notebook kernel after installing google-cloud-aiplatform[agent_engines,adk] and aiofiles.
- Vertex AI API must be enabled, and PROJECT_ID, LOCATION, and a Cloud Storage staging bucket must be configured before initialization.
- Colab authentication uses google.colab.auth.authenticate_user only when running in Colab.
- Reddit access needs a client ID, client secret, and refresh token; the notebook warns not to hardcode secrets.
- The Colab fileno error is handled by redirecting the MCP tool error stream to an aiofiles async file handle.
- Since ADK 1.0.0, MCPToolset has non-pickleable state, so deployment uses a separate root_agent.py and ModuleAgent.
- The custom installer must be included in extra_packages and referenced under build_options.installation.
- The notebook deletes the Agent Engine and Cloud Storage bucket to avoid ongoing charges.
Best practices
- Test the agent locally with InMemorySessionService and Runner before deploying to Agent Engine.
- Use environment variables for Google Cloud settings and Reddit credentials.
- Use one chat_loop abstraction for local Runner and remote AgentEngine or AdkApp testing.
- Close the aiofiles error log in a finally block after local testing.
- Wrap the deployed ADK app in root_agent.py and reference it with ModuleAgent when MCPToolset is used.
- Register session and streaming operations on the ModuleAgent for remote interaction.
- Clean up the deployed Agent Engine and Cloud Storage bucket after the tutorial.
Related
- Concepts: Agents & ADK · Agent Engine · Function Calling & Tools
- Entities: Vertex AI · Google GenAI SDK · Vertex AI SDK · Agent Development Kit · Model Context Protocol · Cloud Storage · Gemini
- Area: Agents & ADK Notebooks
- Best practices: Agents & ADK - Best Practices · Agent Engine - Best Practices · Function Calling & Tools - Best Practices