使用 AP2 和 UCP 保护智能体商务

1. 概览

在此 Codelab 中,您将运行一个 ADK 代理,该代理使用两个开源商务协议在多个影院商家处预订电影票:

  • UCP(通用商务协议):一种标准,用于让智能体发现商家、搜索目录和管理结账流程。
  • AP2(Agent Payments Protocol,代理支付协议):一种协议,用于使用经过加密签名的授权书实现安全、可验证的支付授权。

演示应用 CineAgent 连接到两个具有不同功能(选座、特殊格式和付款方式)的模拟影院商家,并编排从搜索到付款的完整预订流程。

学习内容

  • UCP 商家发现功能如何通过/.well-known/ucp资料运作
  • ADK 智能体如何使用 UCP 搜索目录和创建结账
  • AP2 授权书(CheckoutMandate、PaymentMandate)如何保障交易安全
  • 端到端 UCP 和 AP2 协议如何保障智能体电子商务的安全

所需条件

  • 启用了结算功能的 Google Cloud 项目
  • 网络浏览器,例如 Chrome
  • Python 3.11 及更高版本和 uv(如果您在自己的机器上运行代码,而不是在 Cloud Shell 中运行)

本 Codelab 适用于对 Python 和 Google Cloud 有一定了解的中级开发者。完成本 Codelab 大约需要 30 分钟。

本 Codelab 中创建的资源费用应低于 5 美元。

2. 了解 UCP 和 AP2 协议

在深入了解如何构建智能体之前,我们先来了解一下使这种安全的智能体商务成为可能的两种协议。

此 Codelab 使用 UCP 版本 2026-08-25 和 UCP Python SDK,以及 AP2 v0.2 和 AP2 Python SDK。

通用商务协议 (UCP)

UCP 可标准化 AI 智能体与商家的互动方式。它引入了标准化的资源模型,解决了代理必须学习每个商店的自定义 API 的问题。

工作原理:

  1. 发现:每个符合 UCP 标准的商家都会在标准位置 /.well-known/ucp 公开其资料。示例:Everlane 的 UCP 端点。当代理读取此配置文件时,它会查找:
    • 功能:商家支持的独立核心功能,例如目录搜索或结账。
    • 服务:用于交换数据的较低级别通信层。示例:REST API、MCP(Model Context Protocol)、A2A(Agent2Agent Protocol)。
    • 扩展程序:如果商家需要特殊行为,可以在此配置文件中定义自定义扩展程序。
    • 密钥:商家的公开签名密钥,代理使用这些密钥来检查商家的签名。
  2. 操作:发现服务后,代理会使用提供的服务端点来执行操作。在此 Codelab 中,我们将 Model Context Protocol (MCP) 用作服务传输。代理会向此端点发出 JSON-RPC 2.0 调用,以调用发现的功能:搜索商品、创建结账会话和完成购买交易。

UCP 工作流程

Agent Payments Protocol (AP2)

AP2 规范了代理代表用户授权付款的方式。它解决了智能体处理敏感支付凭据的安全问题。

工作原理:

  1. 商家签名:当代理使用 UCP 协议创建结账时,商家会对结账(订单项和总计)进行签名,并在 ap2.merchant_authorization 中返回签名。它可作为价格锁定保证。如果商家在签名后更改价格,签名将不再匹配。
  2. 结账授权书和支付授权书:在验证结账内容后,用户(或代表用户的代理)签署两项授权书。CheckoutMandate 包含商家签名的结账信息,用于告知商家用户已批准该结账信息。PaymentMandate 授权相应结账交易的付款金额。两者都引用了已签名的结账交易的哈希值,并包含用户的加密签名。
  3. 签名验证:商家收到两份授权书。它会验证 CheckoutMandate 中用户的签名,并检查其中的结账交易是否带有商家的自有签名。PaymentMandate 会发送给付款方(凭据提供方或付款处理方),付款方会在验证该令牌后才转移资金。如果一切有效,交易将继续进行。

这种“双重锁定”系统可确保商家不会过度收费,代理也不会在未经授权的情况下消费。强制性凭据是 SD-JWT(选择性披露 JWT)凭据,可通过仅披露各方需要的字段来保护用户隐私。在 AP2 v0.2 中,CheckoutMandate 取代了 AP2 v0.1 中的 CartMandate。

AP2 工作流程

3. 设置您的环境

Google Cloud 项目设置

创建 Google Cloud 项目

  1. 在 Google Cloud 控制台的项目选择器页面上,选择或创建一个 Google Cloud 项目。
  2. 确保您的 Cloud 项目已启用结算功能。了解如何检查项目是否已启用结算功能。

启动 Cloud Shell

Cloud Shell 是在 Google Cloud 中运行的命令行环境,预加载了必要的工具。

  1. 点击 Google Cloud 控制台顶部的激活 Cloud Shell。
  2. 连接到 Cloud Shell 后,验证您的身份验证:
    gcloud auth list
    
  3. 确认您的项目已配置:
    gcloud config get project
    
  4. 如果项目未按预期设置,请进行设置:
    export PROJECT_ID=<YOUR_PROJECT_ID>
    gcloud config set project $PROJECT_ID
    

启用 API

运行以下命令以启用所需的 API:

gcloud services enable aiplatform.googleapis.com

设置目录结构

复制并粘贴以下命令,以创建一个用于存放此 Codelab 的文件夹,并在其中创建一个用于存放代理代码的 agent_payments 文件夹:

mkdir -p ~/adk-agent-commerce/agent_payments
cd ~/adk-agent-commerce

使用 Gemini 模型

复制并粘贴以下命令,以使用您的云项目和位置创建 agent_payments/.env,并通过您的 Google Cloud 项目让 ADK 调用 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,用于管理环境和依赖项。

  1. 在 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 软件包是一个无关的项目。)

  1. 运行以下命令以创建虚拟环境并安装所有依赖项:
uv sync

uv 会为此 Codelab 创建一个隔离的 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 协议中的特定操作:

工具

作用

协议操作

discover_theaters

查找商家及其支持情况

查询 /.well-known/ucp

search_movies

搜索不同商家的目录

JSON-RPC 到 MCP 端点

get_movie_detail

获取特定商家的放映时间

JSON-RPC 到 MCP 端点

create_checkout

启动结账会话

JSON-RPC 到 MCP 端点

complete_purchase

授权付款并完成订单

签署 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])

了解设置

为了让此 Codelab 专注于构建智能体,我们使用了两个辅助类 UCPClient 和 AP2Handler,我们将在后面的步骤中介绍这两个类。

  • 它们是什么?:这些是我们为此 Codelab 编写的小型辅助类,用于与模拟商家通信。官方 SDK 提供协议组件:UCP SDK 包含每个 UCP 架构的数据模型,而 AP2 SDK 则用于创建和验证已签名的授权。这两个 SDK 均不包含用于调用商家的客户端,因此这些辅助程序会处理该部分。
  • 目前,请将它们视为辅助对象:
    • _ucp.discover(url):提取并验证商家的个人资料。
    • _ucp.mcp_call(url, method, params):向商家的 MCP 端点发送 JSON-RPC 2.0 请求。

探索影院

此工具是 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)

作用:

  1. 它会遍历服务器提供的商家网址列表。在此 Codelab 中,我们将在后面的部分中设置两个模拟商家。
  2. 对于每个网址,它都会调用 _ucp.discover(url),从而命中 /.well-known/ucp 端点。
  3. 它会将名称、功能和付款处理程序收集到摘要列表中。
  4. 它会以 JSON 字符串的形式返回该列表,供代理读取。

搜索电影

此工具会搜索所有已发现的商家,并合并搜索结果。这一点至关重要,因为同一部电影可能会在多家影院以不同的格式(IMAX、杜比)和不同的价格放映。

添加到 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)

作用:

  1. 它会遍历所有已发现的影院。
  2. 它会向商家的 MCP 端点发送搜索目录 JSON-RPC 请求 (_ucp.mcp_call(url, "search_catalog", {"catalog": {"query": query}}))。
  3. 然后,它会进行一些清理工作,以解析结果,找到电影及其“变体”(表示具体的放映时间和格式)。按 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)

作用:

  1. 它会调用商家的 MCP 端点上的 create_checkout 方法。
  2. 它会传递用户请求的 showtime_id 和 quantity。
  3. 商家返回使用商家密钥签名的结账信息。

注意:如果您检查响应数据,会发现 ap2.merchant_authorization 字段包含商家对结账交易的加密签名,用于锁定报价。他们以后无法更改!

完成购买

此工具会执行以下三项操作:

  1. 我们获取结账信息,并验证其中的商家签名。
  2. 使用 AP2 SDK 创建并签署 CheckoutMandate 和 PaymentMandate。
  3. 将这两份授权书发送给商家,以便完成购买交易。

添加到 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 向商家证明,用户已批准以商家签名的价格进行此确切的结账交易。PaymentMandate 向付款方证明用户已授权此扣款。流程如下:

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 商家,您只需将智能体指向其网址即可。在此 Codelab 中,我们需要在本地测试两项内容:

  1. 模拟商家:模拟 UCP 端点的本地服务器,以便您进行测试
  2. 协议辅助程序:通过 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(模型上下文协议)操作。处理目录搜索、结账和付款的 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 界面!这会在浏览器中提供聊天界面,并自动处理工具确认提示。

您的项目现在应如下所示:

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 Web 界面:

cd ~/adk-agent-commerce
uv run adk web --port 8080 --allow_origins '*'

您应该会看到输出,指示服务器正在 http://127.0.0.1:8080 上运行。

与客服人员对话

  1. 按住 Ctrl 键或 Cmd 键的同时点击相应网址,或者点击网页预览按钮并选择在端口 8080 上预览,以打开 ADK 网页界面。
  2. 从下拉菜单中选择 agent_payments(如果尚未选择)。您将看到一个聊天界面。
  3. 尝试询问:“有哪些电影正在放映?”
  4. 代理会在后台发现影院并搜索目录,然后通过 UCP 汇总来自两个商家的结果。
  5. 要求预订电影票:“预订 2 张《奥本海默》的电影票,时间为晚上 7 点”。
  6. 当智能体尝试调用 complete_purchase 时,请注意 ADK 网页界面如何显示包含购买详情的确认卡片!
  7. 如需授权交易,请选中卡上的已确认复选框,然后点击提交。
  8. 智能体将完成购买交易,并返回包含门票代码的订单确认信息!

幕后会发生些什么:

  1. create_checkout → 商家返回了使用其密钥 (ap2.merchant_authorization,价格锁定) 签名的结账信息
  2. complete_purchase → 验证了商家的签名,创建了 CheckoutMandate 和 PaymentMandate,将两者作为 SD-JWT 进行签名,并将其发送给商家
  3. 商家验证了两个授权,并检查了它们是否指向已签名的结账交易 → 已签发支持请求(在模拟环境中)

9. 清理

为避免本地服务器持续运行,请清理资源:

  1. 在运行 adk web 的终端中,按 Ctrl+C 停止代理服务器。
  2. 在运行 merchants.py 的终端中,按 Ctrl+C 停止模拟商家。
  3. (可选)如果您为此 Codelab 创建了一个新的 Google Cloud 项目,并希望将其删除,请运行以下命令,并将 替换为该项目的 ID:
gcloud projects delete <YOUR_PROJECT_ID>

10. 恭喜!🎉

您构建了一个 ADK 代理,该代理使用 UCP 和 AP2 发现商家、浏览目录并完成购买交易。

要点回顾

在此 Codelab 中,您构建了一个可处理安全商务流程的 ADK 智能体。以下是您构建的内容以及应用的关键概念的总结:

构建内容:

  • 5 个代理工具,封装了 UCP 和 AP2 操作:发现、目录搜索、结账、付款。
  • AP2 授权签署:商家签署的结账(价格锁定)+ CheckoutMandate 和 PaymentMandate(用户授权)。
  • 多商家搜索:一个代理查询多个影院,合并结果。

主要概念:

协议

作用

运作方式

UCP Discovery

智能体查找商家及其功能

/.well-known/ucp → 功能、MCP 端点、付款方式、密钥

UCP MCP

智能体浏览目录、创建结账

对商家的 MCP 端点的 JSON-RPC 2.0 调用

商家授权

商家锁定报价

由商家签名,涵盖订单项和总计

AP2 结账强制执行

用户批准确切的结账金额

由用户签名,包含商家签名的结账信息

AP2 PaymentMandate

用户授权扣款

由用户签名,引用结账哈希

生产环境中有何不同?

此 Codelab 使用模拟对象。正式版:

  • UCP 发现针对注册表(而非硬编码的本地主机网址)进行解析
  • MCP 端点由真实商家托管:采用相同的 JSON-RPC 2.0 协议,提供真实的商品目录
  • AP2 强制执行在用户的受信任设备上或由受信任的平台签名,而不是使用代理在启动时生成的密钥签名
  • 签名密钥来自各方的 UCP 个人资料(模拟商家会在每个请求中收到代理的公钥)
  • 付款授权通过凭据提供方进行,该提供方会验证 PaymentMandate 并征求用户同意
  • 前端以丰富的界面(商品网格、结账摘要、确认卡片)呈现工具结果

后续步骤

  • 探索 AP2 协议规范并构建自己的支持付款的智能体
  • 为商家实现 UCP 以启用智能体商务
  • 将 AP2 与 A2A 搭配使用,实现多智能体商业工作流
  • 了解加密货币付款的 AP2 x402 扩展功能

参考文档