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:

What you'll do
- Uncontained baseline: Watch
UnsafeLocalCodeExecutorexpose your Cloud Shell files (.envincluded) and outbound internet to model-written Python so you see what in-process execution puts at risk. - Layer 1 (Code sandbox): Move execution to
AgentEngineSandboxCodeExecutorso 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
SkillToolsetsoload_skill_resourcepulls formatting instructions into context only when requested, keeping normal turns lean. - Layer 2 (Agent Identity): Deploy with
--agent-identity, grantroles/run.invokeronly on privatewallet-toolboxso the agent holds zero BigQuery roles itself, and remove project-wideroles/aiplatform.userso 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.
- 1. Open the Google Cloud Console and click Select a project in the top bar.
- 2. Click New project.

- 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.

- 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.

- 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.

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 |
| Root ADK agent ( |
| Fixed BigQuery tools ( |
| 330 transactions in |
| Five-stage provisioning script and readiness check. |
| Principal lookup, sandbox warm-up, engine teardown, and local Toolbox helper. |
| Step catch-up scripts ( |
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:

💻 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 | Why up front |
| Verifies preinstalled | Ensures consistent |
| Enables nine APIs ( | Required across BigQuery, Cloud Run, Agent Runtime, IAM, and traces. |
| Seeds | Provides customer data plus an off-limits dataset for IAM verification. |
| Creates | Local |
| Deploys | 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) connectsMcpToolsettoTOOLBOX_URL(127.0.0.1:5000locally) and runs generated Python in-process viaUnsafeLocalCodeExecutor, with noSkillToolsetwired yet.mcp-toolbox/tools.yaml: Exposes only two parameterizedSELECTtools onwallet_insights(get_monthly_spendingandget_transactions), so the model passes typed arguments instead of writing raw BigQuery SQL.data/seed.sql: Creates bothwallet_insights(cust_0001's spending rows) andwallet_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 forspending-insightsso lateragents-cli deployruns 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:

💻 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:

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 (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):

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

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 |
|
|
Filesystem | Host working directory ( | Isolated directory with none of your files. |
Network egress | Full outbound internet access. | Blocked; external DNS lookups and |
Generated files | Text output only; PNGs stay on host disk. | Returns |
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 (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>


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:
nameanddescriptioninSKILL.mdfrontmatter forlist_skillsdiscovery. - L2 Instructions:
SKILL.mdbody, loaded viaload_skillwhen triggered. - L3 Resources: Files under
references/,assets/, orscripts/, loaded on demand viaload_skill_resource:

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):

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:

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:
- Search for
deploymentsand select Deployments (Product page · Agent Platform):

- Click spending-insights on Deployments on Agent Runtime:

- Open the Playground tab:

🌐 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:

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.invokeronwallet-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 byagents-cliby 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 automaticroles/aiplatform.agentDefaultAccessgroup 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:

💻 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/browserthroughroles/serviceusage.serviceUsageConsumer): The Agent Identity keeps only baseline telemetry and discovery roles, withroles/aiplatform.userremoved and zero project-wide Cloud Run or BigQuery roles. - Cloud Run service scope (
role: roles/run.invoker): The agent'sprincipal://...can invokewallet-toolboxalone, not other Cloud Run services in the project. - BigQuery dataset scope (
1onwallet_insights,0onwallet_risk): IAM is scoped per dataset inside BigQuery instead of project-wide, sotoolbox-saappears onwallet_insights(1ACL match) and has zero access towallet_risk(0matches).

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:
- Session conversation: Verify user prompts, tool calls (
list_skills), and replies are readable alongside total latency and token counts:

- 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 ..., andexecute_tool ...:

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 withopentelemetry-instrumentation-google-genai==0.7b1sogenerate_contentspans honorSPAN_AND_EVENT.

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

/skills

/model

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.
Option 1: Delete the project (recommended)
💻 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
UnsafeLocalCodeExecutorexposes host files,.envsecrets, and outbound network access. - How
AgentEngineSandboxCodeExecutorblocks host-file and network access in/home/bardwhile returning generated charts as ADK artifacts. - How
SkillToolsetloadsSKILL.mdmetadata, instructions, andreferences/templates incrementally viaload_skill_resourceso idle skills do not bloat every turn's context. - How deploying with
--agent-identity, scopingroles/run.invokerto privatewallet-toolbox(backed bytoolbox-sa), and removing project-wideroles/aiplatform.userkeeps 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
- Agent Runtime Code Execution Overview
- ADK Code Execution on Agent Runtime
- Agent Identity on Agent Runtime
- Google Cloud Agent Identity Overview
- Skills for ADK Agents
- ADK Observability and Cloud Trace
- MCP Toolbox Configuration
- Antigravity CLI Documentation
- Google Cloud Skills and Developer Plugin
- Starter Repository