1. סקירה כללית
בשיעור Codelab הזה נפעיל סוכן ADK שמזמין כרטיסים לסרט אצל כמה מוכרים של כרטיסים לקולנוע באמצעות שני פרוטוקולים מסחריים בקוד פתוח:
- UCP (Universal Commerce Protocol): תקן שמאפשר לסוכנים לגלות מוֹכרים, לחפש קטלוגים ולנהל תהליכי תשלום.
- AP2 (Agent Payments Protocol): פרוטוקול לאישור תשלומים מאובטח שניתן לאימות באמצעות הרשאות חתומות קריפטוגרפית.
אפליקציית ההדגמה, CineAgent, מתחברת לשני מוכרים מדומים של כרטיסים לקולנוע עם יכולות שונות (בחירת מושבים, פורמטים מיוחדים ואמצעי תשלום) ומנהלת את תהליך ההזמנה המלא מחיפוש ועד תשלום.
מה תלמדו
- איך מתבצע גילוי מוכרים ב-UCP באמצעות
/.well-known/ucpפרופילים - איך סוכן ADK משתמש ב-UCP כדי לחפש קטלוגים וליצור דפי תשלום
- איך תכונות AP2 (CheckoutMandate, PaymentMandate) מאפשרות לבצע עסקאות מאובטחות
- איך פרוטוקולי UCP ו-AP2 מקצה לקצה מאבטחים מסחר אג'נטי באינטרנט
הדרישות
- פרויקט ב-Google Cloud שהחיוב בו מופעל
- דפדפן אינטרנט כמו Chrome
- Python 3.11 ואילך ו-uv, אם מריצים את הקוד במחשב שלכם במקום ב-Cloud Shell
שיעור ה-Codelab הזה מיועד למפתחים ברמת ביניים שיש להם היכרות מסוימת עם Python ו-Google Cloud. השלמת ה-codelab הזה תימשך כ-30 דקות.
העלות של המשאבים שנוצרו ב-codelab הזה צריכה להיות פחות מ-5$.
2. הסבר על פרוטוקולי UCP ו-AP2
לפני שנתחיל לבנות את הסוכן, נסביר על שני הפרוטוקולים שמאפשרים מסחר אג'נטי מאובטח.
בשיעור Codelab הזה נעשה שימוש ב-UCP בגרסה 2026-08-25 עם UCP Python SDK, וב-AP2 בגרסה v0.2 עם AP2 Python SDK.
Universal Commerce Protocol (UCP)
UCP קובע תקן לאופן שבו סוכני AI יוצרים אינטראקציה עם מוכרים. הוא פותר את הבעיה שסוכנים צריכים ללמוד ממשקי API מותאמים אישית לכל חנות, באמצעות הצגת מודל משאבים סטנדרטי.
איך זה עובד:
- גילוי: כל מוכר שעומד בדרישות של UCP חושף פרופיל במיקום סטנדרטי:
/.well-known/ucp. דוגמה: נקודת הקצה של UCP של Everlane.כשסוכן קורא את הפרופיל הזה, הוא מחפש:- יכולות: תכונות הליבה העצמאיות שהעסק תומך בהן, כמו חיפוש בקטלוג או תשלום.
- שירותים: שכבות התקשורת ברמה הנמוכה שמשמשות להחלפת נתונים. דוגמאות: API בארכיטקטורת REST, MCP (Model Context Protocol), A2A (פרוטוקול Agent2Agent).
- תוספים: אם מוֹכר צריך התנהגות מיוחדת, הוא יכול להגדיר תוספים מותאמים אישית בפרופיל הזה.
- מפתחות: מפתחות החתימה הציבוריים של המוכר, שסוכנים משתמשים בהם כדי לבדוק את החתימות של המוכר.
- פעולות: אחרי שהסוכן מאתר את נקודת הקצה של השירות, הוא משתמש בה כדי לבצע פעולות. בשיעור ה-Codelab הזה אנחנו משתמשים בModel Context Protocol (MCP) כהעברת השירות. הסוכן מבצע קריאות JSON-RPC 2.0 לנקודת הקצה הזו כדי להפעיל את היכולות שזוהו: חיפוש מוצרים, יצירת דפי תשלום והשלמת רכישות.

Agent Payments Protocol (AP2)
התקן AP2 קובע באופן אחיד איך סוכנים מאשרים תשלומים בשם משתמשים. הפתרון הזה מאפשר לסוכנים לטפל בפרטי כניסה רגישים לתשלום בלי לסכן את האבטחה.
איך זה עובד:
- חתימת המוֹכר: כשסוכן יוצר תהליך תשלום באמצעות פרוטוקול UCP, המוֹכר חותם על תהליך התשלום (פריטים וסכומים כוללים) ומחזיר את החתימה ב-
ap2.merchant_authorization. היא משמשת כהתחייבות למחיר הנמוך ביותר. אם המוכר משנה את המחיר אחרי החתימה, החתימה כבר לא תואמת. - אישור תשלום ואישור תשלום: אחרי אימות התוכן של התשלום, המשתמש (או הסוכן בשם המשתמש) חותם על שני אישורים. הפרמטר
CheckoutMandateמכיל את נתוני התשלום שהמוכר חתם עליהם, ומציין למוכר שהמשתמש אישר את התשלום. PaymentMandateמאשר את סכום התשלום לתהליך התשלום הזה. שניהם מפנים לגיבוב של תהליך התשלום החתום וכוללים את החתימה הקריפטוגרפית של המשתמש. - אימות חתימה: המוכר מקבל את שני כתבי ההרשאה. הוא מאמת את החתימה של המשתמש על
CheckoutMandateובודק שהתשלום בקופה בתוך נושא את החתימה של המוכר. ה-PaymentMandateעובר לצד התשלום (ספק אישורים או מעבד תשלומים), שמאמת אותו לפני העברת כסף. אם הכול תקין, העסקה תתבצע.
מערכת ה"נעילה הכפולה" הזו מבטיחה שהמוכרים לא יוכלו לחייב יותר מדי והסוכנים לא יוכלו להוציא כסף ללא אישור. האישורים הנדרשים הם SD-JWT (Selective Disclosure JWT), שמגנים על פרטיות המשתמשים על ידי חשיפה רק של השדות שכל צד צריך. בגרסה AP2 v0.2, CheckoutMandate מחליף את CartMandate מגרסה AP2 v0.1.

3. הגדרת הסביבה
הגדרת פרויקט ב-Google Cloud
יצירת פרויקט ב-Google Cloud
- במסוף Google Cloud, בדף לבחירת הפרויקט, בוחרים פרויקט ב-Google Cloud או יוצרים פרויקט.
- הקפידו לוודא שהחיוב מופעל בפרויקט שלכם ב-Cloud. כך בודקים אם החיוב מופעל בפרויקט
הפעלת Cloud Shell
Cloud Shell היא סביבת שורת פקודה שפועלת ב-Google Cloud וכוללת את כל הכלים הנדרשים.
- לוחצים על Activate Cloud Shell בחלק העליון של מסוף Google Cloud.
- אחרי שמתחברים ל-Cloud Shell, מאמתים את האימות:
gcloud auth list - מוודאים שהפרויקט מוגדר:
gcloud config get project - אם הפרויקט לא מוגדר כמו שציפיתם, מגדירים אותו:
export PROJECT_ID=<YOUR_PROJECT_ID> gcloud config set project $PROJECT_ID
הפעלת ממשקי ה-API
מריצים את הפקודה הבאה כדי להפעיל את ממשקי ה-API הנדרשים:
gcloud services enable aiplatform.googleapis.com
הגדרת מבנה הספרייה
מעתיקים ומדביקים את הפקודות הבאות כדי ליצור תיקייה בשביל ה-codelab הזה, עם תיקייה בשם agent_payments בתוכה בשביל קוד הסוכן:
mkdir -p ~/adk-agent-commerce/agent_payments
cd ~/adk-agent-commerce
גישה למודלים של Gemini
מעתיקים ומדביקים את הפקודה הבאה כדי ליצור את agent_payments/.env עם הפרויקט והמיקום שלכם, וכדי ש-ADK יפעיל את Gemini דרך פרויקט הענן שלכם ב-Google Cloud. הסוכן Cine משתמש ב-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 לניהול הסביבה והתלויות.
- יוצרים קובץ
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",
]
ה-SDK של AP2 מותקן ממאגר GitHub שלו כי הוא עדיין לא פורסם ב-PyPI. (החבילה ap2 ב-PyPI היא פרויקט לא קשור).
- מריצים את הפקודה הבאה כדי ליצור את הסביבה הווירטואלית ולהתקין את כל יחסי התלות:
uv sync
uv יוצר סביבת Python מבודדת ל-Codelab הזה, כך שלא צריך להפעיל שום דבר. מוסיפים את הקידומת uv run לפקודות Python.
4. הגדרת הסוכן
לפני שכותבים את הלוגיקה של הכלי, צריך להגדיר את הסוכן עצמו בקובץ שנקרא agent.py. הסוכן הזה יפעל ככלי התזמור של תהליך הזמנת הכרטיסים לסרט.
יצירת agent_payments/agent.py:
"""CineAgent — movie ticket booking agent using UCP and AP2."""
from google.adk.agents import Agent
from google.adk.models import Gemini
from google.genai import types
from google.adk.tools import FunctionTool
from agent_payments.tools import (
discover_theaters,
search_movies,
get_movie_detail,
create_checkout,
complete_purchase,
)
root_agent = Agent(
model=Gemini(
model="gemini-3.8-flash",
retry_options=types.HttpRetryOptions(attempts=5),
),
name="cineagent",
description="Movie ticket booking agent using UCP and AP2.",
instruction="""You are CineAgent, a movie ticket booking assistant.
You help users find and book movie tickets across multiple theaters
using UCP (Universal Commerce Protocol) and AP2 (Agent Payments).
**Your tools:**
- discover_theaters: Find theaters and what they support
- search_movies: Search movies across all theaters
- get_movie_detail: Get showtimes at a specific theater
- create_checkout: Start a checkout session
- complete_purchase: Finalize with AP2 mandate signing
**Rules:**
- Always call discover_theaters first if you haven't yet
- Keep responses concise — summarize and suggest next steps
- Prices from tools are in cents (1500 = $15.00)
- Never invent data — only state what tools return
""",
tools=[
discover_theaters,
search_movies,
get_movie_detail,
create_checkout,
FunctionTool(complete_purchase, require_confirmation=True),
],
)
הסבר על הקוד
בואו נפרט מה קורה בהגדרת הסוכן הזו:
-
model=Gemini(...): אנחנו משתמשים ב-Gemini 3.8 Flash לניתוח מידע ולשימוש בכלי. -
instruction: ההנחיה שמגדירה את ההתנהגות של הסוכן. ההנחיה אומרת לסוכן באופן מפורש להשתמש ב-UCP וב-AP2, מפרטת את הכלים הזמינים ומגדירה כללים חשובים כמו 'אף פעם אל תמציא נתונים' ו'המחירים הם בסנטים'. -
tools: רשימה של פונקציות Python (שניצור בהמשך) שהסוכן יכול לבחור להפעיל על סמך הבקשות של המשתמש. -
require_confirmation: אפשר להשתמש ב-FunctionTool(my_function,require_confirmation=True)כדי לעטוף כל כלי. כשהטריגר מופעל, הסוכן מושהה וממתין לאישור פשוט של 'כן' או 'לא' לפני שהוא מפעיל את הכלי. כאן, לפני הפעלת הכליcomplete_purchase, הסוכן מושהה עד לאישור אנושי.
רשימת הכלים
הגדרת הסוכן מציינת מה צריך לבנות. כל כלי ממופה לפעולה ספציפית בפרוטוקול UCP או AP2:
כלי | תיאור | פעולת פרוטוקול |
| חיפוש מוכרים והיכולות שלהם | שאילתות |
| חיפוש בקטלוגים של מוצרים אצל מוכרים שונים | JSON-RPC לנקודת הקצה של MCP |
| חיפוש זמני הצגה אצל מוֹכר ספציפי | JSON-RPC לנקודת הקצה של MCP |
| התחלת סשן תשלום | JSON-RPC לנקודת הקצה של MCP |
| אישור התשלום והשלמת ההזמנה | חתימה על דרישות AP2 ושליחה ל-MCP |
מודל Gemini יחליט מתי להפעיל כל כלי על סמך השיחה. בשלב הבא, אנחנו צריכים להטמיע את הפעולות של כל כלי ב-tools.py.
5. בניית כלי הסוכן: גילוי וגלישה
עכשיו נטמיע את הכלים שבהם הסוכן ישתמש כדי לעיין בסרטים ולגלות אותם. כל כלי עוטף פעולה של UCP.
יוצרים קובץ חדש בשם agent_payments/tools.py ומעתיקים את הקוד הבא:
"""Agent tools — each one wraps a UCP or AP2 operation."""
import json
from .ucp_client import UCPClient
from .ap2_handler import AP2Handler
# Initialize clients directly
_merchant_urls = ["http://localhost:8081", "http://localhost:8082"]
_ap2 = AP2Handler()
_ucp = UCPClient(platform_keys=[_ap2.public_key])
הסבר על ההגדרה
כדי להתמקד בבניית הסוכן ב-Codelab הזה, אנחנו משתמשים בשני מחלקות עזר, UCPClient ו-AP2Handler, שנסביר עליהן בשלב מאוחר יותר.
- מה הם?: אלה מחלקות קטנות של עזרה שכתבנו בשביל ה-codelab הזה כדי לתקשר עם המוכרים המדומים. ערכות ה-SDK הרשמיות מספקות את חלקי הפרוטוקול: ל-UCP SDK יש מודלים של נתונים לכל סכימת UCP, ול-AP2 SDK יש אפשרות ליצור ולאמת הרשאות חתומות. אף אחד מה-SDK לא כולל לקוח להתקשרות עם מוכרים, ולכן רכיבי העזר האלה מטפלים בחלק הזה.
- בינתיים, כדאי להתייחס אליהם כאובייקטים מסייעים:
-
_ucp.discover(url): אחזור ואימות של פרופיל של מוֹכר. -
_ucp.mcp_call(url, method, params): שליחת בקשת JSON-RPC 2.0 לנקודת הקצה של פלטפורמת ניהול המרכזים של המוכר.
-
גילוי אולמות קולנוע
הכלי הזה הוא השלב הראשון בתהליך של UCP. היא מאתרת את המוכרים הקיימים ואת האפשרויות שהם מציעים.
הוספה אל tools.py:
async def discover_theaters() -> str:
"""Discover available theater merchants and their capabilities via UCP."""
theaters = []
for url in _merchant_urls:
info = await _ucp.discover(url)
theaters.append(
{
"url": url,
"name": info["name"],
"capabilities": info["capabilities"],
"payment_handlers": info["payment_handlers"],
}
)
return json.dumps(theaters, indent=2)
מה זה אומר:
- הוא מבצע איטרציה על רשימה של כתובות אתרים של מוֹכרים שסופקו על ידי השרת. ב-codelab הזה נגדיר שני מוכרים לדוגמה בקטע שבהמשך.
- לכל כתובת URL, הפונקציה
_ucp.discover(url)מופעלת, והיא מגיעה לנקודת הקצה/.well-known/ucp. - הוא אוסף את השם, היכולות והאמצעים לטיפול בתשלומים לרשימת סיכום.
- הרשימה מוחזרת כמחרוזת JSON כדי שהסוכן יוכל לקרוא אותה.
חפש סרטים
הכלי הזה מחפש אצל כל המוכרים שזוהו וממזג את התוצאות. זה חשוב כי יכול להיות שאותו סרט יוקרן בכמה בתי קולנוע בפורמטים שונים (IMAX, Dolby) ובמחירים שונים.
הוספה אל tools.py:
async def search_movies(query: str = "") -> str:
"""Search for movies across all theaters. Use '' to browse all."""
all_movies = {}
for url, merchant in _ucp.merchants.items():
result = await _ucp.mcp_call(
url, "search_catalog", {"catalog": {"query": query}}
)
for product in result.get("products", []):
mid = product["id"]
if mid not in all_movies:
all_movies[mid] = {
"id": mid,
"title": product["title"],
"categories": [
c["value"] for c in product.get("categories", [])
],
"theaters": {},
}
showtimes = []
for v in product.get("variants", []):
opts = {o["name"]: o["label"] for o in v.get("options", [])}
showtimes.append(
{
"id": v["id"],
"format": opts.get("format", "Standard"),
"time": opts.get("time", ""),
"price": v.get("price", {}),
"seats": v.get("metadata", {}).get(
"seats_available", 0
),
}
)
all_movies[mid]["theaters"][url] = {
"name": merchant["name"],
"showtimes": showtimes,
}
return json.dumps(list(all_movies.values()), indent=2)
מה זה אומר:
- הוא עובר בלולאה על כל בתי הקולנוע שזוהו.
- הוא שולח בקשת JSON-RPC של קטלוג חיפוש (
_ucp.mcp_call(url, "search_catalog", {"catalog": {"query": query}})) לנקודת הקצה של ה-MCP של המוכר. - לאחר מכן המערכת מבצעת ניקוי נתונים קטן כדי לנתח את התוצאות כדי למצוא סרטים ואת ה'וריאציות' שלהם (שמייצגות שעות הקרנה ופורמטים ספציפיים). הסרטים מקובצים לפי מזהה, כדי שהמשתמש לא יראה רשומות כפולות של סרטים.
קבלת פרטי סרט
הכלי הזה מאחזר את כל פרטי הקטלוג של סרט מסוים בבית קולנוע מסוים.
הוספה אל 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)
מה זה אומר:
- היא קוראת לשיטה
create_checkoutבנקודת הקצה של ה-MCP של המוֹכר. - היא מעבירה את
showtime_idוquantityשהמשתמש ביקש. - המוכר מחזיר דף תשלום שחתום באמצעות המפתח של המוכר.
הערה: אם בודקים את נתוני התגובה, השדה ap2.merchant_authorization מכיל את החתימה הקריפטוגרפית של המוכר על דף התשלום, שנועלת את המחיר שצוין. אי אפשר לשנות את זה אחר כך.
השלמת הרכישה
הכלי הזה מבצע שלושה דברים:
- אנחנו מקבלים את נתוני התשלום ומאמתים את החתימה של המוכר.
- יוצרים את CheckoutMandate ואת PaymentMandate וחותמים עליהם באמצעות AP2 SDK.
- שולחים את שני האישורים למוֹכר כדי להשלים את הרכישה.
הוספה אל 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)
למה יש שני מנדטים? האישור לתשלום מוכיח למוכר שהמשתמש אישר את התשלום הספציפי הזה, במחיר שהמוכר ציין. האישור לתשלום מוכיח לצד המקבל שהמשתמש אישר את החיוב הזה. התהליך הוא:
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. הפיכת הקוד להפעלה
במקרה של מוכרים אמיתיים שמשתמשים בפלטפורמה החדשה, פשוט מפנים את הסוכן לכתובות ה-URL שלהם וזהו. כדי לבצע בדיקה מקומית של ה-codelab הזה, אנחנו צריכים שני דברים:
- מוכרים מדומים: שרתים מקומיים שמדמים נקודות קצה של UCP, כדי שיהיה לכם משהו לבדוק מולו
- עוזרים לפרוטוקול: עטיפות דקות שקוראות למוֹכרים דרך HTTP ומשתמשות בערכות ה-SDK של UCP ו-AP2 לנתוני הפרוטוקול ולחתימות
הערה: לא צריך לקרוא את הקוד הזה בעיון. הקבצים האלה מדמים מוֹכרים אמיתיים וארנק של משתמש. להעתיק אותם כמו שהם.
עזרים לפרוטוקולים
ערכת ה-SDK של UCP מספקת מודלים של נתונים, וערכת ה-SDK של AP2 חותמת על הרשאות ומאמתת אותן, אבל אף אחת מהן לא כוללת לקוח לתקשורת עם מוכרים. שני הקבצים האלה משלימים את הפער. השמות שלהם הם ucp_client.py ו-ap2_handler.py כדי שלא יחליפו את החבילה ap2.
יצירת agent_payments/ucp_client.py:
"""UCP client: discovers merchants and calls their MCP tools."""
import uuid
import httpx
from ucp_sdk.models.schemas.profile import BusinessSchema
# The platform (this agent) identifies itself with a UCP profile URL
PLATFORM_PROFILE = "https://cineagent.example/.well-known/ucp"
class UCPClient:
def __init__(self, platform_keys: list[dict]):
self.client = httpx.AsyncClient(timeout=30)
self.platform_keys = platform_keys
self.merchants = {} # url -> merchant info dict
async def discover(self, merchant_url: str) -> dict:
"""Fetch and validate a merchant's UCP profile from /.well-known/ucp."""
resp = await self.client.get(f"{merchant_url}/.well-known/ucp")
resp.raise_for_status()
profile = BusinessSchema.model_validate(resp.json())
ucp = profile.ucp
info = {
"name": merchant_url.split("//")[-1],
"mcp_endpoint": str(ucp.services["dev.ucp.shopping"][0].endpoint),
"capabilities": list(ucp.capabilities or {}),
"payment_handlers": [
h.id for handlers in ucp.payment_handlers.values() for h in handlers
],
"keys": [k.model_dump(exclude_none=True) for k in profile.keys or []],
}
self.merchants[merchant_url] = info
return info
async def mcp_call(
self, merchant_url: str, tool_name: str, arguments: dict
) -> dict:
"""Call a merchant's MCP tool via JSON-RPC 2.0."""
merchant = self.merchants[merchant_url]
meta = {
"ucp-agent": {
"profile": PLATFORM_PROFILE,
# Mock shortcut: a real merchant reads the platform's public
# keys from the profile URL above instead
"keys": self.platform_keys,
},
"idempotency-key": str(uuid.uuid4()),
}
resp = await self.client.post(
merchant["mcp_endpoint"],
json={
"jsonrpc": "2.0",
"id": uuid.uuid4().hex,
"method": "tools/call",
"params": {
"name": tool_name,
"arguments": {"meta": meta, **arguments},
},
},
)
resp.raise_for_status()
data = resp.json()
if "error" in data:
raise Exception(f"MCP error: {data['error']}")
return data["result"]["structuredContent"]
async def close(self):
await self.client.aclose()
יצירת agent_payments/ap2_handler.py:
"""AP2 mandate handler: verifies the merchant's signature and signs mandates."""
import json
import time
from jwcrypto.jwk import JWK
from jwcrypto.jws import JWS
from ap2.sdk.mandate import MandateClient
from ap2.sdk.utils import b64url_decode, b64url_encode, compute_sha256_b64url
from ap2.sdk.generated.checkout_mandate import CheckoutMandate
from ap2.sdk.generated.payment_mandate import PaymentMandate
from ap2.sdk.generated.types.amount import Amount
from ap2.sdk.generated.types.merchant import Merchant
from ap2.sdk.generated.types.payment_instrument import PaymentInstrument
class AP2Handler:
def __init__(self):
# The user's signing key. In production, this key stays in a wallet or
# on a trusted device, and the user approves each signature.
self.key = JWK.generate(kty="EC", crv="P-256", kid="cineagent-user-key")
self.public_key = json.loads(self.key.export_public())
self.mandates = MandateClient()
def verify_merchant_authorization(
self, checkout: dict, merchant_keys: list[dict]
) -> str | None:
"""Check the merchant's signature on a checkout.
The signature is the merchant's price guarantee: if anything in the
checkout changes, the signature no longer matches. Returns the signed
checkout as a JWT, or None if the signature is missing or invalid.
"""
signature = checkout.get("ap2", {}).get("merchant_authorization")
if not signature:
return None
header, _, sig = signature.split(".") # detached JWS: header..signature
payload = {k: v for k, v in checkout.items() if k != "ap2"}
canonical = json.dumps(
payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False
)
checkout_jwt = f"{header}.{b64url_encode(canonical.encode())}.{sig}"
kid = json.loads(b64url_decode(header))["kid"]
key = next((k for k in merchant_keys if k["kid"] == kid), None)
if not key:
return None
try:
jws = JWS()
jws.deserialize(checkout_jwt)
jws.verify(JWK(**key))
except Exception:
return None
return checkout_jwt
def create_mandates(
self, checkout: dict, checkout_jwt: str, merchant_name: str
) -> tuple[str, str]:
"""Create and sign a CheckoutMandate and a PaymentMandate.
Both mandates reference the hash of the merchant-signed checkout, so
the user's approval is bound to exactly this cart and price.
"""
checkout_hash = compute_sha256_b64url(checkout_jwt)
total = next(t["amount"] for t in checkout["totals"] if t["type"] == "total")
now = int(time.time())
checkout_mandate = CheckoutMandate(
checkout_jwt=checkout_jwt,
checkout_hash=checkout_hash,
iat=now,
exp=now + 600,
)
payment_mandate = PaymentMandate(
transaction_id=checkout_hash,
payee=Merchant(id=merchant_name, name=merchant_name),
payment_amount=Amount(amount=total, currency=checkout["currency"]),
payment_instrument=PaymentInstrument(
id="instr_1", type="card", description="Demo card"
),
iat=now,
exp=now + 600,
)
# Sign each mandate as an SD-JWT with the user's key
return (
self.mandates.create(payloads=[checkout_mandate], issuer_key=self.key),
self.mandates.create(payloads=[payment_mandate], issuer_key=self.key),
)
מוכרים לדוגמה
יצירת agent_payments/merchants.py:
"""Mock UCP merchant servers: two theaters with different capabilities."""
import json
import time
import uuid
import multiprocessing
from datetime import datetime, timezone, timedelta
import uvicorn
from fastapi import FastAPI
from jwcrypto.jwk import JWK
from jwcrypto.jws import JWS
from ap2.sdk.mandate import MandateClient
from ap2.sdk.utils import compute_sha256_b64url
from ap2.sdk.generated.checkout_mandate import CheckoutMandate
from ap2.sdk.generated.payment_mandate import PaymentMandate
from ucp_sdk.models.schemas.common.payment_ap2_mandate import Checkout
from ucp_sdk.models.schemas.profile import BusinessSchema
from ucp_sdk.models.schemas.shopping.catalog_lookup import LookupResponse
from ucp_sdk.models.schemas.shopping.catalog_search import SearchResponse
UCP_VERSION = "2026-08-25"
UCP_SPEC = f"https://ucp.dev/{UCP_VERSION}"
# ── Theater data ────────────────────────────────────────────
THEATERS = {
8081: {
"name": "Meridian Cinemas",
"movies": [
{
"id": "opp",
"title": "Oppenheimer",
"categories": ["Drama", "History"],
"showtimes": [
{"id": "st_opp_7pm_imax", "format": "IMAX", "time": "7:00 PM", "price": 2200, "seats": 45},
{"id": "st_opp_930pm", "format": "Standard", "time": "9:30 PM", "price": 1500, "seats": 80},
],
},
{
"id": "dune3",
"title": "Dune: Part Three",
"categories": ["Sci-Fi", "Action"],
"showtimes": [
{"id": "st_dune_8pm_imax", "format": "IMAX", "time": "8:00 PM", "price": 2200, "seats": 30},
],
},
],
},
8082: {
"name": "StarLight Theaters",
"movies": [
{
"id": "opp",
"title": "Oppenheimer",
"categories": ["Drama", "History"],
"showtimes": [
{"id": "st_opp_6pm_atmos", "format": "Dolby Atmos", "time": "6:00 PM", "price": 1800, "seats": 60},
],
},
{
"id": "spider",
"title": "Spider-Verse",
"categories": ["Animation", "Action"],
"showtimes": [
{"id": "st_spider_4pm", "format": "Standard", "time": "4:00 PM", "price": 1200, "seats": 100},
],
},
],
},
}
def create_app(port):
theater = THEATERS[port]
app = FastAPI()
sessions = {}
checkout_jwts = {} # checkout id -> merchant-signed checkout JWT
# The merchant's signing key. Its public half is published in the profile.
key = JWK.generate(kty="EC", crv="P-256", kid=f"merchant-{port}")
def _capability(name, path, schema, **extra):
return {name: [{
"version": UCP_VERSION,
"spec": f"{UCP_SPEC}/specification/{path}",
"schema": f"{UCP_SPEC}/schemas/{schema}",
**extra,
}]}
payment_handlers = {
"com.example.card": [
{"id": f"card_{port}", "version": UCP_VERSION,
"available_instruments": [{"type": "card"}], "config": {}}
]
}
# ── UCP Discovery endpoint ──────────────────────────────
@app.get("/.well-known/ucp")
def discovery():
profile = {
"ucp": {
"version": UCP_VERSION,
"services": {
"dev.ucp.shopping": [
{"version": UCP_VERSION,
"spec": f"{UCP_SPEC}/specification/overview",
"transport": "mcp",
"schema": f"{UCP_SPEC}/services/shopping/mcp.openrpc.json",
"endpoint": f"http://localhost:{port}/mcp"}
]
},
"capabilities": {
**_capability("dev.ucp.shopping.catalog.search",
"shopping/catalog/search", "shopping/catalog_search.json"),
**_capability("dev.ucp.shopping.catalog.lookup",
"shopping/catalog/lookup", "shopping/catalog_lookup.json"),
**_capability("dev.ucp.shopping.checkout",
"shopping/checkout", "shopping/checkout.json"),
**_capability("dev.ucp.common.payment.ap2_mandate",
"payment/extensions/ap2-mandates",
"common/payment_ap2_mandate.json",
extends="dev.ucp.shopping.checkout",
config={"vp_formats_supported": {"dc+sd-jwt": {}}}),
},
"payment_handlers": payment_handlers,
},
"keys": [json.loads(key.export_public())],
}
# Check the profile against the UCP SDK models before returning it
BusinessSchema.model_validate(profile)
return profile
# ── MCP JSON-RPC endpoint ───────────────────────────────
@app.post("/mcp")
def mcp(body: dict):
tool = body["params"]["name"]
args = body["params"].get("arguments", {})
rid = body.get("id", "1")
if tool == "search_catalog":
q = args.get("catalog", {}).get("query", "").lower()
hits = [m for m in theater["movies"]
if not q or q in m["title"].lower()
or any(q in c.lower() for c in m["categories"])]
result = {"ucp": _ucp_meta("dev.ucp.shopping.catalog.search"),
"products": [_product(m) for m in hits]}
return _ok(rid, SearchResponse, result)
if tool == "lookup_catalog":
ids = args.get("catalog", {}).get("ids", [])
movies = [m for m in theater["movies"] if m["id"] in ids]
if not movies:
return _err(rid, "Not found")
result = {"ucp": _ucp_meta("dev.ucp.shopping.catalog.lookup"),
"products": [_product(m, lookup=True) for m in movies]}
return _ok(rid, LookupResponse, result)
if tool == "create_checkout":
co = args.get("checkout", {})
sid = f"chk_{uuid.uuid4().hex[:12]}"
items, subtotal = [], 0
for li in co.get("line_items", []):
st = _find_showtime(li["item"]["id"])
if not st:
continue
mv = _find_movie(li["item"]["id"])
qty = li.get("quantity", 1)
amt = st["price"] * qty
subtotal += amt
items.append({
"id": f"li_{uuid.uuid4().hex[:8]}",
"item": {
"id": st["id"],
"title": f"{mv['title']} ({st['format']}, {st['time']})",
"price": st["price"],
},
"quantity": qty,
"totals": [{"type": "subtotal", "amount": amt},
{"type": "total", "amount": amt}],
})
if not items:
return _err(rid, "No valid showtimes in checkout")
tax = int(subtotal * 0.08)
total = subtotal + tax
session = {
"ucp": {
**_ucp_meta("dev.ucp.shopping.checkout",
"dev.ucp.common.payment.ap2_mandate"),
"payment_handlers": payment_handlers,
},
"id": sid,
"status": "ready_for_complete",
"currency": "USD",
"line_items": items,
"totals": [
{"type": "subtotal", "display_text": "Subtotal", "amount": subtotal},
{"type": "tax", "display_text": "Tax", "amount": tax},
{"type": "total", "display_text": "Total", "amount": total},
],
"links": [{"type": "terms_of_service",
"url": f"http://localhost:{port}/terms"}],
"expires_at": (
datetime.now(timezone.utc) + timedelta(minutes=10)
).isoformat(),
}
_sign(session)
sessions[sid] = session
return _ok(rid, Checkout, session)
if tool == "get_checkout":
session = sessions.get(args.get("id"))
if not session:
return _err(rid, "Not found")
return _ok(rid, Checkout, session)
if tool == "complete_checkout":
sid = args.get("id")
session = sessions.get(sid)
if not session:
return _err(rid, "Not found")
co = args.get("checkout", {})
checkout_mandate = co.get("ap2", {}).get("checkout_mandate")
instruments = co.get("payment", {}).get("instruments", [])
if not checkout_mandate or not instruments:
return _err(rid, "mandate_required")
payment_mandate = instruments[0]["credential"]["token"]
# Mock shortcut: a real merchant fetches the platform's keys
# from its profile URL (meta["ucp-agent"]["profile"])
platform_key = JWK(**args["meta"]["ucp-agent"]["keys"][0])
try:
cm = MandateClient().verify(
checkout_mandate, platform_key, payload_type=CheckoutMandate
).mandate_payload
pm = MandateClient().verify(
payment_mandate, platform_key, payload_type=PaymentMandate
).mandate_payload
except Exception as e:
return _err(rid, f"mandate_invalid_signature: {e}")
# The mandates must point at the exact checkout this merchant signed
expected_hash = compute_sha256_b64url(checkout_jwts[sid])
total = next(t["amount"] for t in session["totals"] if t["type"] == "total")
if (cm.checkout_jwt != checkout_jwts[sid]
or cm.checkout_hash != expected_hash
or pm.transaction_id != expected_hash
or pm.payment_amount.amount != total):
return _err(rid, "mandate_scope_mismatch")
order_id = f"ord_{uuid.uuid4().hex[:8]}"
session["status"] = "completed"
session["order"] = {
"id": order_id,
"label": theater["name"],
"permalink_url": f"http://localhost:{port}/orders/{order_id}",
"tickets": [
{
"movie": li["item"]["title"],
"quantity": li["quantity"],
"ticket_code": uuid.uuid4().hex[:8].upper(),
}
for li in session["line_items"]
],
}
_sign(session)
return _ok(rid, Checkout, session)
return _err(rid, f"Unknown tool: {tool}")
def _sign(session):
"""Add the merchant's signature (a detached JWS) to the checkout."""
payload = {k: v for k, v in session.items() if k != "ap2"}
canonical = json.dumps(
payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False
)
jws = JWS(canonical.encode())
jws.add_signature(key, alg="ES256",
protected=json.dumps({"alg": "ES256", "kid": key.kid}))
checkout_jwt = jws.serialize(compact=True)
header, _, sig = checkout_jwt.split(".")
session["ap2"] = {"merchant_authorization": f"{header}..{sig}"}
checkout_jwts[session["id"]] = checkout_jwt
def _ucp_meta(*capabilities):
return {"version": UCP_VERSION,
"capabilities": {c: [{"version": UCP_VERSION}] for c in capabilities}}
def _ok(rid, model, result):
# Check the response against the UCP SDK models before returning it
model.model_validate(result)
return {"jsonrpc": "2.0", "id": rid, "result": {
"structuredContent": result,
"content": [{"type": "text", "text": json.dumps(result)}],
}}
def _err(rid, msg):
return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32000, "message": msg}}
def _product(movie, lookup=False):
prices = [st["price"] for st in movie["showtimes"]]
return {
"id": movie["id"],
"title": movie["title"],
"description": {"plain": f"{movie['title']} at {theater['name']}"},
"categories": [{"value": c, "taxonomy": "merchant"} for c in movie["categories"]],
"price_range": {
"min": {"amount": min(prices), "currency": "USD"},
"max": {"amount": max(prices), "currency": "USD"},
},
"variants": [
{
"id": st["id"],
"title": f"{st['format']} {st['time']}",
"description": {"plain": f"{st['format']} showing at {st['time']}"},
"options": [
{"name": "format", "label": st["format"]},
{"name": "time", "label": st["time"]},
],
"price": {"amount": st["price"], "currency": "USD"},
"availability": {"available": st["seats"] > 0},
"metadata": {"seats_available": st["seats"]},
**({"inputs": [{"id": movie["id"], "match": "featured"}]} if lookup else {}),
}
for st in movie["showtimes"]
],
}
def _find_showtime(sid):
return next(
(st for m in theater["movies"] for st in m["showtimes"] if st["id"] == sid),
None,
)
def _find_movie(sid):
return next(
(m for m in theater["movies"] for st in m["showtimes"] if st["id"] == sid),
None,
)
return app
def _run(port):
uvicorn.run(create_app(port), host="0.0.0.0", port=port, log_level="warning")
if __name__ == "__main__":
for port in THEATERS:
multiprocessing.Process(target=_run, args=(port,), daemon=True).start()
print("Merchants running: Meridian (:8081), StarLight (:8082)")
print("Press Ctrl+C to stop")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
הפעולה הזו יוצרת שני שרתי FastAPI, שלכל אחד מהם יש שתי נקודות קצה:
-
GET /.well-known/ucp: גילוי UCP. הפונקציה מחזירה את היכולות של המוכר, את כתובת ה-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, ה-handlers של אמצעי התשלום והמפתח הציבורי.
8. הפעלת הסוכן באמצעות ADK Web
נשתמש בממשק המשתמש האינטרנטי המובנה ב-CLI של ADK. הפעולה הזו מספקת ממשק צ'אט בדפדפן ומטפלת אוטומטית בהנחיות לאישור כלים.
הפרויקט אמור להיראות כך:
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:
cd ~/adk-agent-commerce
uv run adk web --port 8080 --allow_origins '*'
הפלט אמור להראות שהשרת פועל בכתובת http://127.0.0.1:8080.
שיחה עם נציג
- פותחים את ממשק האינטרנט של ADK על ידי לחיצה על כתובת ה-URL עם Ctrl או Cmd, או על ידי לחיצה על הלחצן Web Preview (תצוגה מקדימה באינטרנט) ובחירה באפשרות Preview on port 8080 (תצוגה מקדימה ביציאה 8080).
- בוחרים באפשרות
agent_paymentsמהתפריט הנפתח, אם היא לא נבחרה כבר. יוצג ממשק צ'אט. - אפשר לשאול: "What movies are playing?"
- הסוכן יאתר בתי קולנוע ויחפש קטלוגים מאחורי הקלעים, ויצבור תוצאות משני המוֹכרים דרך UCP.
- מבקשים להזמין כרטיסים: "Book 2 tickets for Oppenheimer for 7 PM" (תזמין 2 כרטיסים לסרט 'אופנהיימר' להקרנה של 19:00).
- כשסוכן מנסה להתקשר אל
complete_purchase, שימו לב איך בממשק המשתמש של ADK Web מוצג כרטיס אישור עם פרטי הרכישה. - כדי לאשר את העסקה, מסמנים את תיבת הסימון מאושר בכרטיס ולוחצים על שליחה.
- הנציג ישלים את הרכישה וישלח לכם אישור הזמנה עם קודי הכרטיסים.
זה מה שקרה מאחורי הקלעים:
-
create_checkout← המוכר החזיר דף תשלום שחתום באמצעות המפתח שלו (ap2.merchant_authorization, נעילת המחיר) complete_purchase← אימת את החתימה של המוכר, יצר CheckoutMandate ו-PaymentMandate, חתם על שניהם כ-SD-JWT ושלח אותם למוכר- המוֹכר אימת את שני כתבי ההרשאה ודאג שהם מפנים לדף התשלום שהוא חתם עליו → הנפיק כרטיסים (בסימולציה)
9. הסרת המשאבים
כדי למנוע הפעלה של שרתים מקומיים, צריך לנקות את המשאבים:
- בטרמינל שבו פועל
adk web, מקישים על Ctrl+C כדי לעצור את שרת הסוכן. - בטרמינל שבו פועל
merchants.py, מקישים על Ctrl+C כדי לעצור את המוכרים המדומים. - (אופציונלי) אם יצרתם פרויקט חדש ב-Google Cloud בשביל ה-Codelab הזה ואתם רוצים למחוק אותו, מריצים את הפקודה הבאה ומחליפים את
במזהה הפרויקט:
gcloud projects delete <YOUR_PROJECT_ID>
10. מעולה! 🎉
פיתחתם סוכן ADK שמגלה מוכרים, מעיין בקטלוגים ומשלים רכישות באמצעות UCP ו-AP2.
מה למדתם
ב-Codelab הזה יצרתם סוכן ADK שמטפל בתהליכי מסחר מאובטחים. סיכום של מה שבניתם והמושגים העיקריים שהשתמשתם בהם:
מה יצרתם:
- 5 כלים לסוכנים שמבוססים על פעולות UCP ו-AP2: גילוי, חיפוש בקטלוג, תשלום.
- חתימה על ייפוי כוח לשימוש ב-AP2: תשלום בחנות עם חתימה של המוכר (נעילת מחיר) + CheckoutMandate ו-PaymentMandate (הרשאת משתמש).
- חיפוש בכמה חנויות: סוכן אחד ששולח שאילתות לכמה בתי קולנוע וממזג את התוצאות.
מושגים מרכזיים:
פרוטוקול | תיאור | איך זה עובד |
UCP Discovery | הסוכן מוצא מוכרים ואת היכולות שלהם | |
UCP MCP | הסוכן מעיין בקטלוגים ויוצר דפי תשלום | קריאות JSON-RPC 2.0 לנקודת הקצה של MCP של המוכר |
הרשאת מוכר | המוֹכר נועל את המחיר שצוין | חתום על ידי המוכר, כולל פריטים + סכומים כוללים |
AP2 CheckoutMandate | המשתמש מאשר את תהליך התשלום המדויק | חתימה של המשתמש, מכיל את תהליך התשלום עם חתימה של המוכר |
AP2 PaymentMandate | המשתמש מאשר את החיוב | נחתם על ידי המשתמש, כולל הפניה לגיבוב של דף התשלום |
מה שונה בייצור?
בשיעור Codelab הזה נעשה שימוש ב-mocks. בסביבת ייצור:
- גילוי UCP מתבצע מול רישום, ולא מול כתובות URL של localhost שמופיעות בקוד.
- נקודות הקצה של MCP מתארחות אצל מוכרים אמיתיים: אותו פרוטוקול JSON-RPC 2.0, מלאי אמיתי
- הוראות AP2 נחתמות במכשיר המהימן של המשתמש או בפלטפורמה מהימנה, ולא באמצעות מפתח שהסוכן יוצר בהפעלה
- מפתחות חתימה מגיעים מפרופיל UCP של כל צד (המוכרים המדומים מקבלים את המפתח הציבורי של הסוכן בכל בקשה במקום זאת)
- אישור התשלום עובר דרך ספק אישורים שמאמת את הוראת התשלום ומבקש את הסכמת המשתמש.
- קצה קדמי מעבד את תוצאות הכלי כרכיבי ממשק משתמש עשירים (רשתות מוצרים, סיכומי תשלום, כרטיסי אישור)
השלבים הבאים
- אפשר לעיין במפרט הפרוטוקול AP2 וליצור סוכן משלכם עם אפשרות לתשלום
- הטמעה של UCP עבור המוכר כדי להפעיל מסחר אג'נטי
- קישור AP2 ל-A2A לתהליכי עבודה מסחריים מרובי סוכנים
- מידע על התוסף AP2 x402 לתשלומים במטבעות וירטואליים