GENAI159
Lab Information
| Lab Manual Last Updated Date |
November 30, 2026 |
| Last Tested Date and Time |
November 30, 2026, 10:16:36 |
| Completion in Last 24 Hours |
61 |
Overview
In this lab, you build and secure a DevOps Assistant Agent using the Google Agent Development Kit (ADK) and Gemini Enterprise Agent Platform.
Specifically, you learn how to design a dual-identity architecture where:
-
The agent acts on its own behalf (Agent Identity): Using a SPIFFE-backed Agent Identity, the agent invokes Auth Manager, stores telemetry, and calls Google Cloud APIs.
-
The agent acts on the user's behalf (User-Delegated Identity): To access external resources such as the Cymbal DevOps Portal, the agent triggers a 3-legged OAuth (3LO) consent flow to securely query tools using the user's credentials.

Prerequisites
This lab pre-provisions the Cymbal DevOps Portal, a self-contained OAuth 2.0 identity provider and DevOps Model Context Protocol (MCP) server running on Cloud Run in your project. No personal external account is required. Once the lab starts, you can find your Cymbal DevOps Portal URL in the lab connection panel (or at ).
Objectives
In this lab, you learn how to perform the following tasks:
- Build an ADK Agent that connects to the Cymbal DevOps Portal Model Context Protocol (MCP) server.
- Update the agent's tool from a static Personal Access Token (PAT) to a 3-legged OAuth (3LO) flow using Google Cloud Auth Manager.
- Deploy the agent securely to Agent Runtime and provision Agent Identity.
- Configure IAM roles to provide the agent's identity access to the token vault on the user's behalf.
- Trace and verify the end-to-end 3LO flow for Auth Manager in Google Cloud.
Setup and requirements
Before you click the Start Lab button
Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources are made available to you.
This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials you use to sign in and access Google Cloud for the duration of the lab.
To complete this lab, you need:
- Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito (recommended) or private browser window to run this lab. This prevents conflicts between your personal account and the student account, which may cause extra charges incurred to your personal account.
- Time to complete the lab—remember, once you start, you cannot pause a lab.
Note: Use only the student account for this lab. If you use a different Google Cloud account, you may incur charges to that account.
How to start your lab and sign in to the Google Cloud console
-
Click the Start Lab button. If you need to pay for the lab, a dialog opens for you to select your payment method.
On the right is the Lab setup pane with the following:
- The Open Google Cloud console button
- The temporary credentials that you must use for this lab
- Other information, if needed, to step through this lab
-
In the Lab Setup section, right-click Open Google Cloud console and select Open link in new window (or alternatively right-click and select Open Link in Incognito Window if you are running the Chrome browser).
The lab spins up resources, and then opens another tab that shows the Sign in page.
Tip: Arrange the tabs in separate windows, side-by-side.
Note: If you see the Choose an account dialog, click Use Another Account.
-
If necessary, copy the Username below and paste it into the Sign in dialog.
{{{user_0.username | "Username"}}}
You can also find the Username in the Lab Setup pane.
-
Click Next.
-
Copy the Password below and paste it into the Welcome dialog.
{{{user_0.password | "Password"}}}
You can also find the Password in the Lab Setup pane.
-
Click Next.
Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials.
Note: Using your own Google Cloud account for this lab may incur extra charges.
-
Click through the subsequent pages:
- Accept the terms and conditions.
- Do not add recovery options or two-factor authentication (because this is a temporary account).
- Do not sign up for free trials.
After a few moments, the Google Cloud console opens in this tab.
Note: To access Google Cloud products and services, click the Navigation menu or type the service or product name in the Search field.
Note: Throughout this lab, you can navigate to Logging > Logs Explorer in the Google Cloud console to inspect application, deployment, and authorization logs if you encounter any issues.
Task 1. Set up the environment
In this task, you set up your Google Cloud Shell development environment and initialize a Python project using uv. Next, you install the agents-cli tool and authenticate your environment to Google Cloud to prepare for agent deployment.
Prepare a Cloud Shell Editor tab
-
Click Activate Cloud Shell (
) in the Google Cloud console title bar.
Note: Alternatively, select the console browser tab and press G, S to open the Cloud Shell terminal.
-
Click Continue.
-
When prompted to authorize Cloud Shell, click Authorize.
-
In the Cloud Shell Terminal toolbar, click the Open in new window button (
).
-
Click the Open Editor pencil icon (
) in the Cloud Shell toolbar to view files.
-
In the Cloud Shell Editor Activity Bar, click the Explorer icon (
) to open your file explorer.
-
Click Open Folder.
-
In the Open Folder dialog, click OK to select your student home directory.
-
Close any additional tutorial or Gemini side panels to maximize space for your code editor.
Throughout the rest of this lab, you can work in this window as your IDE with the Cloud Shell Editor and Cloud Shell Terminal.
Authenticate to Google Cloud and enable APIs
Authenticate to Google Cloud from Cloud Shell to ensure that your environment has the necessary permissions to deploy to Agent Runtime, provision Agent Identity, and configure Auth Manager during this lab:
-
Run the following commands to sign in to your Google Cloud account and configure Application Default Credentials (ADC):
gcloud auth application-default login
gcloud auth login
When prompted, type Y and press ENTER. Click the provided URL to open a new browser window that displays a verification code. Copy the verification code, paste it in response to the Enter verification code: prompt, and press ENTER.
-
Enable the necessary APIs in your Google Cloud project to run this lab. Run the following command in your terminal:
gcloud services enable \
aiplatform.googleapis.com \
iam.googleapis.com \
agentidentity.googleapis.com \
agentidentitycredentials.googleapis.com
Output:
Operation "operations/acat.p2-383622543991-88c76d7c-453b-46dc-b7a2-65227edbd98a" finished successfully.
Install agents CLI and set up the project
-
agents-cli is the command-line tool used to scaffold, manage, test, and deploy ADK agents to Gemini Enterprise Agent Platform. Install it in Cloud Shell:
uvx google-agents-cli@1.5.0 setup
-
Run the following command to verify your installation:
~/.local/bin/agents-cli --help
You should see the CLI's help menu displaying available commands (such as deploy, run, and status).
-
Generate the initial project scaffolding. Start with a local prototype and enhance it later for Agent Runtime deployment:
Note: Version pinning is enforced in the following command to prevent compatibility issues. Leaving packages unpinned pulls the latest stable builds, which might be incompatible with this lab environment.
uvx google-agents-cli@1.5.0 create secure-agent-demo --prototype --yes
cd secure-agent-demo
uv add \
"google-adk[agent-identity,gcp,otel-gcp,mcp]~=2.6.0" \
"google-agents-cli==1.5.0" \
"mcp>=1.24.0,<2.0.0"
Output:
Agents CLI v1.5.0
Info: --agent not specified. Defaulting to 'adk' in auto-approve mode.
Info: Prototype mode: using deployment_target='none'.
> Verifying GCP credentials...
> ✓ Connected to project: qwiklabs-gcp-04-73089dbafae7
✅ Success! Your agent project is ready.
📖 Documentation
README: cat secure-agent-demo/README.md
💡 Tip
Add a deployment target later with: agents-cli scaffold enhance
🚀 Get Started
cd secure-agent-demo && agents-cli install && agents-cli playground
This creates the secure-agent-demo directory containing your foundational agent code, dependencies, and test files.
Task 2. Build and test the agent
In this task, you define the core logic of your DevOps Assistant by configuring its system instructions and the Gemini model in app/agent.py. Additionally, you establish a secure connection to the Cymbal DevOps Portal by creating app/tools.py, which equips your agent with the Model Context Protocol (MCP) toolset for read-only access.
Create the agent
-
In the Cloud Shell Editor, navigate to secure-agent-demo > app > agent.py.
-
Replace the code in the agent.py file with the following:
from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.models import Gemini
from google.genai import types
from app.tools import devops_toolset
import os
import google.auth
_, project_id = google.auth.default()
os.environ["GOOGLE_CLOUD_PROJECT"] = project_id
os.environ["GOOGLE_CLOUD_LOCATION"] = "global"
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
INSTRUCTION = """You are the DevOps Assistant. You help developers list and triage their DevOps issues and pull requests.
Your capabilities: You have a Cymbal DevOps MCP toolset that you can use to perform actions that the user requests.
Rules:
- NEVER write, update, or delete. You are only allowed read access.
- Act on behalf of the signed-in user.
- If a tool returns an authentication or authorization error, guide the user to sign in.
- NEVER fabricate information. Only report real issues returned by tools.
"""
root_agent = Agent(
name="root_agent",
model=Gemini(
model="{{{project_0.startup_script.gemini_flash_model_id | gemini_flash_model_id}}}",
retry_options=types.HttpRetryOptions(attempts=3),
),
instruction=INSTRUCTION,
tools=[devops_toolset()],
)
app = App(
root_agent=root_agent,
name="app",
)
This file defines three key components of the agent:
-
System Instruction (
INSTRUCTION): Sets the persona, scopes the assistant to DevOps triage, and enforces strict safety rules (such as read-only access and guiding users to authenticate if errors occur).
-
Agent Configuration (
root_agent): Instantiates an ADK Agent using the model, configures HTTP retry logic, and equips the agent with the Cymbal DevOps toolset.
-
App Wrapper (
app): Encapsulates the root agent into an ADK App container, making it deployable to Agent Runtime.
Add the Cymbal DevOps MCP tool
-
The agent connects to the Cymbal DevOps Portal via the Model Context Protocol (MCP). Create a new file named tools.py in the app/ folder to register the MCP gateway connection parameters, and copy and paste the following code:
from __future__ import annotations
import os
from google.adk.tools.mcp_tool import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
DEVOPS_MCP_URL = "{{{project_0.startup_script.devops_portal_url | DEVOPS_PORTAL_URL}}}/mcp"
DEVOPS_TOKEN = os.environ.get("DEVOPS_TOKEN", "")
def devops_toolset() -> McpToolset:
"""Returns the McpToolset connecting to the Cymbal DevOps Portal MCP endpoint."""
return McpToolset(
connection_params=StreamableHTTPConnectionParams(
url=DEVOPS_MCP_URL,
headers={
"Authorization": f"Bearer {DEVOPS_TOKEN}",
},
)
)
This function creates a toolset that calls the Cymbal DevOps Portal's MCP server:
-
MCP Toolset (
McpToolset): Dynamically discovers and registers the portal's four read-only DevOps tools (get_user_profile, list_pull_requests, list_issues, and get_pull_request) for the cymbal-infra/agent-platform repository.
-
Connection Parameters (
StreamableHTTPConnectionParams): Points the toolset to the Cymbal DevOps Portal's Streamable HTTP MCP endpoint (/mcp).
-
Authorization Header: Injects
DEVOPS_TOKEN as a Bearer token in the Authorization header.
Test with a Demo PAT (personal access token)
To prototype and test the agent using static credentials without setting up any external account, use the pre-generated Demo Personal Access Token (PAT) provided by the Cymbal DevOps Portal:
-
Open the Cymbal DevOps Portal Developer Settings page in a browser tab at /developers (or copy the Cymbal DevOps Portal URL from the lab connection panel and append /developers).
-
Under Demo Personal Access Token (PAT), click Copy PAT to copy your pre-generated pat_... token.
-
In the Cloud Shell Terminal, replace your_demo_pat_here with the token you copied and export DEVOPS_TOKEN in your environment:
export DEVOPS_TOKEN="your_demo_pat_here"
Note: You can also fetch the Demo PAT directly in Cloud Shell by running curl -s against the portal's /api/pat endpoint at {{{project_0.startup_script.devops_portal_url | DEVOPS_PORTAL_URL | disablehighlight}}}/api/pat.
-
Navigate to the secure-agent-demo folder and start the local ADK playground server:
cd ~/secure-agent-demo
uv run agents-cli playground
If prompted Enable telemetry? [Y/n], type Y and press ENTER.
Note: The server takes a few moments to start. Wait a few minutes before proceeding to the next step.
-
Open the playground interface, and select the app folder from the ADK drop-down list.
-
In the chatbox, run the following prompt and verify that the agent calls the Cymbal DevOps MCP tool and fetches pull requests for cymbal-infra/agent-platform:
Show my recent pull requests.
Output:
Here are your recent pull requests in cymbal-infra/agent-platform:
1. PR #142 — fix: Enforce Cloud Run MemAllocPerProjectRegion max-instances cap
State: open
Summary: Caps max_instance_count and --max-instances to keep regional Cloud Run memory reservations below the 32 GiB sandbox ceiling.
2. PR #139 — feat: Bind SPIFFE Agent Identity to Auth Manager
State: merged
Summary: Grants roles/agentidentity.user to the Agent Runtime SPIFFE principal so delegated 3LO tokens can be retrieved at runtime without static secrets.
3. PR #135 — docs: Update 3LO consent flow architecture guide
State: merged
Summary: Documents the end-to-end /validateUserId nonce verification and credentials:finalize handshake.
-
In the Cloud Shell terminal, press CTRL+C to stop the server.
Task 3. Configure Auth Manager
Although hardcoding static credentials (like a PAT) is convenient for prototyping, it exposes production applications to credential leakage, manual token refresh downtime, and a lack of cloud-native access controls.
To solve this, Google Cloud provides Agent Identity Auth Manager. Agent Identity Auth Manager is a credential vault designed to help protect credentials. It lets agents authenticate using an API key or OAuth client ID and secret, or on behalf of a user through OAuth delegation using end-user access tokens.
Within Auth Manager, you configure auth providers that define the authentication type and credentials for specific third-party applications. The end-to-end Auth Manager workflow operates as follows:

-
Dynamic Consent Interception: When the agent attempts to execute a tool on behalf of a user, the ADK checks Auth Manager for an existing valid credential. If none exists, Auth Manager returns an authorization URL to initiate a 3-legged OAuth (3LO) consent flow.
-
Secure Vault Storage: After the end user authorizes the application, Auth Manager automatically intercepts the OAuth callback and stores the resulting user access and refresh tokens in a secure, Google-managed credential vault.
-
Automated Token Lifecycle: Auth Manager fully manages token expiration and rotation in the background, eliminating the need for manual token refresh logic or downtime.
-
Secret-Free Tool Execution: For subsequent actions, the agent (authenticating via its SPIFFE Agent Identity) dynamically requests the user's delegated access token from Auth Manager at runtime, keeping both client and agent code entirely secret-free.
Configure the Cymbal DevOps Portal as an Auth Provider
-
Run the following command to store the Cloud Shell URL in the environment variable DEV_URL. Copy and save the Cloud Shell URL.
export DEV_URL="https://8501-${WEB_HOST}"
echo $DEV_URL
Output:
https://8501-cs-xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxx.ql-asia-southeast1-xxxx.cloudshell.dev
-
In the Cloud Shell Terminal, run the following gcloud command to create a devops-oauth-provider OAuth auth provider in your Google Cloud project pointing to the Cymbal DevOps Portal's OAuth endpoints:
gcloud alpha agent-identity auth-providers create devops-oauth-provider \
--project="{{{project_0.project_id | PROJECT_ID}}}" \
--location="{{{project_0.default_region | REGION}}}" \
--three-legged-oauth-authorization-url="{{{project_0.startup_script.devops_portal_url | DEVOPS_PORTAL_URL}}}/oauth/authorize" \
--three-legged-oauth-token-url="{{{project_0.startup_script.devops_portal_url | DEVOPS_PORTAL_URL}}}/oauth/token"
-
Run the following command to describe the auth provider and retrieve the created OAuth redirect URL:
gcloud alpha agent-identity auth-providers describe devops-oauth-provider \
--project="{{{project_0.project_id | PROJECT_ID}}}" \
--location="{{{project_0.default_region | REGION}}}"
Output:
authProviderTypeParams:
threeLeggedOauth:
authorizationUrl: {{{project_0.startup_script.devops_portal_url | DEVOPS_PORTAL_URL}}}/oauth/authorize
redirectUrl: https://agentidentitycredentials.googleapis.com/v1/projects/{{{project_0.project_id | PROJECT_ID}}}/locations/{{{project_0.default_region | REGION}}}/authProviders/devops-oauth-provider/oauthcallback
tokenUrl: {{{project_0.startup_script.devops_portal_url | DEVOPS_PORTAL_URL}}}/oauth/token
name: projects/{{{project_0.project_id | PROJECT_ID}}}/locations/{{{project_0.default_region | REGION}}}/authProviders/devops-oauth-provider
state: ENABLED
Look for redirectUrl in the output (for example, https://agentidentitycredentials.googleapis.com/v1/projects/YOUR_PROJECT/locations/REGION/authProviders/devops-oauth-provider/oauthcallback).
Register the OAuth app in the Cymbal DevOps Portal
-
Open the Cymbal DevOps Portal Developer Settings page at /developers.
-
Under Register a New OAuth Application, for Application Name, type DevOps Assistant (or another descriptive name).
-
For Redirect URI, paste the redirectUrl retrieved in the previous step.
-
Click Register application.
-
Under OAuth Client Credentials, copy both the generated Client ID (cymbal_...) and Client Secret.
Update the Auth Provider with credentials
-
Run the following command to update the Auth Provider. Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your respective Client ID and Client Secret:
gcloud alpha agent-identity auth-providers update devops-oauth-provider \
--project="{{{project_0.project_id | PROJECT_ID}}}" \
--location="{{{project_0.default_region | REGION}}}" \
--three-legged-oauth-client-id="YOUR_CLIENT_ID" \
--three-legged-oauth-client-secret="YOUR_CLIENT_SECRET"
Output:
Updated auth provider [devops-oauth-provider].
authProviderTypeParams:
threeLeggedOauth:
authorizationUrl: {{{project_0.startup_script.devops_portal_url | DEVOPS_PORTAL_URL}}}/oauth/authorize
clientId: cymbal_eyJhcHAiOiJEZXZPcHMgQXNzaXN0YW50Ii...
redirectUrl: https://agentidentitycredentials.googleapis.com/v1/projects/{{{project_0.project_id | PROJECT_ID}}}/locations/{{{project_0.default_region | REGION}}}/authProviders/devops-oauth-provider/oauthcallback
tokenUrl: {{{project_0.startup_script.devops_portal_url | DEVOPS_PORTAL_URL}}}/oauth/token
name: projects/{{{project_0.project_id | PROJECT_ID}}}/locations/{{{project_0.default_region | REGION}}}/authProviders/devops-oauth-provider
state: ENABLED
With this step completed, your Google Cloud Auth Manager is now fully configured with your Cymbal DevOps Portal OAuth application credentials, setting up Google Cloud to act as the secure vault that handles consent and token lifecycles.
Click Check my progress to verify the objective.
Configure the Cymbal DevOps Auth Provider
Task 4. Switch PAT token to Auth Manager
Now that the Auth Manager is fully configured, the next step is to update the agent's tool code.
-
In the Cloud Shell Editor, navigate to secure-agent-demo > app > tools.py.
-
Replace the contents of tools.py with the following code:
from __future__ import annotations
import os
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider, GcpAuthProviderScheme
from google.adk.tools.mcp_tool import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
"""1. Register the GCP Auth Provider in the global Credential Manager."""
CredentialManager.register_auth_provider(GcpAuthProvider())
"""2. Set the Auth Provider resource name for your project and region."""
OAUTH_PROVIDER_NAME = f"projects/{{{project_0.project_id | PROJECT_ID}}}/locations/{{{project_0.default_region | REGION}}}/authProviders/devops-oauth-provider"
"""3. Configure the frontend callback URL where the user is redirected after authorizing the Cymbal DevOps Portal."""
OAUTH_CONTINUE_URI = os.environ.get(
"OAUTH_CONTINUE_URI",
"http://localhost:8501/validateUserId"
)
def devops_toolset() -> McpToolset:
"""Returns the McpToolset using 3LO credentials retrieved via GCP Auth Manager."""
auth_scheme = GcpAuthProviderScheme(
name=OAUTH_PROVIDER_NAME,
continue_uri=OAUTH_CONTINUE_URI,
)
return McpToolset(
connection_params=StreamableHTTPConnectionParams(
url="{{{project_0.startup_script.devops_portal_url | DEVOPS_PORTAL_URL}}}/mcp",
),
auth_scheme=auth_scheme,
)
Understand the tool code
This updated code teaches your agent how to use Auth Manager instead of a hardcoded token.
First, CredentialManager.register_auth_provider tells the ADK to manage credentials using Google Cloud. Next, you configure two key settings: OAUTH_PROVIDER_NAME points to your Cymbal DevOps auth provider in the cloud, and OAUTH_CONTINUE_URI tells the browser where to return the user after they log in.
Finally, auth_scheme connects these settings to your Cymbal DevOps toolset. Now, whenever the agent tries to call the Cymbal DevOps Portal, it automatically checks Auth Manager for the user's token. If no token is found, it seamlessly prompts the user to sign in.
Task 5. Deploy agent to Agent Runtime
Now that you have updated the Cymbal DevOps MCP tool to use Auth Manager, the next step is to deploy the agent to Agent Runtime. Deploying the agent to Agent Runtime with the Agent Identity flag provisions a unique SPIFFE ID for the agent.
-
Initialize the deployment configuration for the project by running the following commands in the Cloud Shell terminal:
cd ~/secure-agent-demo
uv run agents-cli scaffold enhance --deployment-target=agent_runtime
uv lock
Output:
Files to add:
+ app/app_utils/reasoning_engine_adapter.py
+ deployment/terraform/shared/completions.sql
+ deployment/terraform/shared/dummy_source.b64
+ deployment/terraform/shared/genai_logs_schema.json
+ deployment/terraform/single-project/apis.tf
+ deployment/terraform/single-project/iam.tf
+ deployment/terraform/single-project/outputs.tf
+ deployment/terraform/single-project/providers.tf
+ deployment/terraform/single-project/service.tf
+ deployment/terraform/single-project/service_outputs.tf
+ deployment/terraform/single-project/storage.tf
+ deployment/terraform/single-project/telemetry.tf
+ deployment/terraform/single-project/telemetry_outputs.tf
+ deployment/terraform/single-project/variables.tf
+ deployment/terraform/single-project/vars/env.tfvars
+ deployment_metadata.json
Dependency changes:
+ Add: google-cloud-aiplatform[evaluation,agent-engines]>=1.156.0,<2.0.0
+ Add: protobuf>=6.31.1,<7.0.0
✓ Keep (yours): google-agents-cli>=1.5.0,<2.0.0
✓ Keep (yours): mcp>=1.24.0,<2.0.0
📦 Creating backup before modification...
Backup created: /home/student_02_df6335d88d34/.agents-cli/backups/secure-agent-demo_20260903_061723
Dependencies updated — run agents-cli install to install the new versions.
Updated: 4 files
Added: 16 files
Removed: 0 files
✅ Enhancement complete!
This command inspects your project structure for ADK compatibility, prepares the underlying container packaging configurations, and generates an agents-cli-manifest.yaml file in your project root pre-populated with default deployment settings.
-
In the Cloud Shell Editor, open the newly created agents-cli-manifest.yaml file and update the region field to to ensure that your agent is deployed in the same region as the auth provider:
Output:
name: secure-agent-demo
acli_version: 1.5.0
agent_directory: app
region: {{{project_0.default_region | REGION}}}
base_template: adk
generated_at: '2026-09-03T05:46:12.168385+00:00'
language: python
create_params:
deployment_target: agent_runtime
cicd_runner: skip
is_a2a: true
agent_gateway: false
agent_guidance_filename: GEMINI.md
-
In the Cloud Shell Editor, navigate to secure-agent-demo > app > app_utils > reasoning_engine_adapter.py and replace its contents with the following code. Replacing this file adds dual async generator iteration (aiter) and nested payload unwrapping ("input" dicts) to prevent streaming crashes during 3LO tool execution:
"""Copyright 2026 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Serve the reasoning_engine ``{class_method, input}`` contract over HTTP.
"""
import inspect
import json
from fastapi import FastAPI, HTTPException, Request, encoders, responses
from vertexai.agent_engines.templates.adk import AdkApp
from app.app_utils import services
def attach_reasoning_engine_routes(app: FastAPI) -> None:
"""Register reasoning_engine routes that dispatch to an AdkApp."""
runtime: AdkApp | None = None
streaming_methods: set[str] = set()
sync_methods: set[str] = set()
def get_runtime() -> AdkApp:
nonlocal runtime, streaming_methods, sync_methods
if runtime is None:
from app.agent import app as adk_app
runtime = AdkApp(
app=adk_app,
session_service_builder=services.get_session_service,
artifact_service_builder=services.get_artifact_service,
)
runtime.set_up()
operations = runtime.register_operations()
streaming_methods = set(operations.get("stream", [])) | set(
operations.get("async_stream", [])
)
sync_methods = set(operations.get("", [])) | set(
operations.get("async", [])
)
return runtime
def resolve_method(class_method: str, *, streaming: bool):
rt = get_runtime()
allowed = streaming_methods if streaming else sync_methods
if class_method not in allowed:
raise HTTPException(
status_code=404,
detail=f"Unsupported reasoning_engine method: {class_method!r}",
)
return getattr(rt, class_method)
@app.post("/api/stream_reasoning_engine")
async def stream_query(request: Request) -> responses.StreamingResponse:
body = await request.json()
if "input" in body and isinstance(body["input"], dict):
body = body["input"]
method = resolve_method(body["class_method"], streaming=True)
kwargs = {k: v for k, v in body.items() if k != "class_method"}
async def generator():
events = method(**kwargs)
if hasattr(events, "__aiter__"):
async for event in events:
yield json.dumps(event) + "\n"
else:
for event in events:
yield json.dumps(event) + "\n"
return responses.StreamingResponse(
content=generator(), media_type="application/json"
)
@app.post("/api/reasoning_engine")
async def query(request: Request) -> responses.JSONResponse:
body = await request.json()
if "input" in body and isinstance(body["input"], dict):
body = body["input"]
method = resolve_method(body["class_method"], streaming=False)
kwargs = {k: v for k, v in body.items() if k != "class_method"}
output = (
await method(**kwargs)
if inspect.iscoroutinefunction(method)
else method(**kwargs)
)
return responses.JSONResponse(
content=encoders.jsonable_encoder({"output": output})
)
Deploy the agent
-
In the Cloud Shell Terminal, run the following command to package your app/ directory and upload it to Agent Runtime. Notice the --agent-identity flag: this instructs Google Cloud to provision a unique, SPIFFE-backed Agent Identity specifically for this runtime instance.
uv run agents-cli deploy \
--agent-identity \
--project="{{{project_0.project_id | PROJECT_ID}}}" \
--region="{{{project_0.default_region | REGION}}}" \
--update-env-vars="OAUTH_CONTINUE_URI=${DEV_URL}/validateUserId"
The deployment process takes 5-10 minutes to build and upload the container. When finished, the CLI outputs a success summary table. Take note of the Agent Identity and Reasoning Engine ID displayed in this table.
Output:

Authorize the Agent Identity
Now that your agent is running in the cloud, it needs permission to access the credentials stored in Auth Manager. By default, the agent's SPIFFE identity has no access to external cloud resources.
-
Run the following gcloud command to bind the roles/agentidentity.user role to your agent's identity. This grants your agent the exact permissions it needs to request user tokens from the vault. For the --member flag, use the full principal string provided in the output of the agents-cli deploy command.
gcloud projects add-iam-policy-binding {{{project_0.project_id | PROJECT_ID}}} \
--role='roles/agentidentity.user' \
--member="principal://agents.global.org-ORG_ID.system.id.goog/resources/aiplatform/projects/{{{project_0.project_number | PROJECT_NUMBER}}}/locations/{{{project_0.default_region | REGION}}}/reasoningEngines/REASONING_ENGINE_ID" \
--condition=None
Note: Ensure that you bind the role to your agent's individual principal://agents.global.org-ORG_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/REGION/reasoningEngines/REASONING_ENGINE_ID identity.
Click Check my progress to verify the objective.
Deploy Agent to Agent Runtime and Authorize Agent Identity
Task 6. Understand the 3LO consent flow
Now that the agent is deployed to Agent Runtime with a secure Agent Identity, the next step is to provide a custom frontend interface for users to chat with it. More importantly, Google Cloud Auth Manager requires a client application callback handler to complete the authentication loop.
Although Google Cloud Auth Manager securely manages user credentials inside a vault, it cannot finalize the OAuth token exchange on its own. The 3LO handshake relies on the client application to bridge the gap:
- When a user authorizes the OAuth app in the Cymbal DevOps Portal, the portal redirects them back to the Google Cloud Auth Provider
redirectUrl.
- The Google Cloud Auth Provider then redirects the user's browser popup back to a client-side callback URL (
continue_uri).
- It is the client application's responsibility to intercept this redirect, read the nonce from the browser's cookies, and call Google Cloud's
credentials:finalize endpoint to complete the handshake.
- After the client finalizes the exchange, Google Cloud securely saves the token in the auth provider's vault, allowing the agent to call the Cymbal DevOps MCP tools.
Without this custom client hosting the callback endpoint, the handshake remains incomplete, and the vault cannot store the credentials.
The interactive OAuth 3LO flow spans across multiple layers. Here is the full execution lifecycle of a tool request, which is described in the following explanation and in the next task.

Review the client's core responsibilities in the handshake
-
Relaying the Nonce (Steps 5-6): When the agent raises an authentication challenge (adk_request_credential), it provides the consent URL (auth_uri) and a single-use security nonce. The client backend intercepts these from the event stream and passes them to the browser, which opens the consent popup and stores the nonce (and user ID) as cookies.
-
Hosting the Redirect Callback (Steps 10-11): The client hosts the /validateUserId endpoint where the Auth Connector redirects the browser popup after consent.
-
Finalizing the Token (Steps 12-14): The client backend reads the signed validation state from the redirect query string and the cached nonce from cookies, then POSTs them to Google Cloud's credentials:finalize endpoint to store the OAuth token in the vault and closes the popup window.
With this architecture in mind, examine how the FastAPI client implements each step.
Task 7. Understand how the FastAPI frontend client works
With the 3LO consent architecture in place, review how the client application implements the authentication loop.
In this task, you examine how the backend web server works. The backend FastAPI code implements the three integration points the 3LO flow requires: relaying the agent's consent request (the auth_uri and single-use nonce) to the browser, forwarding the agent's chat stream as Server-Sent Events, and hosting the continue_uri callback that finalizes the credential.
Note: You do not need to write this client code yourself. The next task provides a prebuilt frontend client to run the demo. This breakdown is provided for your architectural understanding.
The following sections describe the critical segments of this file to show how each role is implemented in Python.
Review initialization and configuration
The client is a plain FastAPI app. It serves a static index.html frontend and reads its target host from the environment.
TARGET_HOST = (
os.environ.get("AGENT_IDENTITY_CREDENTIALS_TARGET_HOST")
or "agentidentitycredentials.googleapis.com"
)
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
async def get_index():
return FileResponse("static/index.html")
Intercept the consent auth_uri and nonce
When a tool needs user credentials (like accessing the user's Cymbal DevOps Portal data), ADK pauses and streams a long-running adk_request_credential function call. Its payload contains the OAuth auth_uri (the consent URL to open) and a single-use cryptographic token called a nonce.
The client inspects each streamed event and, when it finds this call, extracts both values and attaches them to the outgoing event so the browser can open the consent popup and store the nonce and user ID as cookies for later.
def handle_adk_request_credential(auth_config):
"""Extract the OAuth consent URL and nonce from the auth config."""
if (auth_config.exchanged_auth_credential
and auth_config.exchanged_auth_credential.oauth2):
oauth2 = auth_config.exchanged_auth_credential.oauth2
return oauth2.auth_uri, oauth2.nonce
return None, None
Inside the event processor, the relevant tool call is detected by name and the values are surfaced to the frontend:
"""Extract text parts for UI rendering."""
text_parts = [p.get("text", "") for p in parts if isinstance(p, dict) and "text" in p]
if text_parts:
event_data["text"] = "".join(text_parts)
fc = part.get("function_call") or part.get("functionCall")
if fc and fc.get("name") == "adk_request_credential":
cfg_data = fc.get("args", {}).get("authConfig") or fc.get("args", {}).get("auth_config")
auth_config = AuthConfig.model_validate(cfg_data)
auth_uri, consent_nonce = handle_adk_request_credential(auth_config)
if auth_uri:
event_data["popup_auth_uri"] = auth_uri # browser opens this
event_data["auth_request_function_call_id"] = fc.get("id")
event_data["consent_nonce"] = consent_nonce # browser stores as cookie
Where the nonce lives: The flow is: nonce → SSE event → frontend JavaScript → browser cookie (consent_nonce, plus user_id/consent_user_id). This nonce acts as a validation ticket. When the user completes the Cymbal DevOps Portal OAuth consent flow in the popup window, the portal redirects them back to the callback endpoint (/validateUserId). On the callback, the browser sends those cookies back. This handshake proves the browser session initiating the chat is the exact same session completing the OAuth consent, preventing Session Hijacking and Cross-Site Request Forgery (CSRF) attacks.
Review the streaming chat endpoint
The /chat endpoint queries the deployed Agent Runtime and returns Server-Sent Events. It sets a session_id cookie (so the callback can correlate the session) and runs each event through the processor before forwarding it to the browser. It also handles resuming the conversation after consent completes.
@app.post("/chat")
async def chat(request: ChatRequest, response: Response):
session_id = request.session_id or str(uuid.uuid4())
client = vertexai.Client(project=request.project_id, location=request.location)
remote_agent_name = (
f"projects/{request.project_id}/locations/{request.location}"
f"/reasoningEngines/{request.agent_id}"
)
current_agent = client.agent_engines.get(name=remote_agent_name)
"""Set session_id cookie so the /commit callback can correlate the browser session."""
response.set_cookie("session_id", session_id, httponly=True, samesite="lax")
async def event_generator():
"""After consent, resume by returning a function_response for the credential call."""
if request.is_auth_resume and request.auth_request_function_call_id:
message = types.Content(role="user", parts=[types.Part(
function_response=types.FunctionResponse(
id=request.auth_request_function_call_id,
name="adk_request_credential",
response=request.auth_config,
))])
else:
message = types.Content(role="user", parts=[types.Part(text=request.message)])
async for event in current_agent.async_stream_query(
user_id=request.user_id,
message=message.model_dump(exclude_none=True),
session_id=session_id,
):
event_data = process_agent_event(event) # intercepts auth_uri/nonce
yield f"data: {json.dumps(event_data)}\n\n"
return StreamingResponse(event_generator(), media_type="text/event-stream")
Review the continue_uri callback (/validateUserId)
After the user authorizes the third-party app, the provider redirects the browser to your continue_uri. The agent's continue_uri points at this route. It reads the consent state from cookies and query parameters and finalizes the token by calling the Auth Manager Credentials API.
@app.get("/validateUserId")
async def validate_user_id(request: Request):
"""Read state from cookies set by the browser during the popup flow."""
user_id = request.cookies.get("consent_user_id") or request.cookies.get("user_id")
consent_nonce = request.cookies.get("consent_nonce")
"""Read state from the provider's redirect query string."""
user_id_validation_state = request.query_params.get("user_id_validation_state")
auth_provider_name = (request.query_params.get("auth_provider_name")
or request.query_params.get("connector_name"))
"""Refresh ADC credentials to get the Bearer token for Auth Manager API."""
auth_req = AuthRequest()
credentials.refresh(auth_req)
token = credentials.token
"""Send the finalize credentials POST request."""
url = f"https://{TARGET_HOST}/v1alpha/{auth_provider_name}/credentials:finalize"
payload = {
"userId": user_id,
"userIdValidationState": user_id_validation_state,
"consentNonce": consent_nonce,
}
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
async with httpx.AsyncClient() as client:
resp = await client.post(url, json=payload, headers=headers)
if resp.status_code == 200:
return HTMLResponse("Authorization successful! You can close this window.
")
return {"status": "error", "message": f"HTTP {resp.status_code}: {resp.text}"}
After this returns 200, Google Cloud has stored the OAuth token in the Agent Identity vault. The frontend then re-calls /chat with is_auth_resume=True, and the agent retries the tool with the now-available credential.
Task 8. Run the UI client
As traced in the 3LO Consent Flow sequence diagram, the Google Cloud Auth Connector needs to redirect the browser popup back to your /validateUserId callback endpoint. Now that you understand the FastAPI client code, clone and run it in Cloud Shell.
Copy client files to Cloud Shell
Navigate to the gcp_auth/client folder in the adk-python GitHub repository. This folder contains the assets required to build the chat client:
-
main.py: The FastAPI application script containing the token finalization callback (/validateUserId) discussed in the previous task.
-
static/: Contains the HTML pages.
-
Run the following commands to clone the adk-python repository:
cd
git clone --depth 1 https://github.com/google/adk-python.git
-
Create and activate a Python virtual environment:
cd adk-python
python3 -m venv .venv
source .venv/bin/activate
-
Install the client dependencies:
pip install "google-adk[agent-identity]~=2.6.0" google-cloud-aiplatform==1.160.0
Note: google-adk already brings in fastapi, uvicorn, httpx, and google-auth; google-cloud-aiplatform provides the vertexai client the UI uses to call your deployed agent. Equivalently, you can cd into the client folder and run pip install -r requirements.txt.
-
Authenticate Application Default Credentials (ADC) and set your project. Sign in with the account that owns your project so the client can query your deployed agent:
gcloud auth application-default login
export GOOGLE_CLOUD_PROJECT="{{{project_0.project_id | PROJECT_ID}}}"
gcloud auth application-default set-quota-project $GOOGLE_CLOUD_PROJECT
When prompted, type Y and press ENTER. Click the provided URL to open a new browser window that displays a verification code. Copy the verification code, paste it in response to the Enter verification code: prompt, and press ENTER.
-
In the Cloud Shell Editor, navigate to adk-python > contributing > samples > integrations > gcp_auth > client > main.py. Replace the code in main.py with the following code, and replace YOUR_REASONING_ENGINE_ID with the Reasoning Engine ID you saved in Task 5.
"""Copyright 2026 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
A FastAPI client for interacting with ADK remote agents and handling GCP authentication.
"""
import json
import os
import traceback
from typing import Optional
import uuid
from fastapi import FastAPI, Request, Response
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from google.adk.auth import AuthConfig
import google.auth
from google.auth.transport.requests import Request as AuthRequest
from google.genai import types
import httpx
from pydantic import BaseModel
import uvicorn
"""Update the Reasoning Engine ID."""
REASONING_ENGINE_ID = os.environ.get("AGENT_ID", "YOUR_REASONING_ENGINE_ID")
TARGET_HOST = (
os.environ.get("AGENT_IDENTITY_CREDENTIALS_TARGET_HOST")
or "agentidentitycredentials.googleapis.com"
)
"""In-memory cache for consent nonces to bypass third-party cookie restrictions."""
NONCE_CACHE = {}
app = FastAPI()
try:
app.mount("/static", StaticFiles(directory="static"), name="static")
except Exception as e:
print(f"Static mount notice: {e}")
@app.get("/")
async def get_index():
return FileResponse("static/index.html")
def handle_adk_request_credential(auth_config):
if (
auth_config.exchanged_auth_credential
and auth_config.exchanged_auth_credential.oauth2
):
oauth2 = auth_config.exchanged_auth_credential.oauth2
return oauth2.auth_uri, oauth2.nonce
return None, None
try:
credentials, default_project = google.auth.default()
except Exception:
credentials, default_project = None, ""
@app.get("/list_agents")
async def list_remote_agents(project_id: str, location: str):
default_agent_entry = {
"id": REASONING_ENGINE_ID,
"name": "secure-agent-demo",
"full_name": (
f"projects/{project_id}/locations/{location}/reasoningEngines/{REASONING_ENGINE_ID}"
),
}
try:
auth_req = AuthRequest()
credentials.refresh(auth_req)
token = credentials.token
url = (
f"https://{location}-aiplatform.googleapis.com/v1/"
f"projects/{project_id}/locations/{location}/reasoningEngines"
)
headers = {"Authorization": f"Bearer {token}"}
async with httpx.AsyncClient() as client:
resp = await client.get(url, headers=headers)
data = resp.json()
agent_list = []
reasoning_engines = data.get("reasoningEngines", [])
for re_obj in reasoning_engines:
full_name = re_obj.get("name", "")
disp_name = re_obj.get("displayName", "")
agent_id = full_name.split("/")[-1] if full_name else ""
agent_list.append({
"id": agent_id,
"name": disp_name,
"full_name": full_name,
})
if not agent_list:
agent_list.append(default_agent_entry)
return {"agents": agent_list}
except Exception:
return {"agents": [default_agent_entry]}
class ChatRequest(BaseModel):
message: str = ""
agent_type: str = "remote"
local_agent: str = ""
project_id: str = os.environ.get(
"GOOGLE_CLOUD_PROJECT", default_project or ""
)
location: str = os.environ.get("GOOGLE_CLOUD_LOCATION", "{{{project_0.default_region | REGION}}}")
agent_id: str = REASONING_ENGINE_ID
user_id: str = "default_user_id"
session_id: Optional[str] = None
is_auth_resume: Optional[bool] = False
auth_config: Optional[dict] = None
auth_request_function_call_id: Optional[str] = None
@app.post("/chat")
async def chat(request: ChatRequest, response: Response):
try:
session_id = request.session_id if request.session_id else None
raw_user_id = request.user_id or "default_user_id"
clean_user_id = (
raw_user_id.split("@")[0] if "@" in raw_user_id else raw_user_id
)
response.set_cookie(key="consent_user_id", value=clean_user_id, httponly=True, samesite="none", secure=True)
def process_agent_event(event_data):
if not isinstance(event_data, dict):
return {"text": str(event_data)}
content = event_data.get("content", {})
parts = content.get("parts", []) if isinstance(content, dict) else []
long_running = event_data.get("long_running_tool_ids") or event_data.get(
"longRunningToolIds", []
)
text_parts = [
p.get("text", "")
for p in parts
if isinstance(p, dict) and "text" in p
]
if text_parts:
event_data["text"] = "".join(text_parts)
for part in parts:
if not isinstance(part, dict):
continue
fc = part.get("function_call") or part.get("functionCall")
if fc:
fc_name = fc.get("name", "")
if (
"credential" in fc_name
or "adk_request_credential" in fc_name
or "request_credential" in fc_name
):
fc_id = fc.get("id")
if not long_running or fc_id in long_running:
try:
args = fc.get("args", {})
cfg_data = args.get("authConfig") or args.get("auth_config")
if cfg_data:
auth_config = (
AuthConfig.model_validate(cfg_data)
if isinstance(cfg_data, dict)
else cfg_data
)
auth_uri, consent_nonce = handle_adk_request_credential(
auth_config
)
if auth_uri:
if "scope=" not in auth_uri:
auth_uri += "&scope=repo"
event_data["popup_auth_uri"] = auth_uri
event_data["auth_request_function_call_id"] = fc_id
event_data["auth_config"] = (
auth_config.model_dump()
if hasattr(auth_config, "model_dump")
else auth_config
)
event_data["consent_nonce"] = consent_nonce
if consent_nonce:
NONCE_CACHE["last_nonce"] = consent_nonce
NONCE_CACHE[clean_user_id] = consent_nonce
except Exception as e:
print(f"Auth wrapper processing notice: {e}")
break
return event_data
async def event_generator():
if (
request.is_auth_resume
and request.auth_request_function_call_id
and request.auth_config
):
message = types.Content(
role="user",
parts=[
types.Part(
function_response=types.FunctionResponse(
id=request.auth_request_function_call_id,
name="adk_request_credential",
response=request.auth_config,
)
)
],
)
else:
message = types.Content(
role="user", parts=[types.Part(text=request.message)]
)
dumped_message = message.model_dump(exclude_none=True)
payload_input = {
"class_method": "stream_query",
"user_id": clean_user_id,
"message": dumped_message,
}
if session_id:
payload_input["session_id"] = session_id
payload = {"input": payload_input}
auth_req = AuthRequest()
credentials.refresh(auth_req)
token = credentials.token
url = (
f"https://{request.location}-aiplatform.googleapis.com/v1/"
f"projects/{request.project_id}/locations/{request.location}/"
f"reasoningEngines/{request.agent_id}:streamQuery"
)
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
async with httpx.AsyncClient(timeout=120.0) as http_client:
async with http_client.stream(
"POST", url, headers=headers, json=payload
) as resp:
async for line in resp.aiter_lines():
if not line or not line.strip():
continue
clean_line = line.strip()
if clean_line.startswith("data:"):
json_text = clean_line[5:].strip()
else:
json_text = clean_line
try:
raw_json = json.loads(json_text)
processed = process_agent_event(raw_json)
yield f"data: {json.dumps(processed)}\n\n"
except Exception:
pass
return StreamingResponse(event_generator(), media_type="text/event-stream")
except Exception as e:
tb_str = traceback.format_exc()
async def fail_generator():
err_data = {"error": f"Server error: {str(e)}", "traceback": tb_str}
yield f"data: {json.dumps(err_data)}\n\n"
return StreamingResponse(fail_generator(), media_type="text/event-stream")
@app.get("/validateUserId")
@app.get("/commit")
async def validate_user_id(request: Request):
user_id = (
request.cookies.get("consent_user_id")
or request.cookies.get("user_id")
or "default_user_id"
)
consent_nonce = (
request.cookies.get("consent_nonce")
or NONCE_CACHE.get(user_id)
or NONCE_CACHE.get("last_nonce")
)
user_id_validation_state = request.query_params.get(
"user_id_validation_state"
)
auth_provider_name = request.query_params.get(
"auth_provider_name"
) or request.query_params.get("connector_name")
if not user_id or not consent_nonce or not user_id_validation_state:
return {"status": "error", "message": "Missing required cookies or state"}
auth_req = AuthRequest()
credentials.refresh(auth_req)
token = credentials.token
url = (
f"https://{TARGET_HOST}/v1alpha/{auth_provider_name}/credentials:finalize"
)
payload = {
"userId": user_id,
"userIdValidationState": user_id_validation_state,
"consentNonce": consent_nonce,
}
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
async with httpx.AsyncClient() as client:
resp = await client.post(url, json=payload, headers=headers)
if resp.status_code == 200:
return HTMLResponse(
"Authorization successful! You can close this window.
"
)
return {"status": "error", "message": f"HTTP {resp.status_code}: {resp.text}"}
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=8501, reload=True)
Run the client
-
Navigate to the client folder you just cloned:
cd ~/adk-python/contributing/samples/integrations/gcp_auth/client
-
Start the FastAPI server using uvicorn on port 8501:
uvicorn main:app --port 8501 --reload
Output:
INFO: Will watch for changes in these directories: ['/home/student_01_7331653697f9/adk-python/contributing/samples/integrations/gcp_auth/client']
INFO: Uvicorn running on http://127.0.0.1:8501 (Press CTRL+C to quit)
INFO: Started reloader process [3495] using StatReload
Successfully mounted /static
INFO: Started server process [3497]
INFO: Waiting for application startup.
INFO: Application startup complete.
-
Click the http://127.0.0.1:8501 link in the terminal and verify that the server started successfully and is listening on 8501.
Note: The Web Preview button in Cloud Shell defaults to port 8080. You must use the terminal link to access the app on port 8501.
Output:

Task 9. Test the OAuth flow
Now that all services are deployed, IAM bindings are configured, and environment variables are set, you are ready to test the secure end-to-end user-delegated authorization flow!
Initiate tool execution
-
In the Agent Assistant app, open Configuration Settings in the navigation panel and configure the following:
-
Agent Type: Remote Agent (Vertex AI)
-
Project ID:
-
Location:
-
Click Load Remote Agents. This loads all the agents deployed to your project.
-
Select the secure-agent-demo agent from the drop-down list and click Save and Apply Settings.
-
In the chat box, run the following prompt:
Hi
Output:

Observe the chat UI. Because the agent has no credentials for your user session yet, it receives an authentication challenge and displays the Authentication Required card in the conversation thread.
Complete the 3-legged OAuth consent
A separate browser popup window opens, redirecting you through Google Cloud's Auth Manager to the Cymbal DevOps Portal OAuth consent page (/oauth/authorize).
- Review the requested permissions and click Authorize.
After you authorize access:
- The Cymbal DevOps Portal redirects back to Google Cloud, which redirects the popup to your Cloud Shell callback URL
/validateUserId.
- The callback service processes and finalizes the credentials handshake.
Resume
- After the popup window closes, the parent chat tab automatically detects the closure.
- The frontend sends a resume payload back to the agent.
- The agent retrieves the newly exchanged token securely from Google Cloud Auth Manager.
-
Next, run the following prompts:
Can you tell me my DevOps profile details?
Show my recent pull requests.
Output:
Here are your recent pull requests in cymbal-infra/agent-platform:
1. PR #142 — fix: Enforce Cloud Run MemAllocPerProjectRegion max-instances cap
State: open
Summary: Caps max_instance_count and --max-instances to keep regional Cloud Run memory reservations below the 32 GiB sandbox ceiling.
2. PR #139 — feat: Bind SPIFFE Agent Identity to Auth Manager
State: merged
Summary: Grants roles/agentidentity.user to the Agent Runtime SPIFFE principal so delegated 3LO tokens can be retrieved at runtime without static secrets.
3. PR #135 — docs: Update 3LO consent flow architecture guide
State: merged
Summary: Documents the end-to-end /validateUserId nonce verification and credentials:finalize handshake.
The agent executes the MCP tool on your behalf and streams your Cymbal DevOps profile and pull request details back into the chat window.
Inspect the Cloud logs
To verify that the token exchange and finalization were processed securely:
-
In the Google Cloud console, on the Navigation menu, click Logging > Logs Explorer.
-
Locate the server logs confirming the nonce extraction and successful validation.
-
Inspect the Agent Runtime logs, or view execution logs directly inside the Agent Platform console:
- Navigate to the Agent Runtime console.
- Click your deployed agent from the list.
- Click the Playground tab; this displays the live agent logs in the execution logs panel, showing the agent's reasoning loop, tool execution details, and token retrieval lifecycle in real time.
Output:

Click Check my progress to verify the objective.
Test the OAuth Flow and Query the Agent
Congratulations!
You have successfully built and secured a DevOps Assistant Agent! What you learned:
-
Agent System Identity: How the agent operates under its own Account identity to securely interface with GCP infrastructure, manage telemetry logs, and call credential finalization APIs.
-
User Delegated Identity: How the agent requests authorization to act on the user's behalf on external platforms (such as the Cymbal DevOps Portal) by triggering a 3-legged OAuth (3LO) consent flow.
-
Secure Tool Integration: How to connect ADK Agents to Model Context Protocol (MCP) servers using Google Cloud Auth Manager to dynamically fetch user tokens instead of using hardcoded secrets.
-
IAM Policy Configuration: How to set up fine-grained permission bindings to authorize both the Agent Engine runtime identity and the Web client identity on the auth provider.
Further reading
Next steps / Learn more
Google Cloud training and certification
...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.
Manual Last Updated November 20, 2026
Lab Last Tested November 19, 2026
End your lab
When you have completed your lab, click End Lab. Qwiklabs removes the resources you’ve used and cleans the account for you.
You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.
The number of stars indicates the following:
- 1 star = Very dissatisfied
- 2 stars = Dissatisfied
- 3 stars = Neutral
- 4 stars = Satisfied
- 5 stars = Very satisfied
You can close the dialog box if you don't want to provide feedback.
For feedback, suggestions, or corrections, please use the Support tab.
Copyright 2026 Google LLC. All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.