AP2 및 UCP로 안전한 에이전트 상거래

1. 개요

이 Codelab에서는 다음 두 가지 오픈소스 상거래 프로토콜을 사용하여 여러 극장 판매자에서 영화 티켓을 예약하는 ADK 에이전트를 실행합니다.

  • UCP (범용 커머스 프로토콜): 에이전트가 판매자를 검색하고, 카탈로그를 검색하고, 결제 절차를 관리하는 표준입니다.
  • AP2 (에이전트 결제 프로토콜): 암호화 방식으로 서명된 위임을 사용하여 안전하고 검증 가능한 결제 승인을 위한 프로토콜입니다.

데모 앱인 CineAgent는 기능 (좌석 선택, 전문 형식, 결제 수단)이 서로 다른 두 개의 모의 극장 판매자에 연결되어 검색부터 결제까지 전체 예약 흐름을 오케스트레이션합니다.

학습할 내용

  • /.well-known/ucp 프로필을 통한 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 Python SDK와 함께 UCP 버전 2026-08-25을 사용하고 AP2 Python SDK와 함께 AP2 v0.2를 사용합니다.

범용 커머스 프로토콜 (UCP)

UCP는 AI 에이전트가 판매자와 상호작용하는 방식을 표준화합니다. 표준화된 리소스 모델을 도입하여 에이전트가 모든 스토어의 맞춤 API를 학습해야 하는 문제를 해결합니다.

작동 방식:

  1. 탐색: UCP를 준수하는 모든 판매자는 표준 위치(/.well-known/ucp)에 프로필을 노출합니다. 예: Everlane의 UCP 엔드포인트. 상담사가 이 프로필을 읽으면 다음을 찾습니다.
    • 기능: 비즈니스에서 지원하는 독립형 핵심 기능입니다(예: 카탈로그 검색 또는 결제).
    • 서비스: 데이터를 교환하는 데 사용되는 하위 수준 통신 레이어입니다. 예: REST API, MCP (모델 컨텍스트 프로토콜), A2A (Agent2Agent 프로토콜)
    • 확장 프로그램: 판매자에게 전문적인 동작이 필요한 경우 이 프로필에서 맞춤 확장 프로그램을 정의할 수 있습니다.
    • 키: 상담사가 판매자의 서명을 확인하는 데 사용하는 판매자의 공개 서명 키입니다.
  2. 작업: 검색되면 에이전트가 제공된 서비스 엔드포인트를 사용하여 작업을 실행합니다. 이 Codelab에서는 모델 컨텍스트 프로토콜 (MCP)을 서비스 전송으로 사용합니다. 에이전트는 이 엔드포인트에 JSON-RPC 2.0 호출을 하여 검색된 기능(제품 검색, 결제 생성, 구매 완료)을 호출합니다.

UCP 워크플로

에이전트 결제 프로토콜 (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를 만들고 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 프로토콜의 특정 작업에 매핑됩니다.

도구

기능

프로토콜 작업

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): 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)

기능:

  1. 서버에서 제공하는 판매자 URL 목록을 반복합니다. 이 Codelab의 뒷부분에서는 모의 판매자 두 명을 설정합니다.
  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. 검색 카탈로그 JSON-RPC 요청 (_ucp.mcp_call(url, "search_catalog", {"catalog": {"query": query}}))을 판매자의 MCP 엔드포인트로 전송합니다.
  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. Google은 결제를 가져와서 결제에 대한 판매자의 서명을 확인합니다.
  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 판매자의 경우 에이전트가 URL을 가리키면 됩니다. 이 Codelab에서는 로컬에서 테스트하기 위해 다음 두 가지가 필요합니다.

  1. 모의 판매자: 테스트할 수 있도록 UCP 엔드포인트를 시뮬레이션하는 로컬 서버
  2. 프로토콜 도우미: HTTP를 통해 판매자에게 전화하고 프로토콜 데이터 및 서명에 UCP 및 AP2 SDK를 사용하는 씬 래퍼

참고: 이 코드를 자세히 읽지 않아도 됩니다. 이러한 파일은 실제 판매자와 사용자의 지갑을 시뮬레이션합니다. 있는 그대로 복사합니다.

프로토콜 도우미

UCP SDK는 데이터 모델을 제공하고 AP2 SDK는 위임을 서명하고 확인하지만, 둘 다 판매자와 통신하는 클라이언트는 포함하지 않습니다. 이 두 파일이 그 간극을 메웁니다. 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

이렇게 하면 각각 엔드포인트가 두 개인 FastAPI 서버 두 개가 생성됩니다.

  • GET /.well-known/ucp: UCP 검색 판매자의 기능, MCP 엔드포인트 URL, 허용되는 결제 수단, 공개 서명 키를 반환합니다.
  • 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 엔드포인트 URL, 결제 핸들러, 공개 키가 표시됩니다.

8. ADK 웹으로 에이전트 실행

ADK CLI의 내장 웹 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에서 실행되고 있음을 나타내는 출력이 표시됩니다.

상담사와 상담하기

  1. URL을 Ctrl 또는 Cmd 클릭하거나 웹 미리보기 버튼을 클릭하고 포트 8080에서 미리보기를 선택하여 ADK 웹 UI를 엽니다.
  2. 아직 선택하지 않았다면 드롭다운 메뉴에서 agent_payments를 선택합니다. 채팅 인터페이스가 표시됩니다.
  3. '상영 중인 영화는?'이라고 질문해 보세요.
  4. 상담사는 백그라운드에서 영화관을 검색하고 카탈로그를 검색하여 UCP를 통해 두 판매자의 결과를 집계합니다.
  5. 티켓 예약을 요청합니다. "오후 7시에 오펜하이머 티켓 2장 예약해 줘."
  6. 에이전트가 complete_purchase를 호출하려고 하면 ADK 웹 UI에 구매 세부정보가 포함된 확인 카드가 표시됩니다.
  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. 수고하셨습니다 🎉

UCP와 AP2를 사용하여 판매자를 검색하고, 카탈로그를 탐색하고, 구매를 완료하는 ADK 에이전트를 빌드했습니다.

학습한 내용

이 Codelab에서는 보안 상거래 흐름을 처리하는 ADK 에이전트를 빌드했습니다. 빌드한 항목과 적용한 주요 개념을 요약하면 다음과 같습니다.

빌드한 항목:

  • UCP 및 AP2 작업을 래핑하는 5가지 에이전트 도구: 검색, 카탈로그 검색, 결제, 결제
  • AP2 위임장 서명: 판매자가 서명한 결제 (가격 고정) + CheckoutMandate 및 PaymentMandate (사용자 승인)
  • 다중 판매자 검색: 한 에이전트가 여러 극장을 쿼리하고 결과를 병합합니다.

주요 개념:

프로토콜

기능

작동 방식

UCP 탐색

에이전트가 판매자와 판매자의 기능을 찾음

/.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 (제품 그리드, 결제 요약, 확인 카드)로 렌더링합니다.

다음 단계

참조 문서