Deploy, Contain, Observe: Least-Privilege ADK Agents on Agent Runtime, from Sandbox to Trace

1. Before you begin

Moving an AI agent from a local prototype to production takes more than putting it behind a cloud endpoint. Local defaults leave wide gaps across identity, execution, context, and telemetry. A shared account with broad project roles can reach unrelated datasets or modify other agents, while in-process Python execution exposes host files and outbound networks. Stuffing every workflow into the system prompt bloats each turn, and unverified traces either hide multi-hop failures or leak sensitive prompts into logs. Production agents isolate generated code, load skills on demand, scope workload identity to a single backend, and verify every hop in traces.

What you'll build

These patterns apply to any agent that calls internal services, loads specialized workflows, or runs generated code. You will harden, deploy, and observe a Cymbal Wallet spending-insights agent on Agent Runtime with Agent Development Kit (ADK) and gemini-3.5-flash-lite, reading BigQuery data through MCP Toolbox:

Architecture from Cloud Shell development in modules 0 to 3 to deployed Agent Runtime execution with code sandbox, Agent Identity, private Cloud Run MCP Toolbox, and Trace view in modules 4 to 5

What you'll do

  • Uncontained baseline: Watch UnsafeLocalCodeExecutor expose your Cloud Shell files (.env included) and outbound internet to model-written Python so you see what in-process execution puts at risk.
  • Layer 1 (Code sandbox): Move execution to AgentEngineSandboxCodeExecutor so generated Python cannot read host files or reach external networks, returning charts safely as ADK artifacts.
  • On-demand skills: Package a four-section report template with SkillToolset so load_skill_resource pulls formatting instructions into context only when requested, keeping normal turns lean.
  • Layer 2 (Agent Identity): Deploy with --agent-identity, grant roles/run.invoker only on private wallet-toolbox so the agent holds zero BigQuery roles itself, and remove project-wide roles/aiplatform.user so the agent cannot modify or delete other agents in your project.
  • Trace observability: Inspect model and tool spans in the Agent Runtime console to verify every hop while weighing the data-exposure risk of enabling prompt and response content capture.
  • Agentic log inspection (optional): Equip Antigravity CLI (agy) with Agents CLI skills and the Google Cloud Developer plugin to reconstruct your deployed agent's latest conversation without hand-writing log or trace queries.

What you'll need

  • A Google Cloud account with billing enabled.
  • Comfort with Python, gcloud, and terminal commands.

2. Set up your environment

Create a dedicated Google Cloud project, clone the starter repository in Cloud Shell, configure your project, provision the lab resources, and smoke-test the local agent in ADK Web.

Create a Google Cloud project

Create a dedicated project for this codelab in the Google Cloud Console so your billing account links automatically and cleanup stays isolated.

Google Cloud Console top bar highlighting Select a project (1) and New project (2)

  • 3. Enter a Project name (for example, new-lab-project). Cloud Console automatically generates a globally unique Project ID. If prompted, select an active Billing account and leave the default Parent resource (or choose your organization or folder).
  • 4. Click Create.

New Project form highlighting the Project name field (3) and Create button (4)

  • 5. Wait for project creation to finish, then click the Notifications bell icon in the top bar.
  • 6. Click Select Project to switch into your new project.

Notifications panel highlighting the bell icon (5) and Select Project button (6)

  • 7. Click the project selector in the top bar (Select a project or your new project name).
  • 8. Copy the generated ID (for example, new-lab-project-515707) to use in Cloud Shell.

Select a project dialog highlighting the project selector (7) and the generated Project ID (8)

Open Cloud Shell

Open Cloud Shell in your browser (with both the editor and terminal panes enabled) and click Authorize if prompted:

Set up your working directory

💻 Terminal: Clone the starter repository and open it as your workspace:

git clone https://github.com/alphinside/adk-agent-runtime-deployment.git && \
  cd adk-agent-runtime-deployment && \
  cloudshell workspace .

If the terminal pane is hidden after the browser tab reloads, open View -> Terminal.

The repository includes the starter agent, seed data, and helper scripts that automate baseline setup to save time. Each step walks through the relevant commands inside those scripts as you go:

Path

Purpose

spending_agent/agent.py

Root ADK agent (gemini-3.5-flash-lite), code executor config, toolbox_headers, and agent_engine() lookup.

mcp-toolbox/tools.yaml

Fixed BigQuery tools (get_monthly_spending, get_transactions) used locally and on Cloud Run.

data/seed.sql

330 transactions in wallet_insights, plus wallet_risk.risk_scores (off-limits to the agent).

scripts/setup.sh & scripts/check.sh

Five-stage provisioning script and readiness check.

scripts/engine.py & scripts/toolbox.sh

Principal lookup, sandbox warm-up, engine teardown, and local Toolbox helper.

solution/ & scripts/cleanup.sh

Step catch-up scripts (2-sandbox.sh to 4-identity.sh) and full resource cleanup.

Configure your terminal

💻 Terminal: List your projects and copy the project ID you just created:

gcloud projects list

💻 Terminal: Open configure_terminal.sh:

cloudshell edit configure_terminal.sh

📄 Editor (configure_terminal.sh): Paste this script, replace YOUR_PROJECT_ID with your project ID, and save:

#!/bin/bash
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
gcloud config set project "$GOOGLE_CLOUD_PROJECT"
export REGION=us-central1
echo "$GOOGLE_CLOUD_PROJECT"

💻 Terminal: Load the variables into your current shell:

source configure_terminal.sh

Confirm your project ID appears in yellow in the prompt:

Active project on terminal

💻 Terminal: Verify billing is enabled (billingEnabled: true; otherwise link an account in Cloud Console Billing):

gcloud billing projects describe "$GOOGLE_CLOUD_PROJECT"

💻 Terminal: Create .env from .env.example with your active project ID and verify its contents:

cp .env.example .env
sed -i "s/your-project-id/$GOOGLE_CLOUD_PROJECT/g" .env
cat .env

Provision lab infrastructure

Because the first Agent Runtime deploy and initial sandbox creation take a few minutes, scripts/setup.sh provisions them up front in five stages:

Stage

What scripts/setup.sh creates

Why up front

1/5 Agents CLI

Verifies preinstalled agents-cli >= 1.12.0.

Ensures consistent --agent-identity deploy behavior.

2/5 APIs

Enables nine APIs (aiplatform, bigquery, cloudresourcemanager, cloudtrace, iam, logging, run, secretmanager, telemetry).

Required across BigQuery, Cloud Run, Agent Runtime, IAM, and traces.

3/5 Data

Seeds wallet_insights (spending data) and wallet_risk (restricted risk scores).

Provides customer data plus an off-limits dataset for IAM verification.

4/5 MCP Toolbox

Creates toolbox-sa (reads wallet_insights only), deploys private wallet-toolbox on Cloud Run, installs Python dependencies (uv sync), and starts local Toolbox on 127.0.0.1:5000.

Local adk web uses 127.0.0.1:5000 (as you); deployed agent calls wallet-toolbox.

5/5 Agent Runtime

Deploys spending-insights with --agent-identity and warms one code sandbox (scripts/engine.py warm).

Makes your first sandbox run finish in seconds and turns later deploys into fast in-place updates.

💻 Terminal: Provision the lab infrastructure (about 5 minutes) and verify readiness:

scripts/setup.sh && scripts/check.sh

Inspect the starter agent while setup runs

While scripts/setup.sh runs in the terminal, open these files in the Cloud Shell Editor explorer above it to see your starting baseline:

  • spending_agent/agent.py: root_agent (gemini-3.5-flash-lite) connects McpToolset to TOOLBOX_URL (127.0.0.1:5000 locally) and runs generated Python in-process via UnsafeLocalCodeExecutor, with no SkillToolset wired yet.
  • mcp-toolbox/tools.yaml: Exposes only two parameterized SELECT tools on wallet_insights (get_monthly_spending and get_transactions), so the model passes typed arguments instead of writing raw BigQuery SQL.
  • data/seed.sql: Creates both wallet_insights (cust_0001's spending rows) and wallet_risk.risk_scores (an internal table that neither the agent nor MCP Toolbox should ever read).
  • agents-cli-manifest.yaml: Pins the Agent Runtime deployment config for spending-insights so later agents-cli deploy runs update the same instance in place.

When setup finishes in the terminal, confirm the closing summary ends with READY:

What setup created, and where the lab uses it:
  wallet_insights            the agent's data, read through MCP Toolbox in every module
  wallet_risk                data nothing may read; module 4 checks that toolbox-sa can't
  toolbox-sa                 MCP Toolbox's own identity, reads wallet_insights only
  wallet-toolbox             private MCP Toolbox on Cloud Run; the agent calls it from module 4
  Toolbox on 127.0.0.1:5000  runs as you, for adk web in modules 0 to 3
  spending-insights          Agent Runtime instance with its own Agent Identity; module 2's
                             sandbox runs under it, module 4 deploys into it

Setup is done. Run scripts/check.sh to confirm, then uv run adk web.
READY

Start and smoke-test the local agent

At the starting point, adk web and the local MCP Toolbox both run in Cloud Shell as your user account:

Starting request flow where ADK agent and local MCP Toolbox run in Cloud Shell as you with neither sandbox nor Agent Identity active yet

💻 Terminal: Start ADK Web on port 8000:

uv run adk web --port 8000 --allow_origins "*"

Click Web Preview -> Preview on port 8000 (if 8000 is in use, pass a different --port above and use Change port), then select spending_agent from the top-left dropdown.

🌐 ADK Web (spending_agent, + New Session): Ask for your October 2026 total:

I'm cust_0001. How much did I spend in October 2026?

Verify get_monthly_spending runs for cust_0001 (2026-10), Python sums the categories, and the reply reports $727.28:

ADK web UI session showing get_monthly_spending, Python summation, and the $727.28 October 2026 spending breakdown

Leave adk web running for the next step.

3. Test uncontained code execution

The starter agent runs generated Python with UnsafeLocalCodeExecutor. Test what model-written code can access when it executes inside the agent's own process.

How the starter runs locally

Stage 4 of scripts/setup.sh installed the Python environment and started the local MCP Toolbox under your Cloud Shell credentials, while UnsafeLocalCodeExecutor executes every Python block directly in your workspace folder.

🔍 Reference only (scripts/setup.sh, already executed; do not copy or run):

uv sync --quiet
scripts/toolbox.sh start

See it break

🌐 ADK Web (spending_agent, + New Session): Ask for a spending chart and list the current directory:

I'm cust_0001. Chart my spending by category for October 2026. At the end, print the current working directory and the files in it, so I know where the PNG went.

Inspect the code Output in Events:

Current Working Directory: /home/<your-user>/adk-agent-runtime-deployment
Files in Directory: ['data', 'spending_agent', '.env', 'tests', 'agents-cli-manifest.yaml', 'deployment_metadata.json', ..., 'spending_october_2026.png', ...]

The script listed every file in your workspace, including .env:

ADK web UI output from UnsafeLocalCodeExecutor listing the Cloud Shell workspace directory including .env

🌐 ADK Web (spending_agent, + New Session): Ask for a chart using a font downloaded from GitHub:

I'm cust_0001. Chart my spending by category for October 2026 in the Roboto font. Download it from https://github.com/google/fonts/raw/main/ofl/roboto/Roboto%5Bwdth,wght%5D.ttf and register it with matplotlib.

In Events, urllib.request.urlretrieve downloads Roboto.ttf (488,584 bytes) straight into your starter folder and finishes with Succeeded (if GitHub returns a transient 504 Gateway Time-out, retry once; even 504 proves outbound internet access):

ADK web UI showing generated Python downloading Roboto.ttf from GitHub with urllib.request.urlretrieve

Neither chart appears in chat because UnsafeLocalCodeExecutor returns text only and writes PNGs to the host disk:

Request flow with UnsafeLocalCodeExecutor where generated Python runs inside the agent process with full access to workspace files and outbound internet

In-process code execution creates two exposures:

  • Host filesystem and credentials: Generated scripts read and write the agent's directory (.env, source files) and inherit its ambient credentials.
  • Unrestricted network egress: Generated scripts can pull external payloads or send data out to arbitrary endpoints.

4. Contain code in an Agent Runtime sandbox

Switch the agent to AgentEngineSandboxCodeExecutor so generated Python runs inside an isolated Agent Runtime sandbox while adk web keeps running in Cloud Shell.

How Agent Runtime code sandboxes work

Agent Runtime code execution runs generated code in an isolated sandbox under your spending-insights instance, which scripts/setup.sh deployed and pre-warmed in stage 5.

🔍 Reference only (scripts/setup.sh, already executed; do not copy or run):

# Deploy the spending-insights Agent Runtime instance
agents-cli deploy --project="$P" --no-confirm-project --agent-identity \
  --update-env-vars="TOOLBOX_URL=$TOOLBOX_CLOUD_URL"

# Pre-warm one code sandbox so your first sandbox run finishes in seconds
uv run python scripts/engine.py warm

agent_engine() in spending_agent/agent.py resolves the instance ID from deployment_metadata.json in Cloud Shell (or GOOGLE_CLOUD_AGENT_ENGINE_ID once deployed):

Capability

UnsafeLocalCodeExecutor

AgentEngineSandboxCodeExecutor

Filesystem

Host working directory (.env exposed).

Isolated directory with none of your files.

Network egress

Full outbound internet access.

Blocked; external DNS lookups and pip install fail.

Generated files

Text output only; PNGs stay on host disk.

Returns stdout, stderr, and generated files (up to 100 MB) as chat artifacts.

Session state

Stateless per block.

Persists Python variables across turns in a session (up to 14 days TTL).

Fix it

💻 Terminal: Open spending_agent/agent.py:

cloudshell edit spending_agent/agent.py

📄 Editor (spending_agent/agent.py, 1/2, executor import): Replace the UnsafeLocalCodeExecutor import:

from google.adk.code_executors.agent_engine_sandbox_code_executor import (
    AgentEngineSandboxCodeExecutor,
)

📄 Editor (spending_agent/agent.py, 2/2, code_executor on root_agent): Replace UnsafeLocalCodeExecutor(code_block_delimiters=PYTHON_FENCE) after code_executor= and save:

AgentEngineSandboxCodeExecutor(
    agent_engine_resource_name=agent_engine(),
    code_block_delimiters=PYTHON_FENCE,
),

💻 Terminal: Restart adk web:

uv run adk web --port 8000 --allow_origins "*"

Check that it works

🌐 ADK Web (spending_agent, + New Session): Rerun the working-directory prompt:

I'm cust_0001. Chart my spending by category for October 2026. At the end, print the current working directory and the files in it, so I know where the PNG went.

Expected code Output:

Current working directory: /home/bard
Files in directory: ['october_2026_spending_by_category.png']

Saved artifacts:
`october_2026_spending_by_category.png`

The script sees only /home/bard and the new PNG, which now renders inline in chat as an artifact:

ADK web UI showing /home/bard with only the generated chart and rendering the PNG inline in chat as an artifact

🌐 ADK Web (spending_agent, + New Session): Rerun the GitHub font prompt:

I'm cust_0001. Chart my spending by category for October 2026 in the Roboto font. Download it from https://github.com/google/fonts/raw/main/ofl/roboto/Roboto%5Bwdth,wght%5D.ttf and register it with matplotlib.

Because outbound DNS and network access are blocked in the sandbox, the download fails and the chart falls back to the default font:

<urlopen error [Errno -3] Temporary failure in name resolution>

ADK web UI showing Temporary failure in name resolution when attempting to download Roboto.ttf inside the sandbox, followed by fallback chart code

Layer 1 active: generated Python executes in the Agent Runtime sandbox with no network access and an isolated /home/bard folder

5. Add an on-demand reporting skill

Putting every specialized report template into the root system prompt bloats every turn's context. Package a monthly report as an ADK skill (SkillToolset, Experimental) so the model loads its format file only when asked for a report.

How ADK skills load incrementally

SkillToolset loads skill content in three levels:

  • L1 Metadata: name and description in SKILL.md frontmatter for list_skills discovery.
  • L2 Instructions: SKILL.md body, loaded via load_skill when triggered.
  • L3 Resources: Files under references/, assets/, or scripts/, loaded on demand via load_skill_resource:

Request flow with SkillToolset showing the model calling load_skill and load_skill_resource to load references/report-format.md before querying data and charting in the sandbox

Create the skill and wire SkillToolset

💻 Terminal: Create the skill folder and open SKILL.md:

mkdir -p spending_agent/skills/spending-report/references
cloudshell edit spending_agent/skills/spending-report/SKILL.md

📄 Editor (spending_agent/skills/spending-report/SKILL.md): Paste and save:

---
name: spending-report
description: Formats a customer's monthly spending report. Use it when a customer asks for a spending report, or a summary of one month.
---

# Monthly spending report

Load `references/report-format.md` and follow it, section by section, in the
order it gives. Every amount comes from the tools.

💻 Terminal: Open references/report-format.md:

cloudshell edit spending_agent/skills/spending-report/references/report-format.md

📄 Editor (spending_agent/skills/spending-report/references/report-format.md): Paste the four-section template and save:

# Monthly spending report format

Write the report with these four headings, in this order.

## Summary

One line: the month, the total spent in USD, and the number of transactions.

## Top categories

The three largest categories, largest first, one line each: the category and
its total in USD.

## Chart

A bar chart of the month's spending by category, saved as a PNG file. Title
it "<Month> <Year> spending by category".

## One saving tip

One tip drawn from this customer's own transactions that month. Name the
merchant or category, and how much the customer would have saved.

💻 Terminal: Open spending_agent/agent.py:

cloudshell edit spending_agent/agent.py

📄 Editor (spending_agent/agent.py, 1/2, top imports): Add the skill imports alongside the existing google.adk imports:

from google.adk.skills import load_skill_from_dir
from google.adk.tools.skill_toolset import SkillToolset

📄 Editor (spending_agent/agent.py, 2/2, tools list on root_agent): Add SkillToolset below McpToolset(...), inside tools=[...] and save:

SkillToolset(
    skills=[
        load_skill_from_dir(
            Path(__file__).parent / "skills" / "spending-report"
        )
    ],
),

💻 Terminal: Restart adk web:

uv run adk web --port 8000 --allow_origins "*"

Check that it works

🌐 ADK Web (spending_agent, + New Session): Request your October 2026 spending report:

I'm cust_0001. Give me my monthly spending report for October 2026.

Confirm list_skills, load_skill, load_skill_resource, get_monthly_spending, and get_transactions run in Events, and verify all four report sections ($727.28 across 12 transactions; Shopping $429.15, Bills $117.05, Dining $94.17; inline chart artifact; Saffron Table $73.01 saving tip):

ADK web UI showing the October 2026 bar chart artifact and the four-section monthly spending report

6. Lock down access with Agent Identity

Up to now, adk web and local MCP Toolbox ran in Cloud Shell as you. Switch to the deployed spending-insights agent on Agent Runtime, which runs under its own Agent Identity and calls private wallet-toolbox on Cloud Run:

Transition from local Cloud Shell execution running as you in modules 0 to 3 to deployed Agent Runtime execution with Agent Identity and private Cloud Run MCP Toolbox in module 4 onward

How Agent Identity and toolbox-sa separate privileges

Toolbox's service account (toolbox-sa)

Stage 4 of scripts/setup.sh granted toolbox-sa read access on wallet_insights only (leaving wallet_risk unreadable) and deployed wallet-toolbox with --no-allow-unauthenticated.

🔍 Reference only (scripts/setup.sh, already executed; do not copy or run):

# Grant job execution and dataset-scoped DCL (Data Control Language) read on wallet_insights only
gcloud iam service-accounts create toolbox-sa --project="$P" \
  --display-name="MCP Toolbox for the spending-insights lab"
gcloud projects add-iam-policy-binding "$P" --member="serviceAccount:$TOOLBOX_SA" \
  --role=roles/bigquery.jobUser --condition=None
bq --project_id="$P" --location="$REGION" query --nouse_legacy_sql \
  "GRANT \`roles/bigquery.dataViewer\` ON SCHEMA \`$P.wallet_insights\` TO \"serviceAccount:$TOOLBOX_SA\""

# Deploy private MCP Toolbox on Cloud Run running as toolbox-sa
gcloud run deploy "$TOOLBOX_SERVICE" --project="$P" --region="$REGION" \
  --image="$TOOLBOX_IMAGE" \
  --service-account="$TOOLBOX_SA" \
  --no-allow-unauthenticated \
  --set-secrets="/app/tools.yaml=$TOOLBOX_SECRET:latest" \
  --set-env-vars="GOOGLE_CLOUD_PROJECT=$P,REGION=$REGION" \
  --args="--config=/app/tools.yaml,--address=0.0.0.0,--port=8080"

The agent's own Agent Identity

Stage 5's agents-cli deploy ... --agent-identity created a SPIFFE-backed principal://... identity (24-hour auto-rotated X.509 certificate) tied to this single Agent Runtime resource: never shared across workloads, non-impersonatable, and unable to export long-lived keys. To call private Cloud Run, toolbox_headers in spending_agent/agent.py mints an OIDC ID token.

🔍 Reference only (spending_agent/agent.py, already in starter code; do not copy or paste):

def toolbox_headers(_context) -> dict[str, str]:
    # Deployed, TOOLBOX_URL is a private Cloud Run service. Cloud Run accepts an
    # ID token for that URL, minted here for whatever identity the agent runs as.
    # Under Agent Identity, google-auth would otherwise mint a certificate-bound
    # token, which Cloud Run rejects with a 401.
    token = google.oauth2.id_token.fetch_id_token(
        google.auth.transport.requests.Request(), TOOLBOX_URL, bind_id_token=False
    )
    return {"Authorization": f"Bearer {token}"}

Deploy your updated agent and inspect its identity

💻 Terminal: Redeploy spending-insights in place with --agent-identity and OpenTelemetry capture flags (under 3 minutes), then print its principal:

set -a && source .env && set +a
TOOLBOX_URL=$(gcloud run services describe wallet-toolbox --region="$REGION" --format="value(status.url)")
agents-cli deploy --project="$GOOGLE_CLOUD_PROJECT" --agent-identity --update-env-vars="TOOLBOX_URL=$TOOLBOX_URL,OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental,ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS=true,OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_AND_EVENT"
uv run python scripts/engine.py principal

Expected output (trimmed):

  Agent Identity: Enabled
...
✅ Deployment successful!
Agent Identity: principal://agents.global.org-<org>.system.id.goog/resources/aiplatform/projects/<number>/locations/us-central1/reasoningEngines/<id>
principal://agents.global.org-<org>.system.id.goog/resources/aiplatform/projects/<number>/locations/us-central1/reasoningEngines/<id>

See it break in the Agent Runtime Playground

Open the deployed agent in the Google Cloud Console:

  1. Search for deployments and select Deployments (Product page · Agent Platform):

Cloud Console search bar highlighting Deployments under Agent Platform

  1. Click spending-insights on Deployments on Agent Runtime:

Deployments on Agent Runtime listing spending-insights with Identity and Telemetry collection enabled

  1. Open the Playground tab:

spending-insights detail page highlighting the Playground tab and Copy identity button

🌐 Playground (spending-insights, + New session): Ask about October 2026 dining spending:

I'm cust_0001. How much did I spend on dining in October 2026?

Without roles/run.invoker on wallet-toolbox, Cloud Run returns 403 and ADK starts spending_agent with zero data tools. After 90 to 140 seconds, the model either reports missing lookup tools or hits RESOURCE_NOT_FOUND while probing skill files for data:

Agent Runtime Playground showing a skill resource lookup error and reporting that transaction lookup tools are unavailable before granting run.invoker

Fix it: grant narrow invoker access and remove aiplatform.user

Apply two IAM changes to the Agent Identity principal:

  • Narrow Cloud Run invoker grant (roles/run.invoker on wallet-toolbox): Allows the agent to call this single Cloud Run service (MCP Toolbox), with zero BigQuery roles on the agent itself.
  • Project-level role removal (roles/aiplatform.user): Granted by agents-cli by default, this role lets an agent modify or delete other agents in the project. Removing it keeps Gemini, sessions, and sandboxes working via the project's automatic roles/aiplatform.agentDefaultAccess group binding.

💻 Terminal: Update both IAM bindings and wait 2 minutes for Cloud Run IAM propagation:

PRINCIPAL=$(uv run python scripts/engine.py principal)
gcloud run services add-iam-policy-binding wallet-toolbox --region="$REGION" --member="$PRINCIPAL" --role=roles/run.invoker
gcloud projects remove-iam-policy-binding "$GOOGLE_CLOUD_PROJECT" --member="$PRINCIPAL" --role=roles/aiplatform.user --condition=None
echo "Waiting 2 minutes for IAM propagation..."
sleep 120

Check that it works

🌐 Playground (spending-insights, + New session): After the wait finishes, re-send the dining question:

I'm cust_0001. How much did I spend on dining in October 2026?

Confirm get_monthly_spending runs in Events and returns $94.17 across 4 transactions:

Agent Runtime Playground showing get_monthly_spending succeeding and reporting $94.17 on dining in October 2026

💻 Terminal: Verify the principal's project roles, wallet-toolbox invoker policy, and toolbox-sa dataset access:

gcloud projects get-iam-policy "$GOOGLE_CLOUD_PROJECT" --flatten="bindings[].members" --filter="bindings.members:$PRINCIPAL" --format="value(bindings.role)"
gcloud run services get-iam-policy wallet-toolbox --region="$REGION"
bq show --format=prettyjson "$GOOGLE_CLOUD_PROJECT:wallet_insights" | grep -c toolbox-sa
bq show --format=prettyjson "$GOOGLE_CLOUD_PROJECT:wallet_risk" | grep -c toolbox-sa

Expected output:

roles/browser
roles/cloudapiregistry.viewer
roles/logging.logWriter
roles/monitoring.metricWriter
roles/serviceusage.serviceUsageConsumer
bindings:
- members:
  - principal://agents.global.org-.../reasoningEngines/<id>
  role: roles/run.invoker
...
1
0

These four checks verify least privilege from project scope down to individual BigQuery datasets:

  • Project scope (roles/browser through roles/serviceusage.serviceUsageConsumer): The Agent Identity keeps only baseline telemetry and discovery roles, with roles/aiplatform.user removed and zero project-wide Cloud Run or BigQuery roles.
  • Cloud Run service scope (role: roles/run.invoker): The agent's principal://... can invoke wallet-toolbox alone, not other Cloud Run services in the project.
  • BigQuery dataset scope (1 on wallet_insights, 0 on wallet_risk): IAM is scoped per dataset inside BigQuery instead of project-wide, so toolbox-sa appears on wallet_insights (1 ACL match) and has zero access to wallet_risk (0 matches).

Layer 2 active: the deployed agent authenticates with its Agent Identity to call private wallet-toolbox only, while toolbox-sa reads wallet_insights and cannot read wallet_risk

7. Inspect spans and content capture in Traces

Agent Runtime emits OpenTelemetry spans for every agent run, model call, and tool call. Trigger a full report on the deployed agent and inspect its trace.

Generate a deployed report trace

💻 Terminal: Send the October 2026 report prompt to the deployed agent (or run it in Playground, noting inline PNG artifacts render only in adk web):

AGENT_URL="https://$REGION-aiplatform.googleapis.com/reasoningEngines/v1/$(jq -r .remote_agent_runtime_id deployment_metadata.json)/api"
agents-cli run "I'm cust_0001. Give me my monthly spending report for October 2026." --mode adk --url "$AGENT_URL"

Confirm the reply returns all four report sections ($727.28 across 12 transactions and the $73.01 Saffron Table tip).

Walk the session and span timeline

On the spending-insights console page, open the Traces tab and select your latest session:

  1. Session conversation: Verify user prompts, tool calls (list_skills), and replies are readable alongside total latency and token counts:

Agent Runtime session details view showing Session conversation with readable input messages, tool calls, and assistant replies

  1. Trace Timeline: Click a trace ID and select Timeline to inspect POST /api/stream_reasoning_engine -> invoke_workflow spending_agent -> invoke_agent spending_agent -> MCP send ..., generate_content ..., and execute_tool ...:

Agent Runtime trace Timeline view showing nested workflow, agent, MCP, generate_content, and execute_tool spans with the Conversation tab below

Understand content-capture flags and span limits

agents-cli deploy defaults content capture to off (NO_CONTENT / false), and redeploying without the flags resets them. Your redeploy enabled three variables together:

  • ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS=true: Captures payloads on ADK workflow, agent, and tool spans.
  • OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_AND_EVENT: Captures model inputs and outputs on GenAI spans.
  • OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental: Required with opentelemetry-instrumentation-google-genai==0.7b1 so generate_content spans honor SPAN_AND_EVENT.

Full deployed request flow showing spans captured on invoke_agent, generate_content, and execute_tool while sandbox code execution emits no span of its own

Note that ADK emits no dedicated span for callbacks, plugins, or sandbox Python runs.

8. (Optional) Debugging with Antigravity CLI

Instead of writing Cloud Logging filters or Cloud Trace queries by hand, equip Antigravity CLI (agy, preinstalled in Cloud Shell) with Agents CLI skills and the Google Cloud Developer plugin to inspect your deployed agent's latest conversation.

Install skills and configure the Developer plugin

💻 Terminal: Enable the Developer Knowledge API and check agy:

gcloud services enable developerknowledge.googleapis.com
agy --help

💻 Terminal: Link the agents-cli skills (including google-agents-cli-observability) into Antigravity CLI:

agents-cli setup --skip-auth --workspace

💻 Terminal: Install the google-cloud-developer plugin:

agy plugin install https://github.com/google/skills/plugins/cloud/google-cloud-developer

Expected output:

[ok] google-cloud-developer
...
skills : 5 installed
rules : 1 installed (google-cloud-discovery)
mcpServers : 1 installed

💻 Terminal: Add your X-Goog-User-Project header to the plugin's MCP config while preserving its existing X-Goog-Api-Client header:

set -a && source .env && set +a
python3 -c '
import json, os
from pathlib import Path

p = Path.home() / ".gemini/config/plugins/google-cloud-developer/mcp_config.json"
d = json.loads(p.read_text())
d["mcpServers"]["developer-knowledge"].setdefault("headers", {})["X-Goog-User-Project"] = os.environ["GOOGLE_CLOUD_PROJECT"]
p.write_text(json.dumps(d, indent=2) + "\n")
'

Launch Antigravity CLI and select Gemini 3.8 Flash

💻 Terminal: Enable ADC authentication (AGY_ADC_AUTH=true) and launch agy interactively with --dangerously-skip-permissions so log and trace queries run without manual prompts during this lab:

export AGY_ADC_AUTH=true
agy --dangerously-skip-permissions

If prompted on first launch, complete sign-in, pick a theme, and choose Yes, I trust this folder.

🤖 Antigravity CLI: Check that google-cloud-developer_developer-knowledge and google-agents-cli-observability are loaded, then switch /model to Gemini 3.8 Flash (Gemini 3.8 Flash, medium effort):

/mcp

developer knowledge mcp

/skills

cloud developer plugins

/model

model selection

Reconstruct the last conversation from Cloud Logging

🤖 Antigravity CLI: Ask agy to read your deployed agent's latest conversation from logs:

I have a deployed agent on Agent Runtime. Find the relevant skill to read its logs and show me its last conversation.

Wait while agy runs the read-only gcloud and python3 commands and prints the skill, engine details, and reconstructed transcript:

### Relevant Skill
- google-agents-cli-observability
- Resource Type: aiplatform.googleapis.com/ReasoningEngine
- Log Name: projects/<PROJECT_ID>/logs/aiplatform.googleapis.com%2Freasoning_engine_stdout
- Inference Events: labels."event.name"="gen_ai.client.inference.operation.details"

### Deployed Agent Details
- Agent Name: spending_agent
- Reasoning Engine ID: <id> (us-central1)
- Conversation ID: <conversation-id>

### Last Conversation Transcript
- User: I'm cust_0001. Give me my monthly spending report for October 2026.
- Tool calls: list_skills -> load_skill("spending-report") ->
  load_skill_resource("references/report-format.md") ->
  get_monthly_spending("cust_0001", "2026-10") ->
  get_transactions("cust_0001", "2026-10-01", "2026-10-31")
- Agent reply: Summary ($727.28 across 12 transactions), Top categories
  (Shopping $429.15, Bills $117.05, Dining $94.17), Chart, and One saving tip
  (Saffron Table, $73.01 across two visits).

Inspect per-span trace timings (optional)

🤖 Antigravity CLI: Ask for per-call durations from Cloud Trace (fetches cloud-trace-querying via finding-google-skills and runs its trace query script in /tmp):

I want to see what my deployed agent did in its last conversation: the user's question, each model and tool call with how long it took, and the answer. Its ID is in deployment_metadata.json. Use whichever Google skill fits for reading traces.

Verify the output reports the trace ID, invoke_agent latency, MCP and generate_content timings, token counts, execute_tool outputs, and a span tree. Press Ctrl+D twice to exit agy.

9. Clean up

Delete the project or individual resources when you finish so your project does not incur ongoing charges.

💻 Terminal: Delete the project and everything inside it:

gcloud projects delete "$GOOGLE_CLOUD_PROJECT" --quiet

Option 2: Delete individual resources

💻 Terminal: Stop local Toolbox and delete spending-insights, its IAM bindings, wallet-toolbox, wallet-toolbox-tools, toolbox-sa, and both BigQuery datasets:

cd ~/adk-agent-runtime-deployment
scripts/cleanup.sh

10. Wrap up

Your spending-insights agent now executes generated Python inside a networkless Agent Runtime sandbox, loads reporting templates on demand, authenticates to private Cloud Run MCP Toolbox under its own least-privilege Agent Identity, and emits inspectable OpenTelemetry traces.

What you've learned

  • Why running generated code in-process with UnsafeLocalCodeExecutor exposes host files, .env secrets, and outbound network access.
  • How AgentEngineSandboxCodeExecutor blocks host-file and network access in /home/bard while returning generated charts as ADK artifacts.
  • How SkillToolset loads SKILL.md metadata, instructions, and references/ templates incrementally via load_skill_resource so idle skills do not bloat every turn's context.
  • How deploying with --agent-identity, scoping roles/run.invoker to private wallet-toolbox (backed by toolbox-sa), and removing project-wide roles/aiplatform.user keeps the agent out of BigQuery and prevents it from modifying or deleting other agents in your project.
  • How to verify every model and tool hop in Agent Runtime traces (in the console or with Antigravity CLI) while treating content-captured traces and logs like a sensitive data store.

Bonus challenge

Test session state persistence inside the sandbox: start adk web, ask cust_0001 to chart October 2026 spending by category, and send a follow-up in the same session: "Turn the same numbers into a pie chart. Reuse the variables from your last script; don't define the data again." Confirm in Events that the second script reuses the in-memory lists with zero BigQuery calls.

What's next

Pick one agent in your own Google Cloud project and audit its execution and IAM footprint with the teammate who owns your cloud security policies: move in-process code execution to AgentEngineSandboxCodeExecutor, deploy with --agent-identity, drop project-wide roles/aiplatform.user, and scope roles/run.invoker to the single backend service it calls. You can reproduce or adapt this lab anytime from adk-agent-runtime-deployment, and I would love to hear how that audit goes on your own workload.

Happy tinkering!

Reference docs