Secure Agent Commerce ด้วย AP2 และ UCP

1. ภาพรวม

ใน Codelab นี้ คุณจะเรียกใช้ Agent ADK ที่จองตั๋วภาพยนตร์จากผู้ขายโรงภาพยนตร์หลายรายโดยใช้โปรโตคอลการค้าแบบโอเพนซอร์ส 2 รายการ ได้แก่

  • UCP (Universal Commerce Protocol): มาตรฐานสำหรับ Agent ในการค้นหาผู้ขาย ค้นหาแคตตาล็อก และจัดการขั้นตอนการชำระเงิน
  • AP2 (Agent Payments Protocol): โปรโตคอลสำหรับการให้สิทธิ์การชำระเงินที่ปลอดภัยและตรวจสอบได้โดยใช้คำสั่งที่ลงนามด้วยการเข้ารหัส

แอปเดโม CineAgent เชื่อมต่อกับผู้ขายโรงภาพยนตร์จำลอง 2 รายที่มีความสามารถแตกต่างกัน (การเลือกที่นั่ง รูปแบบเฉพาะ และวิธีการชำระเงิน) และจัดระเบียบขั้นตอนการจองทั้งหมดตั้งแต่การค้นหาไปจนถึงการชำระเงิน

สิ่งที่คุณจะได้เรียนรู้

  • วิธีการค้นพบผู้ขาย UCP ผ่าน/.well-known/ucpโปรไฟล์
  • วิธีที่เอเจนต์ ADK ใช้ UCP เพื่อค้นหาแคตตาล็อกและสร้างการชำระเงิน
  • วิธีที่ AP2 กำหนดให้ (CheckoutMandate, PaymentMandate) ทำธุรกรรมอย่างปลอดภัย
  • วิธีการทำงานของโปรโตคอล UCP และ AP2 แบบต้นทางถึงปลายทางเพื่อรักษาความปลอดภัยของอีคอมเมิร์ซที่ดำเนินการโดย Agentic AI

สิ่งที่คุณต้องมี

  • โปรเจ็กต์ Google Cloud ที่เปิดใช้การเรียกเก็บเงิน
  • เว็บเบราว์เซอร์ เช่น Chrome
  • Python 3.11 ขึ้นไปและ uv หากคุณเรียกใช้โค้ดในเครื่องของคุณเองแทน Cloud Shell

Codelab นี้เหมาะสำหรับนักพัฒนาแอประดับกลางที่มีความคุ้นเคยกับ Python และ Google Cloud บ้าง Codelab นี้ใช้เวลาประมาณ 30 นาที

ทรัพยากรที่สร้างในโค้ดแล็บนี้ควรมีค่าใช้จ่ายน้อยกว่า $5

2. ทำความเข้าใจโปรโตคอล UCP และ AP2

ก่อนที่จะเจาะลึกเรื่องการสร้างเอเจนต์ เรามาทำความเข้าใจ 2 โปรโตคอลที่ทำให้ระบบอีคอมเมิร์ซแบบเป็น Agent ที่ปลอดภัยนี้เป็นไปได้กันก่อน

Codelab นี้ใช้ UCP เวอร์ชัน 2026-08-25 กับ UCP Python SDK และ AP2 v0.2 กับ AP2 Python SDK

Universal Commerce Protocol (UCP)

UCP จะกำหนดมาตรฐานวิธีที่เอเจนต์ AI โต้ตอบกับผู้ขาย โดยจะช่วยแก้ปัญหาที่เอเจนต์ต้องเรียนรู้ API ที่กำหนดเองสำหรับร้านค้าทุกร้านด้วยการเปิดตัวโมเดลทรัพยากรที่ได้มาตรฐาน

วิธีการทำงาน

  1. การค้นพบ: ผู้ขายทุกรายที่ปฏิบัติตามข้อกำหนดของ UCP จะแสดงโปรไฟล์ในตำแหน่งมาตรฐาน /.well-known/ucp ตัวอย่าง: ปลายทาง UCP ของ Everlane เมื่อ Agent อ่านโปรไฟล์นี้ Agent จะมองหาข้อมูลต่อไปนี้
    • ความสามารถ: ฟีเจอร์หลักแบบสแตนด์อโลนที่ธุรกิจรองรับ เช่น การค้นหาแคตตาล็อกหรือการชำระเงิน
    • บริการ: เลเยอร์การสื่อสารระดับล่างที่ใช้ในการแลกเปลี่ยนข้อมูล ตัวอย่าง: 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 จะอนุมัติจำนวนเงินที่ชำระสำหรับการชำระเงินนั้น ทั้ง 2 รายการอ้างอิงแฮชของการชำระเงินที่ลงนามและมีลายเซ็นเข้ารหัสของผู้ใช้
  3. การยืนยันลายเซ็น: ผู้ขายจะได้รับทั้ง 2 คำสั่ง โดยจะยืนยันลายเซ็นของผู้ใช้ใน CheckoutMandate และตรวจสอบว่าการชำระเงินภายในมีลายเซ็นของผู้ขายเอง PaymentMandate จะไปที่ฝั่งการชำระเงิน (ผู้ให้บริการข้อมูลเข้าสู่ระบบหรือผู้ประมวลผลการชำระเงิน) ซึ่งจะยืนยันก่อนที่จะโอนเงิน หากทุกอย่างถูกต้อง ธุรกรรมจะดำเนินการต่อ

ระบบ "ล็อก 2 ชั้น" นี้ช่วยให้มั่นใจได้ว่าผู้ขายจะไม่เรียกเก็บเงินมากเกินไป และตัวแทนจะไม่สามารถใช้จ่ายได้โดยไม่ได้รับอนุญาต คำสั่งคือข้อมูลเข้าสู่ระบบ SD-JWT (JWT การเปิดเผยข้อมูลแบบเลือก) ซึ่งปกป้องความเป็นส่วนตัวของผู้ใช้โดยการเปิดเผยเฉพาะฟิลด์ที่แต่ละฝ่ายต้องการ ใน AP2 v0.2 CheckoutMandate จะแทนที่ CartMandate จาก AP2 v0.1

เวิร์กโฟลว์ AP2

3. ตั้งค่าสภาพแวดล้อม

การตั้งค่าโปรเจ็กต์ Google Cloud

สร้างโปรเจ็กต์ Google Cloud

  1. ในคอนโซล Google Cloud ให้เลือกหรือสร้างโปรเจ็กต์ Google Cloud ในหน้าตัวเลือกโปรเจ็กต์
  2. ตรวจสอบว่าโปรเจ็กต์ที่อยู่ในระบบคลาวด์เปิดใช้การเรียกเก็บเงินแล้ว ดูวิธีตรวจสอบว่าได้เปิดใช้การเรียกเก็บเงินในโปรเจ็กต์แล้วหรือไม่

เริ่มต้น Cloud Shell

Cloud Shell คือสภาพแวดล้อมบรรทัดคำสั่งที่ทำงานใน Google Cloud ซึ่งโหลดเครื่องมือที่จำเป็นไว้ล่วงหน้า

  1. คลิกเปิดใช้งาน Cloud Shell ที่ด้านบนของคอนโซล Google Cloud
  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 อยู่ภายในสำหรับโค้ดของ Agent

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

เข้าถึงโมเดล Gemini

คัดลอกและวางคำสั่งต่อไปนี้เพื่อสร้าง agent_payments/.env ด้วยโปรเจ็กต์ที่อยู่ในระบบคลาวด์และสถานที่ตั้งของคุณ และเพื่อให้ ADK เรียกใช้ Gemini ผ่านโปรเจ็กต์ Google Cloud 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

ติดตั้งทรัพยากร Dependency

Google Cloud Shell ติดตั้ง uv มาให้ล่วงหน้าเพื่อจัดการสภาพแวดล้อมและทรัพยากร Dependency

  1. สร้างไฟล์ pyproject.toml ที่รูทของโฟลเดอร์ adk-agent-commerce แล้วเพิ่มเนื้อหาต่อไปนี้ลงในไฟล์ ไฟล์นี้กำหนดข้อมูลเมตาของโปรเจ็กต์และการอ้างอิง
[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 (แพ็กเกจ ap2 ใน PyPI เป็นโปรเจ็กต์ที่ไม่เกี่ยวข้อง)

  1. เรียกใช้คำสั่งต่อไปนี้เพื่อสร้างสภาพแวดล้อมเสมือนและติดตั้งทรัพยากร Dependency ทั้งหมด
uv sync

uv จะสร้างสภาพแวดล้อม Python ที่แยกต่างหากสำหรับ Codelab นี้ คุณจึงไม่ต้องเปิดใช้งานสิ่งใด นำหน้าคำสั่ง Python ด้วย uv run

4. กำหนด Agent

ก่อนเขียนตรรกะของเครื่องมือใดๆ เรามากำหนดเอเจนต์ในไฟล์ที่ชื่อ agent.py กันก่อน Agent นี้จะทำหน้าที่เป็นผู้ประสานงานสำหรับขั้นตอนการจองภาพยนตร์

สร้าง 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),
    ],
)

คำอธิบายโค้ด

มาดูรายละเอียดสิ่งที่เกิดขึ้นในคำจำกัดความของ Agent นี้กัน

  • model=Gemini(...): เราใช้ Gemini 3.8 Flash สำหรับการให้เหตุผลและการใช้เครื่องมือ
  • instruction: นี่คือพรอมต์ที่กำหนดลักษณะการทำงานของ Agent โดยจะบอกเอเจนต์อย่างชัดเจนให้ใช้ UCP และ AP2 แสดงรายการเครื่องมือที่มี และกำหนดกฎที่สำคัญ เช่น "ห้ามสร้างข้อมูลขึ้นมา" และ "ราคาเป็นหน่วยเซ็นต์"
  • tools: นี่คือรายการฟังก์ชัน Python (ซึ่งเราจะสร้างขึ้นในขั้นตอนถัดไป) ที่เอเจนต์สามารถเลือกเรียกใช้ตามคำขอของผู้ใช้
  • require_confirmation: คุณสามารถรวมเครื่องมือใดก็ได้กับ FunctionTool(my_function,require_confirmation=True) เมื่อทริกเกอร์ทำงาน เอเจนต์จะหยุดชั่วคราวและรอการอนุมัติแบบง่ายๆ ว่า "ใช่" หรือ "ไม่" ก่อนที่จะดำเนินการเครื่องมือ ในที่นี้ ก่อนที่จะเรียกใช้เครื่องมือ complete_purchase Agent จะหยุดชั่วคราวเพื่อรอการยืนยันจากเจ้าหน้าที่

รายการเครื่องมือ

คำจำกัดความของ Agent จะประกาศสิ่งที่เราต้องสร้าง เครื่องมือแต่ละอย่างจะเชื่อมโยงกับการดำเนินการที่เฉพาะเจาะจงในโปรโตคอล 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

ให้สิทธิ์การชำระเงินและทำคำสั่งซื้อให้เสร็จสมบูรณ์

Signs AP2 Mandates & sends to 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 อย่างเป็นทางการมีส่วนประกอบของโปรโตคอล ได้แก่ SDK ของ UCP มีโมเดลข้อมูลสำหรับทุกสคีมาของ UCP และ SDK ของ AP2 สร้างและยืนยันคำสั่งที่ลงนาม SDK ทั้ง 2 รายการไม่มีไคลเอ็นต์สำหรับการโทรหาผู้ขาย ดังนั้นตัวช่วยเหล่านี้จึงจัดการส่วนนั้น
  • ในตอนนี้ ให้ถือว่าออบเจ็กต์เหล่านี้เป็นออบเจ็กต์ตัวช่วย:
    • _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 รายในส่วนท้าย
  2. สำหรับแต่ละ URL ระบบจะเรียกใช้ _ucp.discover(url) ซึ่งจะส่งคำขอไปยังปลายทาง /.well-known/ucp
  3. โดยจะรวบรวมชื่อ ความสามารถ และตัวแฮนเดิลการชำระเงินไว้ในรายการสรุป
  4. โดยจะแสดงรายการเป็นสตริง JSON เพื่อให้ Agent อ่านได้

ค้นหาภาพยนตร์

เครื่องมือนี้จะค้นหาผู้ขายทั้งหมดที่พบและผสานผลลัพธ์ ซึ่งเป็นสิ่งสำคัญเนื่องจากภาพยนตร์เรื่องเดียวกันอาจฉายในโรงภาพยนตร์หลายแห่งที่มีรูปแบบ (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. จากนั้นระบบจะทำการล้างข้อมูลเล็กน้อยเพื่อแยกวิเคราะห์ผลลัพธ์เพื่อค้นหาภาพยนตร์และ "ตัวแปร" ของภาพยนตร์ (ซึ่งแสดงถึงเวลาฉายและรูปแบบที่เฉพาะเจาะจง) จัดกลุ่มภาพยนตร์ตามรหัสเพื่อให้ผู้ใช้ไม่เห็นรายการภาพยนตร์ที่ซ้ำกัน

รับรายละเอียดภาพยนตร์

เครื่องมือนี้จะดึงรายละเอียดแคตตาล็อกทั้งหมดสำหรับภาพยนตร์เรื่องหนึ่งๆ ในโรงภาพยนตร์ที่เฉพาะเจาะจง

เพิ่มไปยัง 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)

การดำเนินการนี้จะทำสิ่งต่อไปนี้

  • โดยจะเรียกใช้เมธอด lookup_catalog ที่ปลายทาง MCP ของผู้ขาย และส่ง movie_id ที่เฉพาะเจาะจงใน catalog.ids ซึ่งจะแสดงข้อมูลโดยละเอียด เช่น เวลาฉายและความพร้อมจำหน่ายที่นั่งสำหรับโรงภาพยนตร์นั้นๆ

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. โดยจะเรียกใช้เมธอด create_checkout ที่ปลายทาง MCP ของผู้ขาย
  2. โดยจะส่ง showtime_id และ quantity ที่ผู้ใช้ขอ
  3. ผู้ขายจะแสดงหน้าชำระเงินที่ลงนามด้วยคีย์ของผู้ขาย

หมายเหตุ: หากตรวจสอบข้อมูลการตอบกลับ ฟิลด์ ap2.merchant_authorization จะมีลายเซ็นเข้ารหัสของ Merchant ในการชำระเงิน ซึ่งจะล็อกราคาที่เสนอ โดยผู้ใช้จะเปลี่ยนข้อมูลนี้ในภายหลังไม่ได้

ดำเนินการซื้อให้เสร็จสมบูรณ์

เครื่องมือนี้จะดำเนินการ 3 อย่าง ดังนี้

  1. เราจะได้รับการชำระเงินและยืนยันลายเซ็นของผู้ขายในการชำระเงิน
  2. สร้างและลงนามใน CheckoutMandate และ PaymentMandate ด้วย AP2 SDK
  3. ส่งทั้ง 2 คำสั่งไปยังผู้ขายเพื่อทำการซื้อให้เสร็จสมบูรณ์

เพิ่มไปยัง 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 ที่สมบูรณ์ของคุณควรมีฟังก์ชันเครื่องมือ 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 นี้ เราต้องมี 2 สิ่งเพื่อทดสอบในเครื่อง ได้แก่

  1. ผู้ขายจำลอง: เซิร์ฟเวอร์ในพื้นที่ที่จำลองปลายทาง UCP เพื่อให้คุณมีสิ่งที่ใช้ทดสอบ
  2. ตัวช่วยโปรโตคอล: Wrapper แบบบางที่เรียกผู้ขายผ่าน HTTP และใช้ SDK ของ UCP และ AP2 สำหรับข้อมูลโปรโตคอลและลายเซ็น

หมายเหตุ: คุณไม่จำเป็นต้องอ่านโค้ดนี้อย่างละเอียด ไฟล์เหล่านี้จำลองผู้ขายจริงและกระเป๋าเงินของผู้ใช้ คัดลอกตามที่แสดง

ผู้ช่วยด้านโปรโตคอล

SDK ของ UCP มีโมเดลข้อมูล และ SDK ของ AP2 ลงนามและยืนยันคำสั่ง แต่ไม่มี SDK ใดที่มีไคลเอ็นต์สำหรับพูดคุยกับผู้ขาย ไฟล์ทั้ง 2 นี้จะช่วยเติมเต็มช่องว่างดังกล่าว โดยตั้งชื่อว่า 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 2 เครื่อง โดยแต่ละเครื่องจะมี 2 ปลายทาง ดังนี้

  • GET /.well-known/ucp: การค้นพบ UCP แสดงความสามารถของผู้ขาย, URL ปลายทางของ MCP, วิธีการชำระเงินที่ยอมรับ และคีย์การลงนามสาธารณะ
  • POST /mcp: การดำเนินการ MCP (Model Context Protocol) จัดการการเรียก JSON-RPC 2.0 สำหรับการค้นหาแคตตาล็อก การชำระเงิน และการชำระเงิน

ผู้ขายแต่ละรายจะลงนามในชำระเงินด้วยคีย์ของตนเอง ยืนยันคำสั่ง AP2 ก่อนที่จะดำเนินการตามคำสั่งให้เสร็จสมบูรณ์ และตรวจสอบการตอบกลับทุกครั้งกับโมเดล UCP SDK

เริ่มผู้ขายในเทอร์มินัลใหม่ (ผู้ขายต้องทำงานต่อไป)

cd ~/adk-agent-commerce
uv run python agent_payments/merchants.py

คุณควรเห็นข้อมูลต่อไปนี้

Merchants running: Meridian (:8081), StarLight (:8082)

กลับไปที่เทอร์มินัลแรก แล้วยืนยันการค้นพบ UCP โดยทำดังนี้

curl -s http://localhost:8081/.well-known/ucp | uv run python -m json.tool

คุณควรเห็นความสามารถของผู้ขาย, URL ปลายทางของ MCP, ตัวแฮนเดิลการชำระเงิน และคีย์สาธารณะ

8. เรียกใช้ Agent ด้วย ADK Web

มาใช้ Web UI ที่มีมาให้ใน ADK CLI กัน ซึ่งจะแสดงอินเทอร์เฟซแชทในเบราว์เซอร์และจัดการข้อความแจ้งการยืนยันเครื่องมือโดยอัตโนมัติ

ตอนนี้โปรเจ็กต์ควรมีลักษณะดังนี้

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 UI โดยทำดังนี้

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

คุณควรเห็นเอาต์พุตที่ระบุว่าเซิร์ฟเวอร์ทำงานอยู่ที่ http://127.0.0.1:8080

พูดคุยกับตัวแทน

  1. เปิด ADK Web UI โดยกด Ctrl หรือ Cmd แล้วคลิก URL หรือคลิกปุ่มตัวอย่างเว็บ แล้วเลือกดูตัวอย่างในพอร์ต 8080
  2. เลือก agent_payments จากเมนูแบบเลื่อนลง หากยังไม่ได้เลือก คุณจะเห็นอินเทอร์เฟซแชท
  3. ลองถามว่า "ตอนนี้มีหนังเรื่องไหนบ้าง"
  4. ตัวแทนจะค้นพบโรงภาพยนตร์และค้นหาแคตตาล็อกเบื้องหลัง โดยรวบรวมผลลัพธ์จากทั้งผู้ขายผ่าน UCP
  5. ขอจองตั๋ว: "จองตั๋ว Oppenheimer 2 ใบสำหรับรอบ 19:00 น."
  6. เมื่อตัวแทนพยายามโทรหา complete_purchase ให้สังเกตว่า UI เว็บของ ADK แสดงการ์ดยืนยันพร้อมรายละเอียดการซื้ออย่างไร
  7. หากต้องการให้สิทธิ์ทำธุรกรรม ให้เลือกช่องทำเครื่องหมายยืนยันในบัตร แล้วคลิกส่ง
  8. ตัวแทนจะดำเนินการซื้อให้เสร็จสมบูรณ์และส่งการยืนยันคำสั่งซื้อพร้อมรหัสตั๋วให้คุณ

สิ่งที่เกิดขึ้นเบื้องหลังมีดังนี้

  1. create_checkout → ผู้ขายส่งคืนการชำระเงินที่ลงนามด้วยคีย์ของตน (ap2.merchant_authorization, การล็อกราคา)
  2. complete_purchase → ยืนยันลายเซ็นของผู้ขาย สร้าง CheckoutMandate และ PaymentMandate ลงนามทั้ง 2 รายการเป็น SD-JWT และส่งให้ผู้ขาย
  3. ผู้ขายยืนยันทั้งคำสั่งและตรวจสอบว่าคำสั่งเหล่านั้นชี้ไปที่การชำระเงินที่ลงนามแล้ว → ออกตั๋ว (ในการจำลอง)

9. ล้างข้อมูล

หากต้องการหลีกเลี่ยงการปล่อยให้เซิร์ฟเวอร์ในเครื่องทำงานต่อไป ให้ล้างข้อมูลทรัพยากรโดยทำดังนี้

  1. ในเทอร์มินัลที่เรียกใช้ adk web ให้กด Ctrl+C เพื่อหยุดเซิร์ฟเวอร์ตัวแทน
  2. ในเทอร์มินัลที่เรียกใช้ merchants.py ให้กด Ctrl+C เพื่อหยุดผู้ขายจำลอง
  3. (ไม่บังคับ) หากคุณสร้างโปรเจ็กต์ที่อยู่ในระบบคลาวด์ Google ใหม่สำหรับ Codelab นี้และต้องการลบโปรเจ็กต์ ให้เรียกใช้คำสั่งต่อไปนี้โดยแทนที่ ด้วยรหัสโปรเจ็กต์
gcloud projects delete <YOUR_PROJECT_ID>

10. ยินดีด้วย 🎉

คุณสร้าง ADK Agent ที่ค้นพบผู้ขาย เรียกดูแคตตาล็อก และทำการซื้อให้เสร็จสมบูรณ์โดยใช้ UCP และ AP2

สิ่งที่คุณได้เรียนรู้

ใน Codelab นี้ คุณได้สร้าง Agent ADK ที่จัดการโฟลว์อีคอมเมิร์ซที่ปลอดภัย สรุปสิ่งที่คุณสร้างและแนวคิดหลักที่คุณใช้มีดังนี้

สิ่งที่คุณสร้าง

  • เครื่องมือสำหรับตัวแทน 5 รายการที่ครอบคลุมการดำเนินการ UCP และ AP2 ได้แก่ การค้นพบ การค้นหาแคตตาล็อก การชำระเงิน และการชำระเงิน
  • การลงนามในหนังสือมอบอำนาจ AP2: การชำระเงินที่ลงนามโดยผู้ขาย (การล็อกราคา) + CheckoutMandate และ PaymentMandate (การให้สิทธิ์ผู้ใช้)
  • การค้นหาหลายผู้ขาย: เอเจนต์ 1 รายค้นหาโรงภาพยนตร์หลายแห่งและผสานผลลัพธ์

แนวคิดหลัก:

โปรโตคอล

การทำงาน

วิธีการทำงาน

การค้นพบ UCP

Agent ค้นหาผู้ขายและความสามารถของผู้ขาย

/.well-known/ucp → ความสามารถ, อุปกรณ์ปลายทาง MCP, วิธีการชำระเงิน, คีย์

UCP MCP

Agent เรียกดูแคตตาล็อกและสร้างการชำระเงิน

การเรียก JSON-RPC 2.0 ไปยังปลายทาง MCP ของผู้ขาย

การให้สิทธิ์แก่ผู้ขาย

ผู้ขายล็อกราคาที่เสนอ

ผู้ขายลงนาม ครอบคลุมรายการบรรทัด + ยอดรวม

AP2 CheckoutMandate

ผู้ใช้อนุมัติการชำระเงินที่แน่นอน

ลงนามโดยผู้ใช้ มีการชำระเงินที่ลงนามโดยผู้ขาย

AP2 PaymentMandate

ผู้ใช้อนุญาตให้เรียกเก็บเงิน

ผู้ใช้ลงนาม อ้างอิงแฮชการชำระเงิน

การผลิตแตกต่างกันอย่างไร

Codelab นี้ใช้การจำลอง ในเวอร์ชันที่ใช้งานจริง

  • การค้นพบ UCP จะได้รับการแก้ไขกับรีจิสทรี ไม่ใช่ URL localhost ที่ฮาร์ดโค้ด
  • ปลายทาง MCP โฮสต์โดยผู้ขายจริง: โปรโตคอล JSON-RPC 2.0 เดียวกัน พื้นที่โฆษณาจริง
  • ข้อกำหนดของ AP2 จะลงนามในอุปกรณ์ที่เชื่อถือของผู้ใช้หรือโดยแพลตฟอร์มที่เชื่อถือ ไม่ใช่ด้วยคีย์ที่ตัวแทนสร้างขึ้นเมื่อเริ่มต้น
  • คีย์การลงนามมาจากโปรไฟล์ UCP ของแต่ละฝ่าย (ผู้ขายจำลองจะได้รับคีย์สาธารณะของตัวแทนในแต่ละคำขอแทน)
  • การให้สิทธิ์การชำระเงินจะดำเนินการผ่านผู้ให้บริการข้อมูลเข้าสู่ระบบที่ยืนยัน PaymentMandate และขอความยินยอมจากผู้ใช้
  • ฟรอนท์เอนด์แสดงผลลัพธ์ของเครื่องมือเป็น UI แบบริชมีเดีย (ตารางผลิตภัณฑ์ ข้อมูลสรุปการชำระเงิน การ์ดยืนยัน)

ขั้นตอนถัดไป

  • สำรวจข้อกำหนดโปรโตคอล AP2 และสร้างตัวแทนที่เปิดใช้การชำระเงินของคุณเอง
  • ใช้ UCP สำหรับผู้ขายเพื่อเปิดใช้ระบบอีคอมเมิร์ซแบบเป็น Agent
  • เชื่อมต่อ AP2 กับ A2A สำหรับเวิร์กโฟลว์การค้าแบบหลาย Agent
  • ดูข้อมูลเกี่ยวกับส่วนขยาย AP2 x402 สำหรับการชำระเงินด้วยคริปโตเคอเรนซี

เอกสารอ้างอิง