AP2 と UCP でエージェント コマースを保護する

1. 概要

この Codelab では、次の 2 つのオープンソースの商取引プロトコルを使用して、複数の映画館のチケットを予約する ADK エージェントを実行します。

  • UCP(Universal Commerce Protocol): エージェントが販売者を検出し、カタログを検索し、購入手続きフローを管理するための標準。
  • AP2(Agent Payments Protocol): 暗号署名付きの委任を使用して、安全で検証可能な支払い承認を行うためのプロトコル。

デモアプリの CineAgent は、機能(座席の選択、特殊な形式、支払い方法)が異なる 2 つの架空の映画館販売者と接続し、検索から支払いまでの予約フロー全体をオーケストレートします。

学習内容

  • /.well-known/ucp プロファイルによる UCP 販売者の検出の仕組み
  • ADK エージェントが UCP を使用してカタログを検索し、チェックアウトを作成する方法
  • AP2 の必須項目(CheckoutMandate、PaymentMandate)による安全な取引の実現方法
  • エージェント e コマースを保護するエンドツーエンドの UCP プロトコルと AP2 プロトコルの仕組み

必要なもの

  • 課金を有効にした Google Cloud プロジェクト
  • ウェブブラウザ(Chrome など)
  • Cloud Shell ではなく独自のマシンでコードを実行する場合は、Python 3.11 以降と uv

この Codelab は、Python と Google Cloud にある程度精通している中級レベルのデベロッパーを対象としています。この Codelab を完了するには 30 分程度かかります。

この Codelab で作成するリソースの費用は 5 ドル未満です。

2. UCP プロトコルと AP2 プロトコルについて

エージェントの構築に入る前に、この安全なエージェント型コマースを可能にする 2 つのプロトコルについて説明します。

この Codelab では、UCP Python SDK を使用する UCP バージョン 2026-08-25 と、AP2 Python SDK を使用する AP2 v0.2 を使用します。

Universal Commerce Protocol(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. 購入手続きの委任状と支払いの委任状: 購入手続きの内容を確認した後、ユーザー(またはユーザーに代わってエージェント)が 2 つの委任状に署名します。CheckoutMandate には販売者が署名した購入手続きが含まれており、ユーザーが承認したことを販売者に伝えます。PaymentMandate は、その購入手続きの支払い金額を承認します。どちらも署名付きチェックアウトのハッシュを参照し、ユーザーの暗号署名を保持します。
  3. 署名確認: 販売者は両方の委任状を受け取ります。CheckoutMandate のユーザーの署名を検証し、その内部の購入手続きに販売者の署名が含まれていることを確認します。PaymentMandate は支払い側(認証情報プロバイダまたは決済代行業者)に送信され、そこで検証されてから送金が行われます。すべてが有効な場合、トランザクションは続行されます。

この「二重ロック」システムにより、販売者が過剰な請求をしたり、エージェントが承認なしで費用を支出したりすることを防ぎます。必須の認証情報は SD-JWT(Selective Disclosure 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 を作成し、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 がプリインストールされています。

  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 は、まだ PyPI で公開されていないため、GitHub リポジトリからインストールされます。(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 プロトコルの特定のオペレーションにマッピングされます。

ツール

機能

Protocol Action

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 では、エージェントの構築に焦点を当てるため、2 つのヘルパークラス 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. サーバーから提供された販売者 URL のリストを反復処理します。この Codelab では、後のセクションで 2 つのモック販売者を設定します。
  2. 各 URL に対して _ucp.discover(url) を呼び出し、/.well-known/ucp エンドポイントにヒットします。
  3. 名前、機能、支払いハンドラを収集して、概要リストにまとめます。
  4. エージェントが読み取れるように、リストを 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)

この操作を行うと:

  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 フィールドには、購入手続きに対する販売者の暗号署名が含まれており、見積もり価格がロックされています。後で変更することはできません。

購入を完了

このツールでは次の 3 つのことが行われます。

  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)

2 つの委任状が必要なのはなぜですか?CheckoutMandate は、販売者が署名した価格で、ユーザーがこの購入手続きを承認したことを販売者に証明します。PaymentMandate は、ユーザーがこの請求を承認したことを支払い側に証明します。フローは次のとおりです。

Merchant signs checkout -> User signs mandates -> Merchant and payment side verify -> Order completes。

チェックポイント: フル tools.py

これで、完全な tools.py には、UCP クライアントと AP2 クライアント用の 5 つのツール関数とモジュール レベルの初期化が含まれます。次のようになっていることを確認します。

"""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 販売者の場合は、エージェントに URL を指定すれば完了です。この Codelab では、ローカルでテストするために次の 2 つが必要です。

  1. モック販売者: UCP エンドポイントをシミュレートするローカル サーバー。テスト対象として使用します。
  2. プロトコル ヘルパー: HTTP 経由で販売者を呼び出し、プロトコル データと署名に UCP と AP2 の SDK を使用するシン ラッパー

注: このコードを注意深く読む必要はありません。これらのファイルは、実際の販売者とユーザーのウォレットをシミュレートします。そのままコピーします。

プロトコル ヘルパー

UCP SDK はデータモデルを提供し、AP2 SDK は委任状の署名と検証を行いますが、どちらにも販売者と通信するためのクライアントは含まれていません。この 2 つのファイルでそのギャップを埋めます。ap2 パッケージをシャドーイングしないように、ucp_client.py と ap2_handler.py という名前が付けられています。

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

これにより、それぞれ 2 つのエンドポイントを持つ 2 つの FastAPI サーバーが作成されます。

  • GET /.well-known/ucp: UCP 検出。販売者の機能、MCP エンドポイント URL、利用可能な支払い方法、公開署名鍵を返します。
  • 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 エンドポイント URL、決済ハンドラ、公開鍵が表示されます。

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 の 1 つ上のフォルダ)に移動し、ADK ウェブ UI を起動します。

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

サーバーが http://127.0.0.1:8080 で実行されていることを示す出力が表示されます。

エージェントと話す

  1. Ctrl または Cmd を押しながら URL をクリックするか、[ウェブでプレビュー] ボタンをクリックして [ポート 8080 でプレビュー] を選択して、ADK ウェブ UI を開きます。
  2. プルダウン メニューから agent_payments を選択します(選択されていない場合)。チャット インターフェースが表示されます。
  3. 「上映中の映画は?」と尋ねてみてください。
  4. エージェントは、舞台裏で劇場を検出し、カタログを検索し、UCP を介して両方の販売者の結果を集約します。
  5. チケットの予約を依頼する: 「オッペンハイマーのチケットを 2 枚、午後 7 時で予約して」。
  6. エージェントが complete_purchase を呼び出そうとすると、ADK Web UI に購入の詳細を含む確認カードが表示されます。
  7. 取引を承認するには、カードの [Confirmed] チェックボックスをオンにして、[Submit] をクリックします。
  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. おめでとうございます!🎉

UCP と AP2 を使用して、販売者を検出し、カタログを閲覧し、購入を完了する ADK エージェントを構築しました。

学習した内容

この Codelab では、安全な商取引フローを処理する ADK エージェントを構築しました。作成した内容と適用した主なコンセプトの概要は次のとおりです。

構築した内容:

  • UCP と AP2 オペレーション(検出、カタログ検索、購入手続き、支払い)をラップする 5 つのエージェント ツール。
  • AP2 委任状の署名: 販売者が署名した購入手続き(価格ロック)+ CheckoutMandate と PaymentMandate(ユーザー認証)。
  • マルチマーチャント検索: 1 つのエージェントが複数の映画館にクエリを実行し、結果を統合します。

主なコンセプト:

プロトコル

機能

仕組み

UCP Discovery

エージェントが販売者とその機能を検出する

/.well-known/ucp → 機能、MCP エンドポイント、お支払い方法、キー

UCP MCP

エージェントがカタログを閲覧し、チェックアウトを作成する

販売者の MCP エンドポイントへの JSON-RPC 2.0 呼び出し

販売者の承認

販売者が提示価格をロックする

販売者による署名、明細項目と合計をカバー

AP2 CheckoutMandate

ユーザーが正確な購入手続きを承認する

ユーザーによって署名され、販売者が署名した購入手続きが含まれています

AP2 PaymentMandate

ユーザーが請求を承認する

ユーザーが署名し、チェックアウト ハッシュを参照します

本番環境での違い

この Codelab ではモックを使用します。本番環境:

  • UCP 検出は、ハードコードされた localhost URL ではなく、レジストリに対して解決されます
  • MCP エンドポイントは実際の販売者によってホストされます。同じ JSON-RPC 2.0 プロトコル、実際の在庫
  • AP2 の必須事項は、エージェントが起動時に生成するキーではなく、ユーザーの信頼できるデバイスまたは信頼できるプラットフォームで署名されます。
  • 署名鍵は各当事者の UCP プロファイルから取得されます(モック販売者は各リクエストでエージェントの公開鍵を受け取ります)。
  • 支払いの承認は、PaymentMandate を検証し、ユーザーの同意を求める認証情報プロバイダを経由します。
  • フロントエンド: ツール結果をリッチ UI(商品グリッド、購入手続きの概要、確認カード)としてレンダリングします。

次のステップ

リファレンス ドキュメント