Lab 34: Deploying a Stateless MCP Server to Cloud Run & Connecting agents-cli
Goalโ
In this lab, you will take the stateful MCP server pattern from Module 28, re-architect it into a stateless FastMCP HTTP server, containerize it with a Dockerfile, and deploy it to Google Cloud Run. Then, in Steps 4 and 5, you will connect to your live Cloud Run /mcp endpoint in two ways:
- Standalone ADK Package (
cloud_mcp_server/agent.py): Launchuv run adk webfrom the parentadk-training/directory to test the remote MCP server interactively. - Enterprise
agents-cliProject (support-ops-agent/app/agent.py): Equip the canonical Parts 6โ7support_ops_agentwithMcpToolset(connection_params=StreamableHTTPConnectionParams(url=f"{MCP_SERVER_URL}/mcp", headers=...))and test it immediately viaagents-cli runandagents-cli playground.
Note: For lab simplicity, our server simulates externalized state using per-session JSON files in /tmp/carts keyed by the Mcp-Session-Id HTTP header. In production, you replace those two helper functions (get_cart / save_cart) with Google Cloud Memorystore (Redis) or Firestore.
Prerequisitesโ
- A Google Cloud Project with billing enabled.
- Google Cloud CLI (
gcloud) installed and authenticated. uvandgoogle-agents-cliinstalled (uv tool install google-agents-cli).- Required APIs: Cloud Run, Cloud Build, Artifact Registry, and Vertex AI:
export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
export DEPLOY_REGION=us-central1
gcloud config set project "$GOOGLE_CLOUD_PROJECT"
gcloud services enable run.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com aiplatform.googleapis.com
Step 1: Create the Stateless FastMCP Serverโ
Environment setup:
- 1-Click Launch (Browser): Open in GitHub CodespacesOpen in Google Cloud Shell
- Local machine: If you're continuing the course in sequence,
cdinto theadk-trainingproject you created in Module 2 and skip the block below -- your environment and dependencies already carry forward. If you're starting fresh at this module, create that project first:uv init adk-training --python 3.10 && cd adk-training
uv add "google-adk>=2.1.0" python-dotenv- DevContainer / Codespaces (Alternative): If you opened this repository in a DevContainer or GitHub Codespaces, Python 3.11,
uv,gcloud, and all core ADK dependencies are pre-installed in your container environment.
-
Create a new
cloud_mcp_serverdirectory inside youradk-trainingworkspace:cd /path/to/your/adk-training
mkdir cloud_mcp_server
cd cloud_mcp_server -
Create
stateless_cart_server.py: Usingmcp.server.fastmcp.FastMCP, each tool call extracts themcp-session-idHTTP header managed by the Streamable HTTP transport and reads/writes that session's isolated cart outside Python process globals:# Filename: stateless_cart_server.py
import json
import os
from mcp.server.fastmcp import FastMCP, Context
# --- Configuration ---
# In a serverless environment, we use /tmp/carts to simulate an external store.
# In production, replace get_cart/save_cart with Memorystore (Redis) or Firestore.
STATE_STORAGE_PATH = "/tmp/carts"
if not os.path.exists(STATE_STORAGE_PATH):
os.makedirs(STATE_STORAGE_PATH)
# --- MCP Server Setup ---
mcp = FastMCP("stateless_shopping_cart_server")
def get_session_id(ctx: Context) -> str:
# The MCP session ID arrives as a standard HTTP header tracked by the transport.
return ctx.request_context.request.headers.get("mcp-session-id", "unknown")
def get_cart(session_id: str) -> list:
cart_file = os.path.join(STATE_STORAGE_PATH, f"{session_id}.json")
if os.path.exists(cart_file):
with open(cart_file, "r") as f:
return json.load(f)
return []
def save_cart(session_id: str, cart: list) -> None:
cart_file = os.path.join(STATE_STORAGE_PATH, f"{session_id}.json")
with open(cart_file, "w") as f:
json.dump(cart, f)
@mcp.tool()
def add_item_to_cart(item: str, ctx: Context) -> dict:
"""Adds an item to the session cart."""
session_id = get_session_id(ctx)
print(f"[Server]: Handling add_item_to_cart for session '{session_id}'")
cart = get_cart(session_id)
cart.append(item)
save_cart(session_id, cart)
return {"status": "success", "message": f"Added '{item}'."}
@mcp.tool()
def view_cart(ctx: Context) -> dict:
"""Views all items currently in the session cart."""
session_id = get_session_id(ctx)
print(f"[Server]: Handling view_cart for session '{session_id}'")
cart = get_cart(session_id)
return {"status": "success", "cart": cart}
# --- ASGI app for HTTP, suitable for Cloud Run ---
# FastMCP mounts the Streamable HTTP MCP endpoint at /mcp by default.
app = mcp.streamable_http_app()
Step 2: Containerize the MCP Serverโ
-
Create
requirements.txt: Pinmcp<2alongsideuvicornsomcp.server.fastmcp.FastMCPandgoogle-adk'sMcpToolsetclient stay aligned on the 1.x MCP SDK surface:printf "mcp<2\nuvicorn\n" > requirements.txt -
Create
Dockerfile:FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY stateless_cart_server.py .
# Cloud Run injects PORT (defaults to 8080 locally).
# Shell form is used so ${PORT:-8080} expands at container startup.
CMD python -m uvicorn stateless_cart_server:app --host 0.0.0.0 --port ${PORT:-8080}
Step 3: Build and Deploy the MCP Server to Cloud Runโ
-
Ensure an Artifact Registry Docker repository exists and submit the build:
gcloud artifacts repositories describe adk-images --location="$DEPLOY_REGION" >/dev/null 2>&1 || \
gcloud artifacts repositories create adk-images \
--repository-format=docker \
--location="$DEPLOY_REGION"
gcloud builds submit \
--tag "${DEPLOY_REGION}-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/adk-images/mcp-cart-server:v1" -
Deploy
mcp-cart-serverto Cloud Run and storeMCP_SERVER_URL:gcloud run deploy mcp-cart-server \
--image="${DEPLOY_REGION}-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/adk-images/mcp-cart-server:v1" \
--region="$DEPLOY_REGION" \
--allow-unauthenticated
export MCP_SERVER_URL=$(gcloud run services describe mcp-cart-server \
--region="$DEPLOY_REGION" \
--format='value(status.url)')
echo "Deployed MCP Server Base URL: $MCP_SERVER_URL"
Step 4: Connect Both a Standalone ADK Agent and Your agents-cli Projectโ
Step 4A: Configure the Standalone ADK Client (cloud_mcp_server/agent.py)โ
-
Install the MCP client extra in your
adk-trainingenvironment:uv add "google-adk[mcp]" -
Create
cloud_mcp_server/agent.pyand complete the# TODOblock: Notice thatMCP_SERVER_URLholds the Cloud Run base URL, whileFastMCPserves the Streamable HTTP endpoint atf"{MCP_SERVER_URL}/mcp":# Filename: cloud_mcp_server/agent.py
import os
from google.adk.agents import Agent
from google.adk.tools.mcp_tool import McpToolset, StreamableHTTPConnectionParams
MCP_SERVER_URL = os.environ.get(
"MCP_SERVER_URL",
"https://YOUR_CLOUD_RUN_SERVICE_URL",
).rstrip("/")
# TODO: Define `root_agent` (name="cloud_shopping_agent", model="gemini-3.8-flash")
# equipped with `McpToolset(connection_params=StreamableHTTPConnectionParams(url=f"{MCP_SERVER_URL}/mcp"))`.
root_agent = None -
Create
cloud_mcp_server/__init__.pyandcloud_mcp_server/.env:from . import agentCreate
cloud_mcp_server/.env(separating Cloud Run'sus-central1region fromGOOGLE_CLOUD_LOCATION=globalforgemini-3.8-flash):GOOGLE_GENAI_USE_ENTERPRISE=1
GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
GOOGLE_CLOUD_LOCATION=global
MCP_SERVER_URL=https://YOUR_CLOUD_RUN_SERVICE_URL
Step 4B: Equip Your agents-cli Project (support-ops-agent/app/agent.py)โ
Now connect the exact same Cloud Run MCP server into the canonical Part 6 agents-cli support-ops-agent project so your enterprise support agent can both triage tickets (lookup_ticket, check_sla_policy, escalate_ticket) and stage incident follow-up items in the remote Cloud Run MCP cart!
-
Open (or scaffold)
support-ops-agentand addgoogle-adk[mcp]:cd /path/to/your/adk-training
# If you don't already have support-ops-agent from earlier Part 6 modules, scaffold it now:
if [ ! -d "support-ops-agent" ]; then
agents-cli scaffold create support-ops-agent \
--agent adk \
--prototype \
--region "$DEPLOY_REGION" \
--agent-guidance-filename GEMINI.md
curl -fsSL https://mauripsale.github.io/doc-adk-training/samples/part6/agent.py -o support-ops-agent/app/agent.py
fi
cd support-ops-agent
uv add "google-adk[mcp]"
agents-cli install -
Update
support-ops-agent/app/agent.py(complete the# TODOsection): Equipsupport_ops_agentwithMcpToolsetusingStreamableHTTPConnectionParams(url=f"{MCP_SERVER_URL}/mcp", headers=mcp_headers)(supporting an optionalMCP_AUTH_TOKENBearer header when your Cloud Run MCP service uses--no-allow-unauthenticated), while keepingapp = App(root_agent=root_agent, name="app")intact:# Filename: support-ops-agent/app/agent.py
import os
from typing import Any, Dict
from google.adk.agents import Agent
from google.adk.agents.callback_context import CallbackContext
from google.adk.apps import App
from google.adk.models import Gemini
from google.adk.tools.mcp_tool import McpToolset, StreamableHTTPConnectionParams
from google.adk.tools.tool_context import ToolContext
from google.genai import types
MODEL = "gemini-3.8-flash"
MCP_SERVER_URL = os.environ.get(
"MCP_SERVER_URL",
"https://YOUR_CLOUD_RUN_SERVICE_URL",
).rstrip("/")
MCP_AUTH_TOKEN = os.environ.get("MCP_AUTH_TOKEN", "")
mcp_headers = {"Authorization": f"Bearer {MCP_AUTH_TOKEN}"} if MCP_AUTH_TOKEN else None
# ... (keep TICKET_DB, SLA_POLICIES, initialize_support_state,
# lookup_ticket, check_sla_policy, and escalate_ticket from Part 6 agent.py) ...
# TODO: Instantiate `remote_cart_toolset` using `McpToolset` and
# `StreamableHTTPConnectionParams(url=f"{MCP_SERVER_URL}/mcp", headers=mcp_headers)`,
# and attach it to `root_agent` alongside `[lookup_ticket, check_sla_policy, escalate_ticket]`.
remote_cart_toolset = None
Step 5: Test End-to-End with adk web, agents-cli run, and agents-cli playgroundโ
5A: Test the Standalone ADK Package via uv run adk webโ
adk web must always be launched from the parent directory (adk-training/) containing cloud_mcp_server/:
cd /path/to/your/adk-training
export MCP_SERVER_URL=$(gcloud run services describe mcp-cart-server --region="$DEPLOY_REGION" --format='value(status.url)')
uv run adk web
- Open
http://127.0.0.1:8000in your browser and selectcloud_mcp_serverfrom the dropdown. - Ask the agent to add
'apples'and'bread', then ask"What is in my cart?"to confirm state persists across remote Cloud Run HTTP calls. - Press
Ctrl+Cwhen finished.
5B: Test the agents-cli Project via agents-cli run and agents-cli playgroundโ
Switch into support-ops-agent/ and verify the Cloud Run MCP toolset directly through agents-cli:
cd /path/to/your/adk-training/support-ops-agent
export GOOGLE_GENAI_USE_ENTERPRISE=1
export GOOGLE_CLOUD_LOCATION=global
export MCP_SERVER_URL=$(gcloud run services describe mcp-cart-server --region="$DEPLOY_REGION" --format='value(status.url)')
# Optional if mcp-cart-server was deployed privately without --allow-unauthenticated:
# export MCP_AUTH_TOKEN=$(gcloud auth print-identity-token)
# 1. Terminal smoke test across two turns on the same session (--start-server + --session-id)
agents-cli run "Investigate ticket TCK-1042, check enterprise SLA, and add 'P1-Pager-Bridge' to my cart." \
--start-server \
--session-id ops-mcp-demo
agents-cli run "View my cart and confirm which tickets were escalated." \
--session-id ops-mcp-demo
# 2. Interactive visual debugging via agents-cli playground
agents-cli playground
Notice how seamlessly support_ops_agent combines local stateful Python tools (lookup_ticket, check_sla_policy, escalate_ticket) with remote Cloud Run MCP tools (add_item_to_cart, view_cart)!
Cleanup (Important!)โ
Delete the Cloud Run service and Artifact Registry repository when finished to avoid ongoing storage or compute charges:
gcloud run services delete mcp-cart-server \
--region="$DEPLOY_REGION" \
--async
gcloud artifacts repositories delete adk-images \
--location="$DEPLOY_REGION" \
--async
cd /path/to/your/adk-training
rm -rf cloud_mcp_server
Self-Reflection Questionsโ
- Our demo MCP server writes session files under
/tmp/carts. Why is/tmpvolatile on Cloud Run, and what happens to a user's cart when Cloud Run scales down to zero? - What advantages does Google Cloud Memorystore (Redis) provide over
/tmpfiles for storing MCP session state? - How does
StreamableHTTPConnectionParams(url=f"{MCP_SERVER_URL}/mcp", headers=...)decouplesupport-ops-agentfrom the MCP server's internal storage implementation and authentication topology?
๐ Reference Solution Vaultโ
Official Solution Vault โ Module 34
Locked Challenge โ Active Pedagogical Socratic Gate