Level: Advanced ยท Env: Google Cloud Shell (browser terminal, no local install required)

What you'll build

A Cloud Run Fleet Assistant: an ADK agent that answers questions like "what services are deployed?" and "show me recent errors for my-service" by calling tools that live in a completely separate MCP server - not baked into the agent's own code. You'll deploy both pieces to Cloud Run as two independent services talking to each other over an authenticated HTTP connection.

Learning objectives

By the end you'll be able to:

In Workshop 1, a "tool" was a Python function living directly inside agent.py - useful, but it only exists for that one agent, in that one codebase. MCP (Model Context Protocol) is an open standard that moves tools into their own standalone server, so any MCP-compatible client - an ADK agent, Claude Desktop, a different framework entirely - can discover and call them the same way, over the same protocol.

flowchart LR subgraph Host["ADK Agent (MCP Host)"] A[LLM] --> T[McpToolset] end T -- "Streamable HTTP" --> S[MCP Server] subgraph Server["MCP Server"] S --> L[list_cloud_run_services] S --> G[get_service_logs] end L --> C[Cloud Run Admin API] G --> D[Cloud Logging API]
View diagram source
flowchart LR
  subgraph Host["ADK Agent (MCP Host)"]
    A[LLM] --> T[McpToolset]
  end
  T -- "Streamable HTTP" --> S[MCP Server]
  subgraph Server["MCP Server"]
    S --> L[list_cloud_run_services]
    S --> G[get_service_logs]
  end
  L --> C[Cloud Run Admin API]
  G --> D[Cloud Logging API]

The agent never imports your tool code at all - it sends a tools/list request over the wire, gets back names/schemas/docstrings exactly like a local tool, and calls one with tools/call when the model decides to. Same decision loop as Workshop 1, different transport.

Workshop 1 custom tool

This workshop's MCP tool

Lives in

The agent's own agent.py

A separate server process/service

Reusable across agents?

No - copy-paste only

Yes - any MCP client can connect

Transport

Direct Python function call

stdio (local) or HTTP (remote)

Deployment

Ships with the agent

Its own Cloud Run service, own IAM

Finish Workshop 1 first (or at least its one-time environment setup) - adk --version should already work and your Gemini backend should already be exported. If you don't still have that shell session open, get back into the right folder:

git clone https://github.com/adityajoshi12/ai-workshops/
cd ai-workshops/google-adk
source .venv/bin/activate

The real, runnable code for every step below already exists in this repo, in cloud_run_mcp_server/ and ops_agent/ - the same convention as my_agent/ in Workshop 1. Build it yourself first; peek only if stuck.

Add the extra packages this workshop needs on top of Workshop 1's google-adk:

pip install mcp google-cloud-run google-cloud-logging google-auth

Enable two more APIs beyond the ones from Workshop 1 - this agent will read (never modify) your project's Cloud Run fleet and logs:

gcloud services enable run.googleapis.com logging.googleapis.com

Unlike an agent, an MCP server is a plain Python program - there's no adk create for it. Make the folder yourself:

mkdir cloud_run_mcp_server && cd cloud_run_mcp_server

cloud_run_mcp_server/server.py

import os
from mcp.server.mcpserver import MCPServer
from google.cloud import run_v2

mcp = MCPServer("cloud-run-ops")

@mcp.tool()
def list_cloud_run_services(region: str = "us-central1") -> dict:
    """List Cloud Run services currently deployed in this project and region.

    Args:
        region: GCP region to search, e.g. "us-central1".

    Returns:
        On success: {"status": "ok", "services": [{"name", "url", "last_deployed"}]}
        On failure: {"status": "error", "error_message": "<details>"}
    """
    try:
        project = os.environ["GOOGLE_CLOUD_PROJECT"]
        client = run_v2.ServicesClient()
        parent = f"projects/{project}/locations/{region}"
        services = [
            {
                "name": svc.name.rsplit("/", 1)[-1],
                "url": svc.uri,
                "last_deployed": svc.update_time.isoformat() if svc.update_time else None,
            }
            for svc in client.list_services(parent=parent)
        ]
        return {"status": "ok", "services": services}
    except Exception as e:
        return {"status": "error", "error_message": str(e)}

Same two rules from Workshop 1 apply unchanged: type hints so the schema is correct, and a docstring the model actually reads - MCP tools are read by an LLM exactly the same way a local ADK tool is, the only thing that changed is how the call gets transported.

from google.cloud import logging as gcp_logging

@mcp.tool()
def get_service_logs(service_name: str, limit: int = 20) -> dict:
    """Return the most recent log lines for a given Cloud Run service.

    Args:
        service_name: Cloud Run service name, e.g. "adk-default-service-name".
        limit: Max number of log entries to return (default 20, capped at 50).

    Returns:
        On success: {"status": "ok", "service": "<name>", "logs": ["<line>", ...]}
        On failure: {"status": "error", "error_message": "<details>"}
    """
    try:
        limit = min(limit, 50)
        project = os.environ["GOOGLE_CLOUD_PROJECT"]
        client = gcp_logging.Client(project=project)
        log_filter = (
            f'resource.type="cloud_run_revision" '
            f'resource.labels.service_name="{service_name}"'
        )
        entries = client.list_entries(filter_=log_filter, order_by=gcp_logging.DESCENDING, max_results=limit)
        lines = [str(entry.payload) for entry in entries]
        return {"status": "ok", "service": service_name, "logs": lines}
    except Exception as e:
        return {"status": "error", "error_message": str(e)}


if __name__ == "__main__":
    # Cloud Run injects the port to listen on via $PORT - respect it, or
    # this container fails Cloud Run's startup health check.
    mcp.run(transport="streamable-http", host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

Both tools follow the exact same status/error_message contract as Workshop 1's get_weather - that consistency is what lets the agent's instruction give one universal rule for handling failure, no matter which tool failed.

This is the part that's genuinely new compared to Workshop 1: you can fully test the server before any agent exists. Create a minimal requirements.txt alongside server.py:

mcp
google-cloud-run
google-cloud-logging

Export your project and run it locally:

export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
python server.py

In a second terminal tab, use the MCP Inspector to poke at it without writing any agent code:

npx @modelcontextprotocol/inspector http://localhost:8080/mcp

Open the printed local URL, click List Tools, confirm both list_cloud_run_services and get_service_logs show up with the right argument schemas, then run list_cloud_run_services directly and confirm you get back real services from your project (or an empty list if you haven't deployed anything yet).

Back out to ai-workshops/google-adk/ and scaffold a normal ADK agent exactly like Workshop 1:

cd ..
adk create ops_agent

Drop your Gemini backend into ops_agent/.env (same Option A/B choice as Workshop 1 - nothing about that changes here).

ops_agent/agent.py

import os
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 StreamableHTTPServerParams

MCP_SERVER_URL = os.environ.get("MCP_SERVER_URL", "http://localhost:8080/mcp")

fleet_tools = McpToolset(
    connection_params=StreamableHTTPServerParams(url=MCP_SERVER_URL),
)

root_agent = Agent(
    model="gemini-3.5-flash",
    name="cloud_run_ops_agent",
    description="Answers questions about the Cloud Run services deployed in this project.",
    instruction=(
        "You are an SRE assistant for a Google Cloud project. Use "
        "list_cloud_run_services to see what is deployed, and "
        "get_service_logs to inspect recent activity for one service. "
        "Never guess a service's URL, deploy time, or log contents - "
        "always call a tool. If a tool returns status 'error', explain "
        "the error to the user in plain language instead of retrying blindly."
    ),
    tools=[fleet_tools],
)

Notice tools=[fleet_tools] takes the whole toolset, not individual functions - ADK expands it into every tool the server advertises at connection time. Add a fifth tool to the server later and the agent picks it up with zero code changes on the agent side, which is the entire point of the decoupling.

Two terminal tabs, both from ai-workshops/google-adk/:

Tab 1 - MCP server:

export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
cd cloud_run_mcp_server && python server.py

Tab 2 - agent:

export MCP_SERVER_URL="http://localhost:8080/mcp"
adk web --allow_origins "regex:https://.*\.cloudshell\.dev"

Pick ops_agent in the Web Preview and ask: "What Cloud Run services are deployed in this project?" Open the trace panel - you'll see the model call list_cloud_run_services exactly like a local tool call in Workshop 1, except this one crossed a process boundary to get there. Follow up with "Show me the last 10 log lines for <one of the services it just listed>" and confirm get_service_logs fires with that service name as the argument.

This is a plain HTTP service, not an agent, so it uses gcloud run deploy directly instead of adk deploy cloud_run. Add a Dockerfile next to server.py:

cloud_run_mcp_server/Dockerfile

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY server.py .
CMD ["python", "server.py"]

Deploy it without --allow-unauthenticated - this server can read your project's Cloud Run fleet and logs, so only the agent (and you, for testing) should be able to reach it:

cd cloud_run_mcp_server

gcloud run deploy mcp-server \
  --source . \
  --region=us-central1 \
  --no-allow-unauthenticated \
  --set-env-vars=GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)

Grant the service's own runtime identity permission to actually read that data - by default that's the project's compute service account:

PROJECT_NUMBER=$(gcloud projects describe $(gcloud config get-value project) --format='value(projectNumber)')
SERVICE_ACCOUNT="${PROJECT_NUMBER}-compute@developer.gserviceaccount.com"

gcloud projects add-iam-policy-binding $(gcloud config get-value project) \
  --member="serviceAccount:${SERVICE_ACCOUNT}" --role="roles/run.viewer"

gcloud projects add-iam-policy-binding $(gcloud config get-value project) \
  --member="serviceAccount:${SERVICE_ACCOUNT}" --role="roles/logging.viewer"

Note the printed URL, e.g. https://mcp-server-XXXXXXXXXX.us-central1.run.app, and append /mcp to it for the next step.

An unauthenticated Cloud Run service is reachable by anyone who finds the URL. Instead of a shared secret, Cloud Run supports Google-signed ID tokens: the caller proves its own service-account identity, and the receiving service checks it at the platform level, before your code even runs.

flowchart LR U[You / curl] -->|HTTPS| AgentSvc[Cloud Run: ops-agent] AgentSvc -->|"ID token + Streamable HTTP"| MCPSvc[Cloud Run: mcp-server] MCPSvc --> RunAPI[Cloud Run Admin API] MCPSvc --> LogAPI[Cloud Logging API]
View diagram source
flowchart LR
  U[You / curl] -->|HTTPS| AgentSvc[Cloud Run: ops-agent]
  AgentSvc -->|"ID token + Streamable HTTP"| MCPSvc[Cloud Run: mcp-server]
  MCPSvc --> RunAPI[Cloud Run Admin API]
  MCPSvc --> LogAPI[Cloud Logging API]

Update the agent to mint an ID token scoped to the MCP server's URL and send it as a header:

ops_agent/agent.py (replace the toolset setup)

import google.auth.transport.requests
import google.oauth2.id_token

def _mcp_auth_headers(audience: str) -> dict:
    auth_request = google.auth.transport.requests.Request()
    token = google.oauth2.id_token.fetch_id_token(auth_request, audience)
    return {"Authorization": f"Bearer {token}"}

fleet_tools = McpToolset(
    connection_params=StreamableHTTPServerParams(
        url=MCP_SERVER_URL,
        headers=_mcp_auth_headers(MCP_SERVER_URL.rsplit("/mcp", 1)[0]),
    ),
)

For this to work locally too, authenticate your own Cloud Shell session as a principal that's allowed to call the MCP server:

gcloud auth application-default login
export MCP_SERVER_URL="https://mcp-server-XXXXXXXXXX.us-central1.run.app/mcp"

gcloud run services add-iam-policy-binding mcp-server \
  --region=us-central1 \
  --member="user:$(gcloud config get-value account)" \
  --role="roles/run.invoker"

Re-run adk web locally and confirm the same two prompts from the previous step still work, now against the deployed MCP server instead of localhost.

Same shape as Workshop 1, plus the one new env var:

cd ../ops_agent

adk deploy cloud_run ops_agent -- \
  --region=us-central1 \
  --set-env-vars=MCP_SERVER_URL="https://mcp-server-XXXXXXXXXX.us-central1.run.app/mcp",GOOGLE_API_KEY=YOUR_GEMINI_API_KEY,GOOGLE_GENAI_USE_VERTEXAI=FALSE

Grant the agent's own runtime service account permission to invoke the MCP server - the same run.invoker binding you gave yourself above, now for the agent's identity:

gcloud run services add-iam-policy-binding mcp-server \
  --region=us-central1 \
  --member="serviceAccount:${SERVICE_ACCOUNT}" \
  --role="roles/run.invoker"
export SERVICE_URL="https://adk-default-service-name-XXXXXXXXXX.us-central1.run.app"

curl -X POST "$SERVICE_URL/apps/ops_agent/users/u_123/sessions/s_1" \
  -H "Content-Type: application/json" -d '{}'

curl -X POST "$SERVICE_URL/run" \
  -H "Content-Type: application/json" \
  -d '{
    "appName": "ops_agent",
    "userId": "u_123",
    "sessionId": "s_1",
    "newMessage": {
      "role": "user",
      "parts": [{"text": "What Cloud Run services are deployed, and are any of them erroring?"}]
    }
  }'

If you still have services running from Workshop 1 or 2, this is the payoff moment - the agent should list them by name, then call get_service_logs on whichever one you follow up about, all through a completely separate service it never bundles any code from.

403 from the MCP server: the caller's identity is missing the run.invoker binding on mcp-server - re-check the add-iam-policy-binding command matches the exact service account the agent runs as (gcloud run services describe ops_agent shows its service account).

Tools never show up / empty tool list: confirm MCP_SERVER_URL includes the trailing /mcp path, and that the MCP server process is actually running (gcloud run services describe mcp-server shows a healthy revision).

list_cloud_run_services

returns an empty list unexpectedly: double-check region matches where your Workshop 1/2 services actually deployed - run_v2.ServicesClient.list_services only searches one region per call.

401 after the agent has been running a while: the ID token expired - see the earlier warning about refreshing per request rather than once at startup.

Both tools here only read data - there's no delete_service or restart_service exposed over MCP, on purpose. An MCP server is reachable by any client that authenticates to it, which makes it a wider blast radius than a tool buried in one agent's own code. Keep destructive operations out of a shared tool server entirely, or gate them behind an explicit human-approval step - never behind "the LLM decided to."

The real test of MCP's interoperability promise is connecting to a server you didn't write. Add a second McpToolset to ops_agent pointed at a public MCP server (for example the official GitHub MCP server) alongside fleet_tools, and give the agent an instruction covering both. If it correctly picks the right tool for "what services are deployed" versus "any open issues on my repo," you've proven the whole point of the protocol: your agent code didn't need to know anything about either server's implementation.

gcloud run services delete adk-default-service-name --region=us-central1
gcloud run services delete mcp-server --region=us-central1

Google ADK MCP Tools DocsModel Context Protocol SpecContinue to Workshop 4: A2A CommunicationBack to Workshop 2: Multi-Agent Systems