1. 准备工作
将 AI 智能体从本地原型推向生产环境,不仅仅是将其部署到 Cloud Endpoints。本地默认设置在身份、执行、上下文和遥测方面存在很大差距。拥有广泛项目角色的共享账号可以访问不相关的数据集或修改其他代理,而进程内 Python 执行会暴露主机文件和出站网络。将所有工作流塞入系统提示会导致每次对话都变得臃肿,而未经核实的跟踪记录要么会隐藏多跳故障,要么会将敏感提示泄露到日志中。生产代理会隔离生成的代码、按需加载技能、将工作负载身份限定在单个后端,并验证跟踪记录中的每个跃点。
构建内容
这些模式适用于调用内部服务、加载专用工作流或运行生成代码的任何智能体。您将使用智能体开发套件 (ADK) 和 gemini-3.5-flash-lite 在 Agent Runtime 上强化、部署和观察 Cymbal Wallet 支出分析智能体,并通过 MCP Toolbox 读取 BigQuery 数据:

您将执行的操作
- 无容器基准:观察
UnsafeLocalCodeExecutor如何向模型编写的 Python 脚本公开您的 Cloud Shell 文件(包括.env)和出站互联网访问权限,以便您了解进程内执行会带来哪些风险。 - 第 1 层(代码沙盒):将执行操作移至
AgentEngineSandboxCodeExecutor,这样生成的 Python 代码就无法读取 Hosts 文件或访问外部网络,从而以 ADK 工件的形式安全地返回图表。 - 按需技能:将四部分报告模板与
SkillToolset打包在一起,这样load_skill_resource仅在收到请求时才会将格式设置指令纳入上下文,从而使正常对话保持精简。 - 第 2 层(智能体身份):使用
--agent-identity进行部署,仅向私有wallet-toolbox授予roles/run.invoker,以便智能体本身不持有任何 BigQuery 角色,并移除项目级roles/aiplatform.user,以便智能体无法修改或删除项目中的其他智能体。 - 跟踪可观测性:在 Agent Runtime 控制台中检查模型和工具 span,以验证每个跃点,同时权衡启用提示和回答内容捕获功能的数据泄露风险。
- 智能体日志检查(可选):为 Antigravity CLI (
agy) 配备 Agents CLI 技能和 Google Cloud Developer 插件,无需手动编写日志或跟踪查询,即可重构已部署智能体的最新对话。
所需条件
- 已启用结算功能的 Google Cloud 账号。
- 熟悉 Python、
gcloud和终端命令。
2. 设置您的环境
创建一个专用的 Google Cloud 云项目,在 Cloud Shell 中克隆起始代码库,配置项目,预配实验资源,并在 ADK Web 中对本地智能体进行冒烟测试。
创建 Google Cloud 项目
在 Google Cloud 控制台中为此 Codelab 创建一个专用项目,以便自动关联结算账号,并确保清理工作独立进行。
- 1. 打开 Google Cloud 控制台,然后点击顶部栏中的选择项目。
- 2. 点击新建项目。

- 3. 输入项目名称(例如
new-lab-project)。Cloud 控制台会自动生成一个全局唯一的项目 ID。如果系统提示,请选择一个有效的结算账号,并保留默认的父级资源(或选择您的组织或文件夹)。 - 4. 点击创建。

- 5. 等待项目创建完成,然后点击顶部栏中的通知铃铛图标。
- 6. 点击选择项目,切换到新项目。

- 7. 点击顶部栏中的项目选择器(选择项目或新项目名称)。
- 8. 复制生成的 ID(例如
new-lab-project-515707),以便在 Cloud Shell 中使用。

打开 Cloud Shell
在浏览器中打开 Cloud Shell(同时启用编辑器和终端窗格),并在系统提示时点击授权:
设置工作目录
💻 终端:克隆起始代码库,并将其作为工作区打开:
git clone https://github.com/alphinside/adk-agent-runtime-deployment.git && \
cd adk-agent-runtime-deployment && \
cloudshell workspace .
如果浏览器标签页重新加载后终端窗格处于隐藏状态,请依次打开视图 -> 终端。
该代码库包含起始智能体、种子数据和辅助脚本,可自动完成基准设置,从而节省时间。每个步骤都会逐步介绍这些脚本中的相关命令:
路径 | 用途 |
| 根 ADK 智能体 ( |
| 修复了在本地和 Cloud Run 上使用的 BigQuery 工具( |
|
|
| 五阶段预配脚本和就绪性检查。 |
| 主体查找、沙盒预热、引擎拆解和本地 Toolbox 辅助程序。 |
| 步骤追赶脚本( |
配置终端
💻 终端:列出您的项目,并复制您刚刚创建的项目 ID:
gcloud projects list
💻 终端:打开 configure_terminal.sh:
cloudshell edit configure_terminal.sh
📄 编辑器 (configure_terminal.sh):粘贴此脚本,将 YOUR_PROJECT_ID 替换为您的项目 ID,然后保存:
#!/bin/bash
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"
gcloud config set project "$GOOGLE_CLOUD_PROJECT"
export REGION=us-central1
echo "$GOOGLE_CLOUD_PROJECT"
💻 终端:将变量加载到当前 shell 中:
source configure_terminal.sh
确认您的项目 ID 在提示中以黄色显示:

💻 终端:验证是否已启用结算功能(billingEnabled: true;否则,请在 Cloud 控制台结算中关联账号):
gcloud billing projects describe "$GOOGLE_CLOUD_PROJECT"
💻 终端:使用您的有效项目 ID 从 .env.example 创建 .env,并验证其内容:
cp .env.example .env
sed -i "s/your-project-id/$GOOGLE_CLOUD_PROJECT/g" .env
cat .env
预配实验基础设施
由于首次部署 Agent Runtime 和创建初始沙盒需要几分钟时间,因此 scripts/setup.sh 会分五个阶段预先预配这些资源:
阶段 |
| 为何要预先付费 |
| 验证预安装的 | 确保 |
| 启用 9 个 API( | BigQuery、Cloud Run、Agent Runtime、IAM 和跟踪记录都需要此权限。 |
| 种子 | 提供客户数据以及用于 IAM 验证的受限数据集。 |
| 创建 | 本地 |
| 使用 | 让您的首次沙盒运行在几秒钟内完成,并将后续部署转换为快速就地更新。 |
💻 终端:预配实验基础设施(大约需要 5 分钟),并验证是否已准备就绪:
scripts/setup.sh && scripts/check.sh
在设置运行期间检查启动代理
当 scripts/setup.sh 在终端中运行时,在 Cloud Shell 编辑器资源管理器中打开这些文件,查看初始基准:
spending_agent/agent.py:root_agent(gemini-3.5-flash-lite) 将McpToolset连接到TOOLBOX_URL(本地为127.0.0.1:5000),并通过UnsafeLocalCodeExecutor在进程中运行生成的 Python,尚未连接SkillToolset。mcp-toolbox/tools.yaml:仅在wallet_insights上公开两个参数化SELECT工具(get_monthly_spending和get_transactions),因此模型会传递类型化实参,而不是编写原始 BigQuery SQL。data/seed.sql:创建wallet_insights(cust_0001的支出行)和wallet_risk.risk_scores(智能体和 MCP Toolbox 都不应读取的内部表)。agents-cli-manifest.yaml:固定spending-insights的 Agent Runtime 部署配置,以便后续agents-cli deploy运行就地更新同一实例。
在终端中完成设置后,确认结束摘要以 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
启动并冒烟测试本地智能体
在初始阶段,adk web 和本地 MCP Toolbox 都会在 Cloud Shell 中以您的用户账号身份运行:

💻 终端:在端口 8000 上启动 ADK Web:
uv run adk web --port 8000 --allow_origins "*"
依次点击网页预览 -> 在端口 8000 上预览(如果 8000 正在使用中,请在上方传递其他 --port,并使用更改端口),然后从左上角的下拉菜单中选择 spending_agent。
🌐 ADK Web(spending_agent,+ 新会话):询问 2026 年 10 月的总支出:
I'm cust_0001. How much did I spend in October 2026?
验证 get_monthly_spending 是否针对 cust_0001 (2026-10) 运行,Python 会对类别求和,回复会报告 $727.28:

让 adk web 保持运行状态,以便执行下一步。
3. 测试未包含的代码执行
初学者智能体使用 UnsafeLocalCodeExecutor 运行生成的 Python 代码。测试模型编写的代码在智能体自身进程中执行时可以访问哪些内容。
starter 如何在本地运行
scripts/setup.sh 的第 4 阶段安装了 Python 环境,并使用您的 Cloud Shell 凭证启动了本地 MCP 工具箱,而 UnsafeLocalCodeExecutor 会直接在工作区文件夹中执行每个 Python 代码块。
🔍 仅供参考(scripts/setup.sh,已执行;请勿复制或运行):
uv sync --quiet scripts/toolbox.sh start
查看损坏情况
ADK Web (spending_agent, + New Session):请求支出图表并列出当前目录:
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.
检查事件中的代码输出:
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', ...]
该脚本列出了工作区中的每个文件,包括 .env:

🌐 ADK Web(spending_agent,+ 新会话):要求使用从 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.
在 Events(事件)中,urllib.request.urlretrieve 会将 Roboto.ttf(488,584 字节)直接下载到您的 starter 文件夹中,并以 Succeeded 结束(如果 GitHub 返回暂时性 504 Gateway Time-out,请重试一次;即使 504 也证明了出站互联网访问权限):

这两个图表都不会显示在对话中,因为 UnsafeLocalCodeExecutor 仅返回文本,并将 PNG 写入主机磁盘:

进程内代码执行会产生两个风险:
- 主机文件系统和凭据:生成的脚本会读取和写入智能体的目录(
.env、源文件),并继承其环境凭据。 - 不受限制的网络出站流量:生成的脚本可以拉取外部载荷或将数据发送到任意端点。
4. 在 Agent Runtime 沙盒中包含代码
将智能体切换到 AgentEngineSandboxCodeExecutor,以便生成的 Python 代码在隔离的 Agent Runtime 沙盒中运行,而 adk web 则继续在 Cloud Shell 中运行。
Agent Runtime 代码沙盒的工作原理
Agent Runtime 代码执行会在您的 spending-insights 实例下的隔离沙盒中运行生成的代码,该实例由 scripts/setup.sh 在第 5 阶段部署并预热。
🔍 仅供参考(scripts/setup.sh,已执行;请勿复制或运行):
# 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
spending_agent/agent.py 中的 agent_engine() 会解析 Cloud Shell 中 deployment_metadata.json 的实例 ID(或部署后的 GOOGLE_CLOUD_AGENT_ENGINE_ID):
能力 |
|
|
文件系统 | 主机工作目录( | 不含任何文件的隔离目录。 |
网络出站流量 | 完整的出站互联网访问权限。 | 已屏蔽;外部 DNS 查找和 |
生成的文件 | 仅输出文本;PNG 文件保留在主机磁盘上。 | 以对话工件的形式返回 |
会话状态 | 每个块都是无状态的。 | 在会话的多轮交互中持久保留 Python 变量(TTL 最长为 14 天)。 |
解决问题
💻 终端:打开 spending_agent/agent.py:
cloudshell edit spending_agent/agent.py
编辑器 (spending_agent/agent.py, 1/2, executor import):替换 UnsafeLocalCodeExecutor 导入:
from google.adk.code_executors.agent_engine_sandbox_code_executor import (
AgentEngineSandboxCodeExecutor,
)
📄 Editor(spending_agent/agent.py,2/2,code_executor,root_agent):将 code_executor= 之后的 UnsafeLocalCodeExecutor(code_block_delimiters=PYTHON_FENCE) 替换为以下内容并保存:
AgentEngineSandboxCodeExecutor(
agent_engine_resource_name=agent_engine(),
code_block_delimiters=PYTHON_FENCE,
),
💻 终端:重启 adk web:
uv run adk web --port 8000 --allow_origins "*"
检查是否生效
🌐 ADK Web(spending_agent,+ 新会话):重新运行工作目录提示:
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.
预期代码输出:
Current working directory: /home/bard Files in directory: ['october_2026_spending_by_category.png'] Saved artifacts: `october_2026_spending_by_category.png`
脚本只能看到 /home/bard 和新的 PNG,后者现在会作为工件在对话中以内嵌方式呈现:

🌐 ADK Web(spending_agent,+ 新会话):重新运行 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.
由于沙盒中阻止了出站 DNS 和网络访问,下载会失败,图表会回退到默认字体:
<urlopen error [Errno -3] Temporary failure in name resolution>


5. 添加按需报告技能
将每个专用报告模板都放入根系统提示中,会导致每轮对话的上下文变得臃肿。将月度报告打包为 ADK 技能(SkillToolset,实验性),以便模型仅在被要求提供报告时才加载其格式文件。
ADK 技能如何增量加载
SkillToolset 会加载三个级别的技能内容:
- L1 元数据:
SKILL.md前置元数据中的name和description,用于list_skills探索。 - L2 Instructions:
SKILL.mdbody, loaded viaload_skillwhen triggered. - L3 资源:
references/、assets/或scripts/下的文件,通过load_skill_resource按需加载:

创建技能并关联 SkillToolset
💻 终端:创建技能文件夹并打开 SKILL.md:
mkdir -p spending_agent/skills/spending-report/references
cloudshell edit spending_agent/skills/spending-report/SKILL.md
📄 编辑器 (spending_agent/skills/spending-report/SKILL.md):粘贴并保存:
---
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.
💻 终端:打开 references/report-format.md:
cloudshell edit spending_agent/skills/spending-report/references/report-format.md
📄 编辑器 (spending_agent/skills/spending-report/references/report-format.md):粘贴包含四个部分的模板并保存:
# 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.
💻 终端:打开 spending_agent/agent.py:
cloudshell edit spending_agent/agent.py
📄 Editor (spending_agent/agent.py, 1/2, top imports):在现有 google.adk 导入旁边添加技能导入:
from google.adk.skills import load_skill_from_dir
from google.adk.tools.skill_toolset import SkillToolset
📄 编辑器(spending_agent/agent.py,2/2,root_agent 上的 tools 列表):在 tools=[...] 内的 McpToolset(...), 下方添加 SkillToolset,然后保存:
SkillToolset(
skills=[
load_skill_from_dir(
Path(__file__).parent / "skills" / "spending-report"
)
],
),
💻 终端:重启 adk web:
uv run adk web --port 8000 --allow_origins "*"
检查是否生效
🌐 ADK Web(spending_agent,+ 新会话):请求 2026 年 10 月的支出报告:
I'm cust_0001. Give me my monthly spending report for October 2026.
确认 list_skills、load_skill、load_skill_resource、get_monthly_spending 和 get_transactions 在事件中运行,并验证所有四个报告部分(12 笔交易共 $727.28;购物 $429.15、账单 $117.05、餐饮 $94.17;内嵌图表工件;Saffron Table $73.01 省钱提示):

6. 使用代理身份锁定访问权限
到目前为止,adk web 和本地 MCP Toolbox 都是以您的身份在 Cloud Shell 中运行的。切换到 Agent Runtime 上部署的 spending-insights 智能体,该智能体以自己的智能体身份运行,并调用 Cloud Run 上的私有 wallet-toolbox:

智能体身份和 toolbox-sa 如何分离权限
Toolbox 的服务账号 (toolbox-sa)
scripts/setup.sh 的第 4 阶段仅向 toolbox-sa 授予了对 wallet_insights 的读取权限(使 wallet_risk 无法读取),并使用 --no-allow-unauthenticated 部署了 wallet-toolbox。
🔍 仅供参考(scripts/setup.sh,已执行;请勿复制或运行):
# 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"
智能体自身的智能体身份
第 5 阶段的 agents-cli deploy ... --agent-identity 创建了一个由 SPIFFE 支持的 principal://... 身份(24 小时自动轮替的 X.509 证书),该身份与此单一 Agent Runtime 资源绑定:绝不跨工作负载共享、不可冒充,且无法导出长期密钥。为了调用私有 Cloud Run,spending_agent/agent.py 中的 toolbox_headers 会生成一个 OIDC ID 令牌。
🔍 仅供参考(spending_agent/agent.py,已在起始代码中;请勿复制或粘贴):
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}"}
部署更新后的智能体并检查其身份
💻 终端:使用 --agent-identity 和 OpenTelemetry 捕获标志就地重新部署 spending-insights(不到 3 分钟),然后输出其主账号:
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
预期输出(已修剪):
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>
在 Agent Runtime Playground 中查看其故障情况
在 Google Cloud 控制台中打开已部署的代理:
- 搜索
deployments,然后选择部署(产品页面 · Agent Platform):

- 点击 Agent Runtime 上的部署中的 spending-insights:

- 打开实验室标签页:

🌐 Playground(spending-insights,+ 新会话):询问 2026 年 10 月的餐饮支出:
I'm cust_0001. How much did I spend on dining in October 2026?
如果 wallet-toolbox 上没有 roles/run.invoker,Cloud Run 会返回 403,ADK 会在没有数据工具的情况下启动 spending_agent。90 到 140 秒后,模型要么报告缺少查找工具,要么在探测技能文件以获取数据时达到 RESOURCE_NOT_FOUND:

解决方法:授予范围较窄的调用方访问权限,并移除 aiplatform.user
对代理身份主账号应用两项 IAM 更改:
- 缩小 Cloud Run Invoker 授权范围(
roles/run.invoker针对wallet-toolbox):允许智能体调用此单一 Cloud Run 服务 (MCP Toolbox),而无需为智能体本身授予任何 BigQuery 角色。 - 项目级角色移除 (
roles/aiplatform.user):此角色默认由agents-cli授予,可让代理修改或删除项目中的其他代理。移除该角色后,Gemini、会话和沙盒将通过项目的自动roles/aiplatform.agentDefaultAccess群组绑定继续运行。
💻 终端:更新两个 IAM 绑定,并等待 2 分钟,让 Cloud Run IAM 传播:
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
检查是否生效
🌐 Playground(spending-insights,+ 新会话):等待结束后,重新发送用餐问题:
I'm cust_0001. How much did I spend on dining in October 2026?
确认 get_monthly_spending 在事件中运行,并在 4 笔交易中返回 $94.17:

💻 终端:验证主账号的项目角色、wallet-toolbox 调用方政策和 toolbox-sa 数据集访问权限:
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
预期输出:
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
这四项检查会验证从项目范围到单个 BigQuery 数据集的最小权限:
- 项目范围(
roles/browser到roles/serviceusage.serviceUsageConsumer):代理身份仅保留基准遥测和发现角色,移除了roles/aiplatform.user,并且没有项目范围的 Cloud Run 或 BigQuery 角色。 - Cloud Run 服务范围 (
role: roles/run.invoker):代理的principal://...只能调用wallet-toolbox,而不能调用项目中的其他 Cloud Run 服务。 - BigQuery 数据集范围(
wallet_insights上的1,wallet_risk上的0):IAM 的范围是 BigQuery 中的每个数据集,而不是整个项目,因此toolbox-sa会出现在wallet_insights上(1ACL 匹配),并且对wallet_risk的访问权限为零(0匹配)。

7. 在跟踪记录中检查 span 和内容捕获
Agent Runtime 会为每次智能体运行、模型调用和工具调用发出 OpenTelemetry span。触发已部署智能体的完整报告,并检查其跟踪记录。
生成已部署的报告跟踪记录
💻 终端:向已部署的智能体发送 2026 年 10 月报告提示(或在 Playground 中运行,请注意,内嵌 PNG 工件仅在 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"
确认回复中包含所有四个报告部分(12 笔交易共 $727.28,以及 $73.01 Saffron Table 小费)。
浏览会话和 span 时间轴
在 spending-insights 控制台页面上,打开跟踪记录标签页,然后选择最新会话:
- 会话对话:验证用户提示、工具调用 (
list_skills) 和回答是否可读,以及总延迟时间和词元数量:

- 跟踪时间轴:点击跟踪 ID,然后选择时间轴,以检查
POST /api/stream_reasoning_engine->invoke_workflow spending_agent->invoke_agent spending_agent->MCP send ...、generate_content ...和execute_tool ...:

了解内容捕获标志和 span 限制
agents-cli deploy 会默认关闭内容捕获功能(NO_CONTENT/false),在不使用这些标志的情况下重新部署会重置这些标志。您的重新部署同时启用了三个变量:
ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS=true:捕获 ADK 工作流、智能体和工具 span 上的载荷。OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_AND_EVENT:捕获生成式 AI span 上的模型输入和输出。OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental:opentelemetry-instrumentation-google-genai==0.7b1必需,以便generate_contentspan 遵循SPAN_AND_EVENT。

请注意,ADK 不会为回调、插件或沙盒 Python 运行发出专用 span。
8. (可选)使用 Antigravity CLI 进行调试
无需手动编写 Cloud Logging 过滤条件或 Cloud Trace 查询,只需为 Antigravity CLI(agy,已预安装在 Cloud Shell 中)配备 Agents CLI 技能和 Google Cloud Developer 插件,即可检查已部署智能体的最新对话。
安装技能并配置开发者插件
💻 终端:启用 Developer Knowledge API 并检查 agy:
gcloud services enable developerknowledge.googleapis.com
agy --help
💻 终端:将 agents-cli skills(包括 google-agents-cli-observability)关联到 Antigravity CLI:
agents-cli setup --skip-auth --workspace
💻 终端:安装 google-cloud-developer 插件:
agy plugin install https://github.com/google/skills/plugins/cloud/google-cloud-developer
预期输出:
[ok] google-cloud-developer ... skills : 5 installed rules : 1 installed (google-cloud-discovery) mcpServers : 1 installed
💻 终端:将 X-Goog-User-Project 标头添加到插件的 MCP 配置中,同时保留其现有的 X-Goog-Api-Client 标头:
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")
'
启动 Antigravity CLI 并选择 Gemini 3.8 Flash
💻 终端:启用 ADC 身份验证 (AGY_ADC_AUTH=true),并使用 --dangerously-skip-permissions 以交互方式启动 agy,以便在本实验期间无需手动提示即可运行日志和跟踪查询:
export AGY_ADC_AUTH=true
agy --dangerously-skip-permissions
如果系统在首次启动时提示,请完成登录,选择一个主题,然后选择是,我信任此文件夹。
🤖 Antigravity CLI:检查 google-cloud-developer_developer-knowledge 和 google-agents-cli-observability 是否已加载,然后将 /model 切换到 Gemini 3.8 Flash(Gemini 3.8 Flash,medium 努力程度):
/mcp

/skills

/model

从 Cloud Logging 重构上一次对话
🤖 Antigravity CLI:让 agy 从日志中读取已部署智能体的最新对话:
I have a deployed agent on Agent Runtime. Find the relevant skill to read its logs and show me its last conversation.
等待 agy 运行只读 gcloud 和 python3 命令,并输出技能、引擎详细信息和重构的转录内容:
### 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).
检查每个 span 的跟踪记录时间(可选)
🤖 Antigravity CLI:请求从 Cloud Trace 获取每次调用的时长(通过 finding-google-skills 提取 cloud-trace-querying,并在 /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.
验证输出是否报告了跟踪记录 ID、invoke_agent 延迟时间、MCP 和 generate_content 时间、词元计数、execute_tool 输出以及 span 树。按 Ctrl+D 两次以退出 agy。
9. 清理
完成后,请删除项目或单个资源,以免项目产生持续费用。
选项 1:删除项目(推荐)
💻 终端:删除项目及其中的所有内容:
gcloud projects delete "$GOOGLE_CLOUD_PROJECT" --quiet
选项 2:删除单个资源
💻 终端:停止本地 Toolbox 并删除 spending-insights、其 IAM 绑定、wallet-toolbox、wallet-toolbox-tools、toolbox-sa 以及两个 BigQuery 数据集:
cd ~/adk-agent-runtime-deployment
scripts/cleanup.sh
10. 小结
现在,您的 spending-insights 智能体会在无网络的 Agent Runtime 沙盒中执行生成的 Python 代码,按需加载报告模板,使用其自身的最小权限智能体身份向私有 Cloud Run MCP Toolbox 进行身份验证,并发出可检查的 OpenTelemetry 跟踪记录。
您学到的内容
- 为什么在进程内使用
UnsafeLocalCodeExecutor运行生成的代码会暴露主机文件、.env密钥和出站网络访问权限。 AgentEngineSandboxCodeExecutor如何在/home/bard中阻止主机文件和网络访问,同时将生成的图表作为 ADK 工件返回。SkillToolset如何通过load_skill_resource增量加载SKILL.md元数据、指令和references/模板,从而避免闲置技能导致每个轮次的上下文膨胀。- 如何通过使用
--agent-identity进行部署、将roles/run.invoker的范围限定为私有wallet-toolbox(由toolbox-sa提供支持)以及移除项目级roles/aiplatform.user,使代理无法访问 BigQuery,并防止其修改或删除项目中的其他代理。 - 如何在 Agent Runtime 跟踪记录(在控制台中或使用 Antigravity CLI)中验证每个模型和工具跃点,同时将捕获内容的跟踪记录和日志视为敏感数据存储区。
奖励挑战
在沙盒中测试会话状态持久性:启动 adk web,让 cust_0001 按类别绘制 2026 年 10 月的支出图表,并在同一会话中发送后续请求:"Turn the same numbers into a pie chart. Reuse the variables from your last script; don't define the data again."。在事件中确认第二个脚本重用了内存中的列表,且未调用 BigQuery。
后续步骤
在您自己的 Google Cloud 项目中选择一个智能体,并与负责云安全政策的团队成员一起审核其执行情况和 IAM 痕迹:将进程内代码执行迁移到 AgentEngineSandboxCodeExecutor,使用 --agent-identity 进行部署,移除项目级 roles/aiplatform.user,并将 roles/run.invoker 范围限定为它调用的单个后端服务。您可以随时通过 adk-agent-runtime-deployment 重现或调整此实验,我很想了解您在自己的工作负载上进行审核的情况。
祝您探索愉快!