1. 總覽
在本程式碼研究室中,您將執行 ADK 代理,使用兩種開放原始碼商務通訊協定,向多個電影院商家預訂電影票:
- UCP (通用商務通訊協定):代理程式的標準,可探索商家、搜尋目錄及管理結帳流程。
- AP2 (Agent Payments Protocol):這項通訊協定可使用經加密簽署的授權,安全地授權付款並驗證授權。
CineAgent 示範應用程式會連線至兩個具有不同功能的模擬電影院商家 (選位、特殊格式和付款方式),並從搜尋到付款,協調整個預訂流程。
課程內容
- 如何透過
/.well-known/ucp設定檔啟用 UCP 商家探索功能 - ADK 代理如何使用 UCP 搜尋目錄及建立結帳程序
- AP2 授權書 (CheckoutMandate、PaymentMandate) 如何確保交易安全
- 端對端 UCP 和 AP2 通訊協定如何確保代理式電子商務安全
軟硬體需求
本程式碼實驗室適合對 Python 和 Google Cloud 有基本認識的中級開發人員。完成本程式碼研究室大約需要 30 分鐘。
本程式碼研究室建立的資源費用應低於 $5 美元。
2. 瞭解 UCP 和 AP2 通訊協定
在深入瞭解如何建構代理程式之前,我們先來瞭解這兩個通訊協定,這兩個通訊協定可確保代理式商務安全無虞。
本程式碼研究室使用 UCP 版本 2026-08-25 和 UCP Python SDK,以及 AP2 v0.2 和 AP2 Python SDK。
通用商務通訊協定 (UCP)
UCP 規範 AI 代理與商家互動的方式,這項功能引進標準化資源模型,解決代理商必須為每間商店學習自訂 API 的問題。
運作方式:
- 探索:每個符合 UCP 規範的商家都會在標準位置 (
/.well-known/ucp) 公開設定檔。示例:Everlane 的 UCP 端點。代理程式讀取這個設定檔時,會尋找:- 功能:商家支援的獨立核心功能,例如目錄搜尋或結帳。
- 服務:用於交換資料的低層級通訊層。例如:REST API、MCP (Model Context Protocol)、A2A (Agent2Agent Protocol)。
- 擴充功能:如果商家需要特殊行為,可以在這個設定檔中定義自訂擴充功能。
- 金鑰:商家的公開簽署金鑰,代理商會使用這些金鑰檢查商家的簽章。
- 作業:探索完成後,代理程式會使用提供的服務端點執行作業。在本程式碼實驗室中,我們使用 Model Context Protocol (MCP) 做為服務傳輸方式。代理程式會對這個端點發出 JSON-RPC 2.0 呼叫,以叫用探索到的功能:搜尋產品、建立結帳程序及完成購買。

Agent Payments Protocol (AP2)
AP2 會統一代理人代表使用者授權付款的方式。解決代理人處理敏感付款憑證時的安全問題。
運作方式:
- 商家簽章:代理商使用 UCP 通訊協定建立結帳程序時,商家會簽署結帳程序 (項目和總計),並在
ap2.merchant_authorization中傳回簽章。這項服務可確保你預訂的價格不會變動。如果商家在簽署後變更價格,簽章就不再相符。 - 結帳授權和付款委託書:驗證結帳內容後,使用者 (或代表使用者的代理人) 會簽署兩份委託書。
CheckoutMandate包含商家簽署的結帳資訊,並告知商家使用者已核准。PaymentMandate會授權該結帳程序的付款金額。兩者都會參照已簽署結帳程序的雜湊值,並攜帶使用者的加密簽章。 - 簽名驗證:商家會收到兩份授權書。並驗證
CheckoutMandate上的使用者簽章,確認其中的結帳程序是否帶有商家自己的簽章。PaymentMandate會傳送至付款端 (憑證供應商或付款處理方),由對方驗證後才會轉移款項。如果一切正常,交易就會繼續進行。
這套「雙重鎖定」系統可確保商家不會超收費用,代理商也不會在未經授權的情況下消費。授權是 SD-JWT (選擇性揭露 JWT) 憑證,可只揭露各方需要的欄位,保護使用者隱私權。在 AP2 v0.2 中,CheckoutMandate 會取代 AP2 v0.1 中的 CartMandate。

3. 設定環境
設定 Google Cloud 專案
建立 Google Cloud 專案
- 在 Google Cloud 控制台的專案選擇器頁面中,選取或建立 Google Cloud 專案。
- 確認 Cloud 專案已啟用計費功能。瞭解如何檢查專案是否已啟用計費功能。
啟動 Cloud Shell
Cloud Shell 是在 Google Cloud 中運作的指令列環境,已預先載入必要工具。
- 點選 Google Cloud 控制台頂端的「啟用 Cloud Shell」。
- 連至 Cloud Shell 後,請驗證您的驗證:
gcloud auth list - 確認專案已設定:
gcloud config get project - 如果專案未如預期設定,請設定專案:
export PROJECT_ID=<YOUR_PROJECT_ID> gcloud config set project $PROJECT_ID
啟用 API
執行下列指令,啟用必要 API:
gcloud services enable aiplatform.googleapis.com
設定目錄結構
複製並貼上下列指令,為本程式碼研究室建立資料夾,並在其中建立 agent_payments 資料夾,存放代理程式碼:
mkdir -p ~/adk-agent-commerce/agent_payments
cd ~/adk-agent-commerce
存取 Gemini 模型
複製並貼上下列指令,建立專案和位置的 agent_payments/.env,並讓 ADK 透過 Google Cloud 雲端專案呼叫 Gemini。Cine Agent 會使用 Gemini 決定要呼叫哪些工具。ADK 會自動載入這個檔案,因此設定也會在新終端機中生效。
cat > ~/adk-agent-commerce/agent_payments/.env <<EOF
GOOGLE_CLOUD_PROJECT=$(gcloud config get project)
GOOGLE_CLOUD_LOCATION=global
GOOGLE_GENAI_USE_ENTERPRISE=True
EOF
安裝依附元件
Google Cloud Shell 已預先安裝 uv,可管理環境和依附元件。
- 在
adk-agent-commerce資料夾的根目錄建立pyproject.toml檔案,並加入以下內容。這個檔案會定義專案中繼資料和依附元件。
[project]
name = "agent-payments-demo"
version = "0.1.0"
description = "CineAgent booking agent using UCP and AP2"
requires-python = ">=3.11"
dependencies = [
"google-adk",
"fastapi",
"uvicorn",
"httpx",
"ucp-sdk",
"ap2 @ git+https://github.com/google-agentic-commerce/AP2.git@main",
]
AP2 SDK 會從 GitHub 存放區安裝,因為尚未發布至 PyPI。(PyPI 上的 ap2 套件是無關的專案)。
- 執行下列指令,建立虛擬環境並安裝所有依附元件:
uv sync
uv 會為這個程式碼研究室建立獨立的 Python 環境,因此您不需要啟用任何項目。在 Python 指令前加上 uv run。
4. 定義代理
撰寫任何工具邏輯之前,請先在名為 agent.py 的檔案中定義代理程式本身。這個代理程式會做為電影訂票流程的自動化調度管理工具。
建立 agent_payments/agent.py:
"""CineAgent — movie ticket booking agent using UCP and AP2."""
from google.adk.agents import Agent
from google.adk.models import Gemini
from google.genai import types
from google.adk.tools import FunctionTool
from agent_payments.tools import (
discover_theaters,
search_movies,
get_movie_detail,
create_checkout,
complete_purchase,
)
root_agent = Agent(
model=Gemini(
model="gemini-3.8-flash",
retry_options=types.HttpRetryOptions(attempts=5),
),
name="cineagent",
description="Movie ticket booking agent using UCP and AP2.",
instruction="""You are CineAgent, a movie ticket booking assistant.
You help users find and book movie tickets across multiple theaters
using UCP (Universal Commerce Protocol) and AP2 (Agent Payments).
**Your tools:**
- discover_theaters: Find theaters and what they support
- search_movies: Search movies across all theaters
- get_movie_detail: Get showtimes at a specific theater
- create_checkout: Start a checkout session
- complete_purchase: Finalize with AP2 mandate signing
**Rules:**
- Always call discover_theaters first if you haven't yet
- Keep responses concise — summarize and suggest next steps
- Prices from tools are in cents (1500 = $15.00)
- Never invent data — only state what tools return
""",
tools=[
discover_theaters,
search_movies,
get_movie_detail,
create_checkout,
FunctionTool(complete_purchase, require_confirmation=True),
],
)
解釋程式碼
我們來分析這個代理程式定義的內容:
model=Gemini(...):我們使用 Gemini 3.8 Flash 進行推論和工具使用。instruction:這是引導代理行為的提示。這項提示會明確告知代理使用 UCP 和 AP2、列出可用工具,並設定重要規則,例如「絕不編造資料」和「價格以美分為單位」。tools:這是 Python 函式清單 (我們會在下一個步驟中建構),代理可以根據使用者的要求選擇呼叫這些函式。require_confirmation:你可以使用FunctionTool(my_function,require_confirmation=True)包裝任何工具。觸發後,代理程式會暫停並等待簡單的「是」或「否」核准,然後再執行工具。在這裡,代理會在執行complete_purchase工具前暫停,等待人工確認。
工具清單
代理程式定義會宣告我們需要建構的內容。每項工具都會對應至 UCP 或 AP2 通訊協定中的特定作業:
工具 | 用途 | 通訊協定動作 |
| 尋找商家及其服務 | 查詢 |
| 搜尋各商家的目錄 | JSON-RPC 至 MCP 端點 |
| 取得特定商家提供的電影場次 | JSON-RPC 至 MCP 端點 |
| 啟動結帳工作階段 | JSON-RPC 至 MCP 端點 |
| 授權付款並完成訂單 | 簽署 AP2 授權並傳送至 MCP |
Gemini 模型會根據對話內容,決定何時呼叫各項工具。接下來的工作是在 tools.py 中實作每個工具的功能。
5. 建構代理工具:探索和瀏覽
現在來實作代理程式將用於瀏覽及探索電影的工具。每個工具都會包裝 UCP 作業。
建立名為 agent_payments/tools.py 的新檔案,然後複製並貼上下列程式碼:
"""Agent tools — each one wraps a UCP or AP2 operation."""
import json
from .ucp_client import UCPClient
from .ap2_handler import AP2Handler
# Initialize clients directly
_merchant_urls = ["http://localhost:8081", "http://localhost:8082"]
_ap2 = AP2Handler()
_ucp = UCPClient(platform_keys=[_ap2.public_key])
瞭解設定
為讓本程式碼研究室專注於建構代理程式,我們使用了兩個輔助類別 UCPClient 和 AP2Handler,稍後會介紹這兩個類別。
- 什麼是這些指標?:這是我們為本程式碼研究室編寫的小型輔助類別,可與模擬商家通訊。官方 SDK 提供通訊協定片段:UCP SDK 具有每個 UCP 結構定義的資料模型,AP2 SDK 則會建立及驗證簽署的授權。這兩個 SDK 都不包含呼叫商家的用戶端,因此這些輔助程式會處理這部分。
- 目前請將這些物件視為輔助物件:
_ucp.discover(url):擷取並驗證商家檔案。_ucp.mcp_call(url, method, params):將 JSON-RPC 2.0 要求傳送至商家 MCP 端點。
探索劇院
這個工具是 UCP 流程的第一步。並找出現有的商家和支援的項目。
新增至「tools.py」:
async def discover_theaters() -> str:
"""Discover available theater merchants and their capabilities via UCP."""
theaters = []
for url in _merchant_urls:
info = await _ucp.discover(url)
theaters.append(
{
"url": url,
"name": info["name"],
"capabilities": info["capabilities"],
"payment_handlers": info["payment_handlers"],
}
)
return json.dumps(theaters, indent=2)
作用:
- 並逐一檢查伺服器提供的商家網址清單。在本程式碼研究室的後續章節中,我們會設定兩個模擬商家。
- 針對每個網址,系統會呼叫
_ucp.discover(url),這會觸發/.well-known/ucp端點。 - 並將名稱、功能和付款處理常式收集到摘要清單中。
- 並以 JSON 字串形式傳回清單,供代理程式讀取。
搜尋電影
這項工具會搜尋所有已探索到的商家,並合併結果。這點非常重要,因為同一部電影可能會在多個影廳以不同格式 (IMAX、Dolby) 播放,且價格不同。
新增至「tools.py」:
async def search_movies(query: str = "") -> str:
"""Search for movies across all theaters. Use '' to browse all."""
all_movies = {}
for url, merchant in _ucp.merchants.items():
result = await _ucp.mcp_call(
url, "search_catalog", {"catalog": {"query": query}}
)
for product in result.get("products", []):
mid = product["id"]
if mid not in all_movies:
all_movies[mid] = {
"id": mid,
"title": product["title"],
"categories": [
c["value"] for c in product.get("categories", [])
],
"theaters": {},
}
showtimes = []
for v in product.get("variants", []):
opts = {o["name"]: o["label"] for o in v.get("options", [])}
showtimes.append(
{
"id": v["id"],
"format": opts.get("format", "Standard"),
"time": opts.get("time", ""),
"price": v.get("price", {}),
"seats": v.get("metadata", {}).get(
"seats_available", 0
),
}
)
all_movies[mid]["theaters"][url] = {
"name": merchant["name"],
"showtimes": showtimes,
}
return json.dumps(list(all_movies.values()), indent=2)
作用:
- 這個函式會逐一檢查所有找到的電影院。
- 並將搜尋目錄 JSON-RPC 要求 (
_ucp.mcp_call(url, "search_catalog", {"catalog": {"query": query}})) 傳送至商家 MCP 端點。 - 接著進行一些清理作業,剖析結果以找出電影及其「變體」(代表特定放映時間和格式)。依 ID 將電影分組,避免使用者看到重複的電影項目。
取得電影詳細資料
這項工具會取得特定電影在特定戲院的完整目錄詳細資料。
新增至「tools.py」:
async def get_movie_detail(movie_id: str, merchant_url: str) -> str:
"""Get detailed showtimes for a movie at a specific theater."""
result = await _ucp.mcp_call(
merchant_url, "lookup_catalog", {"catalog": {"ids": [movie_id]}}
)
return json.dumps(result, indent=2)
作用:
- 並在商家的 MCP 端點上呼叫
lookup_catalog方法,在catalog.ids中傳遞特定movie_id。這會傳回詳細資訊,例如特定戲院的放映時間和座位供應情形。
6. 建構代理工具:結帳和付款
這些工具會處理結帳和購買流程。此時 AP2 通訊協定就能派上用場,確保交易安全無虞。
建立結帳頁面
這項工具會在特定劇院的特定放映時間啟動結帳程序。
新增至「tools.py」:
async def create_checkout(
merchant_url: str, showtime_id: str, quantity: int = 1
) -> str:
"""Create a checkout session for tickets at a theater."""
result = await _ucp.mcp_call(merchant_url, "create_checkout", {
"checkout": {
"line_items": [
{"item": {"id": showtime_id}, "quantity": quantity}
],
"context": {"address_country": "US", "currency": "USD"},
}
})
return json.dumps(result, indent=2)
作用:
- 並在商家的 MCP 端點上呼叫
create_checkout方法。 - 並傳遞使用者要求的
showtime_id和quantity。 - 商家會傳回以商家金鑰簽署的結帳資訊。
注意:如果您檢查回應資料,ap2.merchant_authorization 欄位會包含商家對結帳交易的加密簽章,鎖定報價。設定後即無法變更!
完成購買程序
這項工具會執行三項操作:
- 我們取得結帳資訊,並驗證商家簽章。
- 使用 AP2 SDK 建立並簽署 CheckoutMandate 和 PaymentMandate。
- 將這兩份授權書傳送給商家,完成購買程序。
新增至「tools.py」:
async def complete_purchase(checkout_id: str, merchant_url: str) -> str:
"""Complete purchase with AP2 payment authorization."""
merchant = _ucp.merchants[merchant_url]
# 1. Get the checkout and verify the merchant's signature on it
checkout = await _ucp.mcp_call(
merchant_url, "get_checkout", {"id": checkout_id}
)
checkout_jwt = _ap2.verify_merchant_authorization(checkout, merchant["keys"])
if not checkout_jwt:
return json.dumps({"error": "Merchant signature is missing or invalid"})
# 2. Create and sign the CheckoutMandate and PaymentMandate
# In production, this step asks the user to approve on a trusted device
# (biometric or device auth). In this demo, the agent signs with a local key.
checkout_mandate, payment_mandate = _ap2.create_mandates(
checkout, checkout_jwt, merchant["name"]
)
# 3. Send both mandates to the merchant to complete the purchase
result = await _ucp.mcp_call(merchant_url, "complete_checkout", {
"id": checkout_id,
"checkout": {
"payment": {
"instruments": [{
"id": "instr_1",
"handler_id": merchant["payment_handlers"][0],
"type": "card",
"selected": True,
"credential": {
"type": "ap2_payment_mandate",
"token": payment_mandate,
},
}],
},
"ap2": {"checkout_mandate": checkout_mandate},
},
})
return json.dumps(result, indent=2)
為什麼需要兩份授權書?CheckoutMandate 會向商家證明使用者已核准這項結帳交易,且價格與商家簽署的價格一致。付款授權書會向付款方證明使用者已授權這筆費用。流程如下:
Merchant signs checkout -> User signs mandates -> Merchant and payment side verify -> Order completes。
檢查點:完整 tools.py
完整的 tools.py 現在應有 5 個工具函式,以及 UCP 和 AP2 用戶端的模組層級初始化。確認是否像這樣:
"""Agent tools — each one wraps a UCP or AP2 operation."""
import json
from .ucp_client import UCPClient
from .ap2_handler import AP2Handler
# Initialize clients directly
_merchant_urls = ["http://localhost:8081", "http://localhost:8082"]
_ap2 = AP2Handler()
_ucp = UCPClient(platform_keys=[_ap2.public_key])
async def discover_theaters() -> str:
"""Discover available theater merchants and their capabilities via UCP."""
theaters = []
for url in _merchant_urls:
info = await _ucp.discover(url)
theaters.append(
{
"url": url,
"name": info["name"],
"capabilities": info["capabilities"],
"payment_handlers": info["payment_handlers"],
}
)
return json.dumps(theaters, indent=2)
async def search_movies(query: str = "") -> str:
"""Search for movies across all theaters. Use '' to browse all."""
all_movies = {}
for url, merchant in _ucp.merchants.items():
result = await _ucp.mcp_call(
url, "search_catalog", {"catalog": {"query": query}}
)
for product in result.get("products", []):
mid = product["id"]
if mid not in all_movies:
all_movies[mid] = {
"id": mid,
"title": product["title"],
"categories": [
c["value"] for c in product.get("categories", [])
],
"theaters": {},
}
showtimes = []
for v in product.get("variants", []):
opts = {o["name"]: o["label"] for o in v.get("options", [])}
showtimes.append(
{
"id": v["id"],
"format": opts.get("format", "Standard"),
"time": opts.get("time", ""),
"price": v.get("price", {}),
"seats": v.get("metadata", {}).get(
"seats_available", 0
),
}
)
all_movies[mid]["theaters"][url] = {
"name": merchant["name"],
"showtimes": showtimes,
}
return json.dumps(list(all_movies.values()), indent=2)
async def get_movie_detail(movie_id: str, merchant_url: str) -> str:
"""Get detailed showtimes for a movie at a specific theater."""
result = await _ucp.mcp_call(
merchant_url, "lookup_catalog", {"catalog": {"ids": [movie_id]}}
)
return json.dumps(result, indent=2)
async def create_checkout(
merchant_url: str, showtime_id: str, quantity: int = 1
) -> str:
"""Create a checkout session for tickets at a theater."""
result = await _ucp.mcp_call(merchant_url, "create_checkout", {
"checkout": {
"line_items": [
{"item": {"id": showtime_id}, "quantity": quantity}
],
"context": {"address_country": "US", "currency": "USD"},
}
})
return json.dumps(result, indent=2)
async def complete_purchase(checkout_id: str, merchant_url: str) -> str:
"""Complete purchase with AP2 payment authorization."""
merchant = _ucp.merchants[merchant_url]
# 1. Get the checkout and verify the merchant's signature on it
checkout = await _ucp.mcp_call(
merchant_url, "get_checkout", {"id": checkout_id}
)
checkout_jwt = _ap2.verify_merchant_authorization(checkout, merchant["keys"])
if not checkout_jwt:
return json.dumps({"error": "Merchant signature is missing or invalid"})
# 2. Create and sign the CheckoutMandate and PaymentMandate
# In production, this step asks the user to approve on a trusted device
# (biometric or device auth). In this demo, the agent signs with a local key.
checkout_mandate, payment_mandate = _ap2.create_mandates(
checkout, checkout_jwt, merchant["name"]
)
# 3. Send both mandates to the merchant to complete the purchase
result = await _ucp.mcp_call(merchant_url, "complete_checkout", {
"id": checkout_id,
"checkout": {
"payment": {
"instruments": [{
"id": "instr_1",
"handler_id": merchant["payment_handlers"][0],
"type": "card",
"selected": True,
"credential": {
"type": "ap2_payment_mandate",
"token": payment_mandate,
},
}],
},
"ap2": {"checkout_mandate": checkout_mandate},
},
})
return json.dumps(result, indent=2)
7. 讓程式碼可執行
如果是實際的 UCP 商家,您只要將代理程式指向他們的網址即可。在本程式碼研究室中,我們需要兩項項目才能在本機進行測試:
- 模擬商家:模擬 UCP 端點的本機伺服器,方便您進行測試
- 通訊協定輔助程式:透過 HTTP 呼叫商家,並使用 UCP 和 AP2 SDK 取得通訊協定資料和簽章的精簡包裝函式
注意:您不需要仔細閱讀這段程式碼,這些檔案會模擬真實商家和使用者的錢包。直接複製。
通訊協定輔助程式
UCP SDK 提供資料模型,AP2 SDK 則會簽署及驗證授權,但兩者都不包含與商家通訊的用戶端。這兩個檔案可填補這項缺口。這兩個函式分別命名為 ucp_client.py 和 ap2_handler.py,因此不會遮蔽 ap2 套件。
建立 agent_payments/ucp_client.py:
"""UCP client: discovers merchants and calls their MCP tools."""
import uuid
import httpx
from ucp_sdk.models.schemas.profile import BusinessSchema
# The platform (this agent) identifies itself with a UCP profile URL
PLATFORM_PROFILE = "https://cineagent.example/.well-known/ucp"
class UCPClient:
def __init__(self, platform_keys: list[dict]):
self.client = httpx.AsyncClient(timeout=30)
self.platform_keys = platform_keys
self.merchants = {} # url -> merchant info dict
async def discover(self, merchant_url: str) -> dict:
"""Fetch and validate a merchant's UCP profile from /.well-known/ucp."""
resp = await self.client.get(f"{merchant_url}/.well-known/ucp")
resp.raise_for_status()
profile = BusinessSchema.model_validate(resp.json())
ucp = profile.ucp
info = {
"name": merchant_url.split("//")[-1],
"mcp_endpoint": str(ucp.services["dev.ucp.shopping"][0].endpoint),
"capabilities": list(ucp.capabilities or {}),
"payment_handlers": [
h.id for handlers in ucp.payment_handlers.values() for h in handlers
],
"keys": [k.model_dump(exclude_none=True) for k in profile.keys or []],
}
self.merchants[merchant_url] = info
return info
async def mcp_call(
self, merchant_url: str, tool_name: str, arguments: dict
) -> dict:
"""Call a merchant's MCP tool via JSON-RPC 2.0."""
merchant = self.merchants[merchant_url]
meta = {
"ucp-agent": {
"profile": PLATFORM_PROFILE,
# Mock shortcut: a real merchant reads the platform's public
# keys from the profile URL above instead
"keys": self.platform_keys,
},
"idempotency-key": str(uuid.uuid4()),
}
resp = await self.client.post(
merchant["mcp_endpoint"],
json={
"jsonrpc": "2.0",
"id": uuid.uuid4().hex,
"method": "tools/call",
"params": {
"name": tool_name,
"arguments": {"meta": meta, **arguments},
},
},
)
resp.raise_for_status()
data = resp.json()
if "error" in data:
raise Exception(f"MCP error: {data['error']}")
return data["result"]["structuredContent"]
async def close(self):
await self.client.aclose()
建立 agent_payments/ap2_handler.py:
"""AP2 mandate handler: verifies the merchant's signature and signs mandates."""
import json
import time
from jwcrypto.jwk import JWK
from jwcrypto.jws import JWS
from ap2.sdk.mandate import MandateClient
from ap2.sdk.utils import b64url_decode, b64url_encode, compute_sha256_b64url
from ap2.sdk.generated.checkout_mandate import CheckoutMandate
from ap2.sdk.generated.payment_mandate import PaymentMandate
from ap2.sdk.generated.types.amount import Amount
from ap2.sdk.generated.types.merchant import Merchant
from ap2.sdk.generated.types.payment_instrument import PaymentInstrument
class AP2Handler:
def __init__(self):
# The user's signing key. In production, this key stays in a wallet or
# on a trusted device, and the user approves each signature.
self.key = JWK.generate(kty="EC", crv="P-256", kid="cineagent-user-key")
self.public_key = json.loads(self.key.export_public())
self.mandates = MandateClient()
def verify_merchant_authorization(
self, checkout: dict, merchant_keys: list[dict]
) -> str | None:
"""Check the merchant's signature on a checkout.
The signature is the merchant's price guarantee: if anything in the
checkout changes, the signature no longer matches. Returns the signed
checkout as a JWT, or None if the signature is missing or invalid.
"""
signature = checkout.get("ap2", {}).get("merchant_authorization")
if not signature:
return None
header, _, sig = signature.split(".") # detached JWS: header..signature
payload = {k: v for k, v in checkout.items() if k != "ap2"}
canonical = json.dumps(
payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False
)
checkout_jwt = f"{header}.{b64url_encode(canonical.encode())}.{sig}"
kid = json.loads(b64url_decode(header))["kid"]
key = next((k for k in merchant_keys if k["kid"] == kid), None)
if not key:
return None
try:
jws = JWS()
jws.deserialize(checkout_jwt)
jws.verify(JWK(**key))
except Exception:
return None
return checkout_jwt
def create_mandates(
self, checkout: dict, checkout_jwt: str, merchant_name: str
) -> tuple[str, str]:
"""Create and sign a CheckoutMandate and a PaymentMandate.
Both mandates reference the hash of the merchant-signed checkout, so
the user's approval is bound to exactly this cart and price.
"""
checkout_hash = compute_sha256_b64url(checkout_jwt)
total = next(t["amount"] for t in checkout["totals"] if t["type"] == "total")
now = int(time.time())
checkout_mandate = CheckoutMandate(
checkout_jwt=checkout_jwt,
checkout_hash=checkout_hash,
iat=now,
exp=now + 600,
)
payment_mandate = PaymentMandate(
transaction_id=checkout_hash,
payee=Merchant(id=merchant_name, name=merchant_name),
payment_amount=Amount(amount=total, currency=checkout["currency"]),
payment_instrument=PaymentInstrument(
id="instr_1", type="card", description="Demo card"
),
iat=now,
exp=now + 600,
)
# Sign each mandate as an SD-JWT with the user's key
return (
self.mandates.create(payloads=[checkout_mandate], issuer_key=self.key),
self.mandates.create(payloads=[payment_mandate], issuer_key=self.key),
)
模擬商家
建立 agent_payments/merchants.py:
"""Mock UCP merchant servers: two theaters with different capabilities."""
import json
import time
import uuid
import multiprocessing
from datetime import datetime, timezone, timedelta
import uvicorn
from fastapi import FastAPI
from jwcrypto.jwk import JWK
from jwcrypto.jws import JWS
from ap2.sdk.mandate import MandateClient
from ap2.sdk.utils import compute_sha256_b64url
from ap2.sdk.generated.checkout_mandate import CheckoutMandate
from ap2.sdk.generated.payment_mandate import PaymentMandate
from ucp_sdk.models.schemas.common.payment_ap2_mandate import Checkout
from ucp_sdk.models.schemas.profile import BusinessSchema
from ucp_sdk.models.schemas.shopping.catalog_lookup import LookupResponse
from ucp_sdk.models.schemas.shopping.catalog_search import SearchResponse
UCP_VERSION = "2026-08-25"
UCP_SPEC = f"https://ucp.dev/{UCP_VERSION}"
# ── Theater data ────────────────────────────────────────────
THEATERS = {
8081: {
"name": "Meridian Cinemas",
"movies": [
{
"id": "opp",
"title": "Oppenheimer",
"categories": ["Drama", "History"],
"showtimes": [
{"id": "st_opp_7pm_imax", "format": "IMAX", "time": "7:00 PM", "price": 2200, "seats": 45},
{"id": "st_opp_930pm", "format": "Standard", "time": "9:30 PM", "price": 1500, "seats": 80},
],
},
{
"id": "dune3",
"title": "Dune: Part Three",
"categories": ["Sci-Fi", "Action"],
"showtimes": [
{"id": "st_dune_8pm_imax", "format": "IMAX", "time": "8:00 PM", "price": 2200, "seats": 30},
],
},
],
},
8082: {
"name": "StarLight Theaters",
"movies": [
{
"id": "opp",
"title": "Oppenheimer",
"categories": ["Drama", "History"],
"showtimes": [
{"id": "st_opp_6pm_atmos", "format": "Dolby Atmos", "time": "6:00 PM", "price": 1800, "seats": 60},
],
},
{
"id": "spider",
"title": "Spider-Verse",
"categories": ["Animation", "Action"],
"showtimes": [
{"id": "st_spider_4pm", "format": "Standard", "time": "4:00 PM", "price": 1200, "seats": 100},
],
},
],
},
}
def create_app(port):
theater = THEATERS[port]
app = FastAPI()
sessions = {}
checkout_jwts = {} # checkout id -> merchant-signed checkout JWT
# The merchant's signing key. Its public half is published in the profile.
key = JWK.generate(kty="EC", crv="P-256", kid=f"merchant-{port}")
def _capability(name, path, schema, **extra):
return {name: [{
"version": UCP_VERSION,
"spec": f"{UCP_SPEC}/specification/{path}",
"schema": f"{UCP_SPEC}/schemas/{schema}",
**extra,
}]}
payment_handlers = {
"com.example.card": [
{"id": f"card_{port}", "version": UCP_VERSION,
"available_instruments": [{"type": "card"}], "config": {}}
]
}
# ── UCP Discovery endpoint ──────────────────────────────
@app.get("/.well-known/ucp")
def discovery():
profile = {
"ucp": {
"version": UCP_VERSION,
"services": {
"dev.ucp.shopping": [
{"version": UCP_VERSION,
"spec": f"{UCP_SPEC}/specification/overview",
"transport": "mcp",
"schema": f"{UCP_SPEC}/services/shopping/mcp.openrpc.json",
"endpoint": f"http://localhost:{port}/mcp"}
]
},
"capabilities": {
**_capability("dev.ucp.shopping.catalog.search",
"shopping/catalog/search", "shopping/catalog_search.json"),
**_capability("dev.ucp.shopping.catalog.lookup",
"shopping/catalog/lookup", "shopping/catalog_lookup.json"),
**_capability("dev.ucp.shopping.checkout",
"shopping/checkout", "shopping/checkout.json"),
**_capability("dev.ucp.common.payment.ap2_mandate",
"payment/extensions/ap2-mandates",
"common/payment_ap2_mandate.json",
extends="dev.ucp.shopping.checkout",
config={"vp_formats_supported": {"dc+sd-jwt": {}}}),
},
"payment_handlers": payment_handlers,
},
"keys": [json.loads(key.export_public())],
}
# Check the profile against the UCP SDK models before returning it
BusinessSchema.model_validate(profile)
return profile
# ── MCP JSON-RPC endpoint ───────────────────────────────
@app.post("/mcp")
def mcp(body: dict):
tool = body["params"]["name"]
args = body["params"].get("arguments", {})
rid = body.get("id", "1")
if tool == "search_catalog":
q = args.get("catalog", {}).get("query", "").lower()
hits = [m for m in theater["movies"]
if not q or q in m["title"].lower()
or any(q in c.lower() for c in m["categories"])]
result = {"ucp": _ucp_meta("dev.ucp.shopping.catalog.search"),
"products": [_product(m) for m in hits]}
return _ok(rid, SearchResponse, result)
if tool == "lookup_catalog":
ids = args.get("catalog", {}).get("ids", [])
movies = [m for m in theater["movies"] if m["id"] in ids]
if not movies:
return _err(rid, "Not found")
result = {"ucp": _ucp_meta("dev.ucp.shopping.catalog.lookup"),
"products": [_product(m, lookup=True) for m in movies]}
return _ok(rid, LookupResponse, result)
if tool == "create_checkout":
co = args.get("checkout", {})
sid = f"chk_{uuid.uuid4().hex[:12]}"
items, subtotal = [], 0
for li in co.get("line_items", []):
st = _find_showtime(li["item"]["id"])
if not st:
continue
mv = _find_movie(li["item"]["id"])
qty = li.get("quantity", 1)
amt = st["price"] * qty
subtotal += amt
items.append({
"id": f"li_{uuid.uuid4().hex[:8]}",
"item": {
"id": st["id"],
"title": f"{mv['title']} ({st['format']}, {st['time']})",
"price": st["price"],
},
"quantity": qty,
"totals": [{"type": "subtotal", "amount": amt},
{"type": "total", "amount": amt}],
})
if not items:
return _err(rid, "No valid showtimes in checkout")
tax = int(subtotal * 0.08)
total = subtotal + tax
session = {
"ucp": {
**_ucp_meta("dev.ucp.shopping.checkout",
"dev.ucp.common.payment.ap2_mandate"),
"payment_handlers": payment_handlers,
},
"id": sid,
"status": "ready_for_complete",
"currency": "USD",
"line_items": items,
"totals": [
{"type": "subtotal", "display_text": "Subtotal", "amount": subtotal},
{"type": "tax", "display_text": "Tax", "amount": tax},
{"type": "total", "display_text": "Total", "amount": total},
],
"links": [{"type": "terms_of_service",
"url": f"http://localhost:{port}/terms"}],
"expires_at": (
datetime.now(timezone.utc) + timedelta(minutes=10)
).isoformat(),
}
_sign(session)
sessions[sid] = session
return _ok(rid, Checkout, session)
if tool == "get_checkout":
session = sessions.get(args.get("id"))
if not session:
return _err(rid, "Not found")
return _ok(rid, Checkout, session)
if tool == "complete_checkout":
sid = args.get("id")
session = sessions.get(sid)
if not session:
return _err(rid, "Not found")
co = args.get("checkout", {})
checkout_mandate = co.get("ap2", {}).get("checkout_mandate")
instruments = co.get("payment", {}).get("instruments", [])
if not checkout_mandate or not instruments:
return _err(rid, "mandate_required")
payment_mandate = instruments[0]["credential"]["token"]
# Mock shortcut: a real merchant fetches the platform's keys
# from its profile URL (meta["ucp-agent"]["profile"])
platform_key = JWK(**args["meta"]["ucp-agent"]["keys"][0])
try:
cm = MandateClient().verify(
checkout_mandate, platform_key, payload_type=CheckoutMandate
).mandate_payload
pm = MandateClient().verify(
payment_mandate, platform_key, payload_type=PaymentMandate
).mandate_payload
except Exception as e:
return _err(rid, f"mandate_invalid_signature: {e}")
# The mandates must point at the exact checkout this merchant signed
expected_hash = compute_sha256_b64url(checkout_jwts[sid])
total = next(t["amount"] for t in session["totals"] if t["type"] == "total")
if (cm.checkout_jwt != checkout_jwts[sid]
or cm.checkout_hash != expected_hash
or pm.transaction_id != expected_hash
or pm.payment_amount.amount != total):
return _err(rid, "mandate_scope_mismatch")
order_id = f"ord_{uuid.uuid4().hex[:8]}"
session["status"] = "completed"
session["order"] = {
"id": order_id,
"label": theater["name"],
"permalink_url": f"http://localhost:{port}/orders/{order_id}",
"tickets": [
{
"movie": li["item"]["title"],
"quantity": li["quantity"],
"ticket_code": uuid.uuid4().hex[:8].upper(),
}
for li in session["line_items"]
],
}
_sign(session)
return _ok(rid, Checkout, session)
return _err(rid, f"Unknown tool: {tool}")
def _sign(session):
"""Add the merchant's signature (a detached JWS) to the checkout."""
payload = {k: v for k, v in session.items() if k != "ap2"}
canonical = json.dumps(
payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False
)
jws = JWS(canonical.encode())
jws.add_signature(key, alg="ES256",
protected=json.dumps({"alg": "ES256", "kid": key.kid}))
checkout_jwt = jws.serialize(compact=True)
header, _, sig = checkout_jwt.split(".")
session["ap2"] = {"merchant_authorization": f"{header}..{sig}"}
checkout_jwts[session["id"]] = checkout_jwt
def _ucp_meta(*capabilities):
return {"version": UCP_VERSION,
"capabilities": {c: [{"version": UCP_VERSION}] for c in capabilities}}
def _ok(rid, model, result):
# Check the response against the UCP SDK models before returning it
model.model_validate(result)
return {"jsonrpc": "2.0", "id": rid, "result": {
"structuredContent": result,
"content": [{"type": "text", "text": json.dumps(result)}],
}}
def _err(rid, msg):
return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32000, "message": msg}}
def _product(movie, lookup=False):
prices = [st["price"] for st in movie["showtimes"]]
return {
"id": movie["id"],
"title": movie["title"],
"description": {"plain": f"{movie['title']} at {theater['name']}"},
"categories": [{"value": c, "taxonomy": "merchant"} for c in movie["categories"]],
"price_range": {
"min": {"amount": min(prices), "currency": "USD"},
"max": {"amount": max(prices), "currency": "USD"},
},
"variants": [
{
"id": st["id"],
"title": f"{st['format']} {st['time']}",
"description": {"plain": f"{st['format']} showing at {st['time']}"},
"options": [
{"name": "format", "label": st["format"]},
{"name": "time", "label": st["time"]},
],
"price": {"amount": st["price"], "currency": "USD"},
"availability": {"available": st["seats"] > 0},
"metadata": {"seats_available": st["seats"]},
**({"inputs": [{"id": movie["id"], "match": "featured"}]} if lookup else {}),
}
for st in movie["showtimes"]
],
}
def _find_showtime(sid):
return next(
(st for m in theater["movies"] for st in m["showtimes"] if st["id"] == sid),
None,
)
def _find_movie(sid):
return next(
(m for m in theater["movies"] for st in m["showtimes"] if st["id"] == sid),
None,
)
return app
def _run(port):
uvicorn.run(create_app(port), host="0.0.0.0", port=port, log_level="warning")
if __name__ == "__main__":
for port in THEATERS:
multiprocessing.Process(target=_run, args=(port,), daemon=True).start()
print("Merchants running: Meridian (:8081), StarLight (:8082)")
print("Press Ctrl+C to stop")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
這會建立兩個 FastAPI 伺服器,每個伺服器都有兩個端點:
GET /.well-known/ucp:UCP 探索。傳回商家的功能、MCP 端點網址、接受的付款方式和公開簽署金鑰。POST /mcp:MCP (Model Context Protocol) 作業。處理目錄搜尋、結帳和付款的 JSON-RPC 2.0 呼叫。
每位商家都會使用自己的金鑰簽署結帳程序、在完成訂單前驗證 AP2 授權,並根據 UCP SDK 模型檢查每項回應。
在新的終端機中啟動商家 (必須保持執行狀態):
cd ~/adk-agent-commerce
uv run python agent_payments/merchants.py
如下所示:
Merchants running: Meridian (:8081), StarLight (:8082)
返回第一個終端機,驗證 UCP 探索:
curl -s http://localhost:8081/.well-known/ucp | uv run python -m json.tool
你應該會看到商家的功能、MCP 端點網址、付款處理常式和公開金鑰。
8. 使用 ADK Web 執行代理
我們來使用 ADK CLI 內建的 Web UI!這會在瀏覽器中提供即時通訊介面,並自動處理工具確認提示。
您的專案現在應如下所示:
adk-agent-commerce/
├── pyproject.toml
└── agent_payments/
├── .env # Project settings
├── merchants.py # Mock UCP merchants
├── ucp_client.py # UCP client helper
├── ap2_handler.py # AP2 mandate handler
├── tools.py # Agent tools
└── agent.py # Agent definition
試試看
在第一個終端機中,前往 adk-agent-commerce 資料夾 (agent_payments 上方的資料夾),然後啟動 ADK 網頁版 UI:
cd ~/adk-agent-commerce
uv run adk web --port 8080 --allow_origins '*'
輸出內容應該會指出伺服器正在 http://127.0.0.1:8080 執行。
與服務專員交談
- 按住 Ctrl 鍵或 Cmd 鍵,然後點選網址,或按一下「Web Preview」(網頁預覽) 按鈕,然後選取「Preview on port 8080」(透過以下通訊埠預覽:8080),即可開啟 ADK 網頁介面。
- 如果尚未在下拉式選單中選取
agent_payments,請先選取。畫面上會顯示對話介面。 - 試著詢問:「有哪些電影正在上映?」
- 代理商會找出電影院並在幕後搜尋目錄,透過 UCP 彙整兩位商家提供的結果。
- 要求預訂電影票:「預訂《奧本海默》晚上 7 點的 2 張票」。
- 當代理嘗試呼叫
complete_purchase時,請注意 ADK Web UI 如何顯示包含購買詳細資料的確認卡! - 如要授權交易,請選取卡片上的「已確認」核取方塊,然後按一下「提交」。
- 代理人會完成購買程序,並將訂單確認資訊連同票券代碼傳送給您!
幕後到底發生了什麼事?
create_checkout→ 商家傳回以金鑰簽署的結帳程序 (ap2.merchant_authorization,即價格鎖定)complete_purchase→ 驗證商家簽章、建立 CheckoutMandate 和 PaymentMandate、將兩者簽署為 SD-JWT,然後傳送給商家- 商家已驗證授權,並確認授權指向簽署的結帳頁面 → 核發票券 (模擬)
9. 清理
為避免本機伺服器持續運作,請清理資源:
- 在執行
adk web的終端機中,按下 Ctrl+C 鍵停止代理程式伺服器。 - 在執行
merchants.py的終端機中,按下 Ctrl+C 鍵停止模擬商家。 - (選用) 如果您為這個程式碼實驗室建立了新的 Google Cloud 雲端專案,並想將其刪除,請執行下列指令,並將
替換為專案 ID:
gcloud projects delete <YOUR_PROJECT_ID>
10. 恭喜!🎉
您已建構 ADK 代理,可使用 UCP 和 AP2 探索商家、瀏覽目錄及完成購買。
您學到的內容
在本程式碼研究室中,您建構了可處理安全商務流程的 ADK 代理。以下摘要說明您建構的內容,以及套用的重要概念:
建構內容:
- 5 個代理工具,可包裝 UCP 和 AP2 作業:探索、目錄搜尋、結帳、付款。
- 簽署 AP2 委託書:商家簽署結帳 (價格鎖定) + CheckoutMandate 和 PaymentMandate (使用者授權)。
- 多商家搜尋:一個代理查詢多個劇院,合併結果。
重要概念:
通訊協定 | 用途 | 運作方式 |
UCP 探索 | 代理程式會尋找商家及其功能 |
|
UCP MCP | 代理程式瀏覽目錄、建立結帳程序 | 對商家 MCP 端點的 JSON-RPC 2.0 呼叫 |
商家授權 | 商家鎖定報價 | 商家簽署,涵蓋明細項目 + 總計 |
AP2 CheckoutMandate | 使用者核准確切結帳金額 | 由使用者簽署,內含商家簽署的結帳資訊 |
AP2 PaymentMandate | 使用者授權扣款 | 由使用者簽署,並參照結帳雜湊 |
正式版有何不同?
本程式碼研究室會使用模擬。實際運作中:
- UCP 探索會針對登錄檔 (而非硬式編碼的 localhost 網址) 進行解析
- MCP 端點由實際商家代管:採用相同的 JSON-RPC 2.0 通訊協定,提供真實的商品目錄
- AP2 強制執行是在使用者的信任裝置或信任平台簽署,而不是在代理程式啟動時產生金鑰
- 簽署金鑰來自各方的 UCP 設定檔 (模擬商家會在每個要求中收到代理商的公開金鑰)
- 付款授權會透過憑證提供者驗證 PaymentMandate,並徵求使用者同意
- 前端會將工具結果算繪為豐富的使用者介面 (產品格線、結帳摘要、確認資訊卡)
後續步驟
- 探索 AP2 通訊協定規格,並建構自己的付款功能代理
- 為商家導入通用商務通訊協定 (UCP),啟用代理式商務
- 將 AP2 與 A2A 連結,建立多代理商務工作流程
- 瞭解加密貨幣付款的 AP2 x402 擴充功能