1. खास जानकारी
इस कोडलैब में, आपको ADK एजेंट चलाने का तरीका बताया जाएगा. यह एजेंट, दो ओपन-सोर्स कॉमर्स प्रोटोकॉल का इस्तेमाल करके, अलग-अलग थिएटर में फ़िल्मों के टिकट बुक करता है:
- यूसीपी (यूनिवर्सल कॉमर्स प्रोटोकॉल): यह एजेंट के लिए एक स्टैंडर्ड है. इससे एजेंट, कारोबारियों या कंपनियों को खोज सकते हैं, कैटलॉग खोज सकते हैं, और चेकआउट फ़्लो मैनेज कर सकते हैं.
- AP2 (Agent Payments Protocol): यह एक प्रोटोकॉल है. इसका इस्तेमाल, क्रिप्टोग्राफ़िक तरीके से हस्ताक्षर किए गए निर्देशों का इस्तेमाल करके, सुरक्षित और पुष्टि किए जा सकने वाले पेमेंट ऑथराइज़ेशन के लिए किया जाता है.
डेमो ऐप्लिकेशन, CineAgent, दो मॉक थिएटर कारोबारियों से कनेक्ट होता है. इनमें अलग-अलग सुविधाएं (सीट चुनने की सुविधा, खास फ़ॉर्मैट, और पेमेंट के तरीके) होती हैं. साथ ही, यह खोज से लेकर पेमेंट तक की पूरी बुकिंग प्रोसेस को मैनेज करता है.
आपको क्या सीखने को मिलेगा
/.well-known/ucpप्रोफ़ाइलों के ज़रिए, कारोबारी या कंपनी की यूसीपी प्रोफ़ाइल को खोजने की सुविधा कैसे काम करती है- ADK एजेंट, कैटलॉग खोजने और चेकआउट बनाने के लिए यूसीपी का इस्तेमाल कैसे करता है
- AP2 के ज़रूरी निर्देशों (CheckoutMandate, PaymentMandate) के ज़रिए लेन-देन को सुरक्षित कैसे बनाया जाता है
- एंड-टू-एंड यूसीपी और AP2 प्रोटोकॉल, एजेंटिक ई-कॉमर्स को सुरक्षित रखने के लिए कैसे काम करते हैं
आपको किन चीज़ों की ज़रूरत होगी
- बिलिंग की सुविधा वाला Google Cloud प्रोजेक्ट
- कोई वेब ब्राउज़र, जैसे कि Chrome
- Python 3.11+ और uv, अगर आपको Cloud Shell के बजाय अपनी मशीन पर कोड चलाना है
यह कोडलैब, उन डेवलपर के लिए है जिन्हें Python और Google Cloud के बारे में कुछ जानकारी है. इस कोडलैब को पूरा करने में करीब 30 मिनट लगते हैं.
इस कोडलैब में बनाए गए संसाधनों की लागत 5 डॉलर से कम होनी चाहिए.
2. यूसीपी और एपी2 प्रोटोकॉल के बारे में जानकारी
एजेंट बनाने से पहले, आइए उन दो प्रोटोकॉल के बारे में जानते हैं जिनकी वजह से, सुरक्षित एजेंटिक कॉमर्स मुमकिन हो पाता है.
इस कोडलैब में, UCP Python SDK के साथ UCP के 2026-08-25 वर्शन और AP2 Python SDK के साथ AP2 के v0.2 वर्शन का इस्तेमाल किया गया है.
यूनिवर्सल कॉमर्स प्रोटोकॉल (UCP)
यूसीपी, एआई एजेंट के कारोबारियों या कंपनियों के साथ इंटरैक्ट करने के तरीके को स्टैंडर्ड बनाता है. यह एक स्टैंडर्ड रिसोर्स मॉडल उपलब्ध कराता है. इससे एजेंट को हर स्टोर के लिए, कस्टम एपीआई सीखने की ज़रूरत नहीं पड़ती.
यह कैसे काम करता है:
- डिस्कवरी: यूसीपी के मानकों का पालन करने वाला हर कारोबारी या कंपनी, एक स्टैंडर्ड जगह पर प्रोफ़ाइल दिखाता है:
/.well-known/ucp. उदाहरण: Everlane का यूसीपी एंडपॉइंट.जब कोई एजेंट इस प्रोफ़ाइल को पढ़ता है, तो वह इन चीज़ों को ढूंढता है:- क्षमताएं: ये ऐसी मुख्य सुविधाएं होती हैं जो कारोबार के लिए उपलब्ध होती हैं. जैसे, कैटलॉग में खोज करने की सुविधा या चेकआउट करने की सुविधा.
- सेवाएं: ये कम्यूनिकेशन की लोअर-लेवल लेयर होती हैं. इनका इस्तेमाल डेटा को शेयर करने के लिए किया जाता है. उदाहरण: REST API, एमसीपी (मॉडल कॉन्टेक्स्ट प्रोटोकॉल), A2A (Agent2Agent प्रोटोकॉल).
- एक्सटेंशन: अगर किसी कारोबारी या कंपनी को खास व्यवहार की ज़रूरत है, तो वह इस प्रोफ़ाइल में कस्टम एक्सटेंशन तय कर सकती है.
- कुंजियां: कारोबारी या कंपनी के सार्वजनिक हस्ताक्षर करने वाले पासकोड. एजेंट इनका इस्तेमाल करके, कारोबारी या कंपनी के हस्ताक्षर की पुष्टि करते हैं.
- कार्रवाइयां: सेवा का पता चलने के बाद, एजेंट कार्रवाइयां करने के लिए, दिए गए सेवा एंडपॉइंट का इस्तेमाल करता है. इस कोडलैब में, हम मॉडल कॉन्टेक्स्ट प्रोटोकॉल (एमसीपी) का इस्तेमाल, सर्विस ट्रांसपोर्ट के तौर पर करते हैं. एजेंट, इस एंडपॉइंट पर JSON-RPC 2.0 कॉल करता है, ताकि खोजी गई क्षमताओं को लागू किया जा सके. जैसे, प्रॉडक्ट खोजना, चेकआउट बनाना, और खरीदारी पूरी करना.

Agent Payments Protocol (AP2)
AP2, इस बात को स्टैंडर्ड बनाता है कि एजेंट, उपयोगकर्ताओं की ओर से पेमेंट को कैसे अनुमति देते हैं. इससे, पेमेंट के संवेदनशील क्रेडेंशियल को मैनेज करने वाले एजेंट की सुरक्षा से जुड़ी समस्या हल हो जाती है.
यह कैसे काम करता है:
- कारोबारी या कंपनी के हस्ताक्षर: जब कोई एजेंट, यूसीपी प्रोटोकॉल का इस्तेमाल करके चेकआउट बनाता है, तो कारोबारी या कंपनी चेकआउट (लाइन आइटम और कुल कीमत) पर हस्ताक्षर करती है और
ap2.merchant_authorizationमें हस्ताक्षर वापस भेजती है. यह किराया लॉक करने की गारंटी की तरह काम करता है. अगर कारोबारी या कंपनी, हस्ताक्षर करने के बाद कीमत में बदलाव करती है, तो हस्ताक्षर मेल नहीं खाते. - चेकआउट और पेमेंट के लिए ज़रूरी कानूनी दस्तावेज़: चेकआउट के कॉन्टेंट की पुष्टि करने के बाद, उपयोगकर्ता (या उसकी ओर से एजेंट) दो कानूनी दस्तावेज़ों पर हस्ताक्षर करता है.
CheckoutMandateमें कारोबारी या कंपनी के हस्ताक्षर वाला चेकआउट शामिल होता है. इससे कारोबारी या कंपनी को पता चलता है कि उपयोगकर्ता ने इसे स्वीकार कर लिया है.PaymentMandate, चेकआउट के लिए पेमेंट की रकम को मंज़ूरी देता है. दोनों कुकी, साइन किए गए चेकआउट के हैश को रेफ़रंस करती हैं. साथ ही, इनमें उपयोगकर्ता का क्रिप्टोग्राफ़िक हस्ताक्षर होता है. - हस्ताक्षर की पुष्टि: कारोबारी या कंपनी को दोनों निर्देश मिलते हैं. यह
CheckoutMandateपर उपयोगकर्ता के हस्ताक्षर की पुष्टि करता है. साथ ही, यह देखता है कि इसमें मौजूद चेकआउट में कारोबारी या कंपनी का हस्ताक्षर है या नहीं.PaymentMandate, पेमेंट की प्रोसेस करने वाली कंपनी (क्रेडेंशियल देने वाली कंपनी या पेमेंट प्रोसेसर) के पास जाता है. यह कंपनी, पेमेंट की प्रोसेस करने से पहले इसकी पुष्टि करती है. अगर सब कुछ मान्य है, तो लेन-देन पूरा हो जाएगा.
"डबल लॉक" सिस्टम यह पक्का करता है कि कारोबारी या कंपनियां, खरीदारों से ज़्यादा शुल्क न लें. साथ ही, एजेंट बिना अनुमति के पैसे खर्च न कर पाएं. ये SD-JWT (चुनिंदा जानकारी ज़ाहिर करने वाला JWT) क्रेडेंशियल होते हैं. ये क्रेडेंशियल, उपयोगकर्ता की निजता की सुरक्षा करते हैं. ऐसा इसलिए, क्योंकि ये सिर्फ़ उन फ़ील्ड को ज़ाहिर करते हैं जिनकी हर पक्ष को ज़रूरत होती है. AP2 v0.2 में, CheckoutMandate ने AP2 v0.1 के CartMandate की जगह ले ली है.

3. अपना एनवायरमेंट सेट अप करने का तरीका
Google Cloud प्रोजेक्ट का सेटअप
Google Cloud प्रोजेक्ट बनाना
- Google Cloud Console में, प्रोजेक्ट चुनने वाले पेज पर जाकर, Google Cloud प्रोजेक्ट चुनें या बनाएं.
- पक्का करें कि आपके क्लाउड प्रोजेक्ट के लिए बिलिंग की सुविधा चालू हो. किसी प्रोजेक्ट के लिए बिलिंग चालू है या नहीं, यह देखने का तरीका जानें.
Cloud Shell शुरू करना
Cloud Shell, Google Cloud में चलने वाला एक कमांड-लाइन एनवायरमेंट है. इसमें ज़रूरी टूल पहले से लोड होते हैं.
- Google Cloud कंसोल में सबसे ऊपर मौजूद, Cloud Shell चालू करें पर क्लिक करें.
- Cloud Shell से कनेक्ट होने के बाद, अपने क्रेडेंशियल की पुष्टि करें:
gcloud auth list - पुष्टि करें कि आपका प्रोजेक्ट कॉन्फ़िगर किया गया है:
gcloud config get project - अगर आपका प्रोजेक्ट उम्मीद के मुताबिक सेट नहीं है, तो इसे सेट करें:
export PROJECT_ID=<YOUR_PROJECT_ID> gcloud config set project $PROJECT_ID
एपीआई चालू करें
ज़रूरी एपीआई चालू करने के लिए, यह कमांड चलाएं:
gcloud services enable aiplatform.googleapis.com
डायरेक्ट्री स्ट्रक्चर सेटअप करना
इस कोडलैब के लिए फ़ोल्डर बनाने के लिए, यहां दिए गए निर्देशों को कॉपी करके चिपकाएं. साथ ही, एजेंट कोड के लिए इसके अंदर agent_payments फ़ोल्डर बनाएं:
mkdir -p ~/adk-agent-commerce/agent_payments
cd ~/adk-agent-commerce
Gemini के मॉडल ऐक्सेस करना
अपने प्रोजेक्ट और जगह के हिसाब से agent_payments/.env बनाने के लिए, नीचे दिए गए कमांड को कॉपी करके चिपकाएं. साथ ही, Google Cloud प्रोजेक्ट के ज़रिए ADK को Gemini को कॉल करने की अनुमति दें. Cine Agent, Gemini का इस्तेमाल करके यह तय करता है कि किन टूल को कॉल करना है. ADK इस फ़ाइल को अपने-आप लोड कर लेता है. इसलिए, सेटिंग नए टर्मिनल में भी काम करती हैं.
cat > ~/adk-agent-commerce/agent_payments/.env <<EOF
GOOGLE_CLOUD_PROJECT=$(gcloud config get project)
GOOGLE_CLOUD_LOCATION=global
GOOGLE_GENAI_USE_ENTERPRISE=True
EOF
डिपेंडेंसी इंस्टॉल करना
Google Cloud Shell में, एनवायरमेंट और डिपेंडेंसी को मैनेज करने के लिए uv पहले से इंस्टॉल होता है.
- अपने
adk-agent-commerceफ़ोल्डर के रूट मेंpyproject.tomlफ़ाइल बनाएँ और उसमें यह कॉन्टेंट जोड़ें. इस फ़ाइल में, प्रोजेक्ट का मेटाडेटा और डिपेंडेंसी तय की जाती हैं.
[project]
name = "agent-payments-demo"
version = "0.1.0"
description = "CineAgent booking agent using UCP and AP2"
requires-python = ">=3.11"
dependencies = [
"google-adk",
"fastapi",
"uvicorn",
"httpx",
"ucp-sdk",
"ap2 @ git+https://github.com/google-agentic-commerce/AP2.git@main",
]
AP2 SDK को GitHub रिपॉज़िटरी से इंस्टॉल किया जाता है, क्योंकि इसे अब तक PyPI पर पब्लिश नहीं किया गया है. (PyPI पर मौजूद ap2 पैकेज, एक अलग प्रोजेक्ट है.)
- वर्चुअल एनवायरमेंट बनाने और सभी ज़रूरी सॉफ़्टवेयर इंस्टॉल करने के लिए, यह कमांड चलाएं:
uv sync
uv, इस कोडलैब के लिए एक अलग 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: यह वह प्रॉम्प्ट है जो एजेंट के व्यवहार को तय करता है. इसमें एजेंट को साफ़ तौर पर यूसीपी और AP2 का इस्तेमाल करने के लिए कहा गया है. साथ ही, इसमें उपलब्ध टूल की सूची दी गई है. इसमें "कभी भी डेटा न बनाएं" और "कीमतें सेंट में हैं" जैसे ज़रूरी नियम सेट किए गए हैं.tools: यह Python फ़ंक्शन की सूची है. इसे हम अगले चरण में बनाएंगे. एजेंट, उपयोगकर्ता के अनुरोधों के आधार पर इनमें से किसी फ़ंक्शन को कॉल कर सकता है.require_confirmation: किसी भी टूल कोFunctionTool(my_function,require_confirmation=True)के साथ रैप किया जा सकता है. ट्रिगर होने पर, एजेंट रुक जाता है और टूल को लागू करने से पहले, "हाँ" या "नहीं" में जवाब मिलने का इंतज़ार करता है. यहां,complete_purchaseटूल का इस्तेमाल करने से पहले, एजेंट को मैन्युअल तौर पर पुष्टि करने की ज़रूरत होती है.
टूल की सूची
एजेंट की परिभाषा से पता चलता है कि हमें क्या बनाना है. हर टूल, UCP या AP2 प्रोटोकॉल में किसी खास ऑपरेशन से मैप होता है:
टूल | यह क्या करता है | प्रोटोकॉल ऐक्शन |
| कारोबारी या कंपनियों और उनकी क्षमताओं के बारे में जानकारी पाना | क्वेरी |
| कारोबारियों या कंपनियों के कैटलॉग में खोज करना | एमसीपी एंडपॉइंट को JSON-RPC |
| किसी कारोबारी या कंपनी के शो का समय देखना | एमसीपी एंडपॉइंट को JSON-RPC |
| चेकआउट सेशन शुरू करना | एमसीपी एंडपॉइंट को JSON-RPC |
| पेमेंट की अनुमति देना और ऑर्डर पूरा करना | AP2 के निर्देशों का पालन करता है और उन्हें MCP को भेजता है |
Gemini मॉडल, बातचीत के आधार पर यह तय करेगा कि हर टूल को कब कॉल करना है. इसके बाद, हमारा काम यह है कि हम tools.py में हर टूल के काम करने के तरीके को लागू करें.
5. एजेंट के टूल बनाना: खोजने और ब्राउज़ करने की सुविधा
अब उन टूल को लागू करते हैं जिनका इस्तेमाल एजेंट, फ़िल्में ब्राउज़ करने और खोजने के लिए करेगा. हर टूल, यूसीपी ऑपरेशन को रैप करता है.
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])
सेटअप के बारे में जानकारी
इस कोडलैब में, एजेंट बनाने पर फ़ोकस किया गया है. इसलिए, हम दो हेल्पर क्लास, UCPClient और AP2Handler का इस्तेमाल कर रहे हैं. इनके बारे में हम बाद में जानेंगे.
- ये क्या हैं?: ये छोटी हेल्पर क्लास हैं. हमने इस कोडलैब के लिए इन्हें लिखा है, ताकि नकली कारोबारियों से बात की जा सके. आधिकारिक एसडीके, प्रोटोकॉल के हिस्से उपलब्ध कराते हैं: यूसीपी एसडीके में हर यूसीपी स्कीमा के लिए डेटा मॉडल होते हैं. वहीं, AP2 एसडीके, हस्ताक्षर किए गए निर्देशों को बनाता और उनकी पुष्टि करता है. इनमें से किसी भी एसडीके में, कारोबारियों या कंपनियों को कॉल करने के लिए क्लाइंट शामिल नहीं है. इसलिए, ये हेल्पर उस हिस्से को मैनेज करते हैं.
- फ़िलहाल, इन्हें हेल्पर ऑब्जेक्ट के तौर पर इस्तेमाल करें:
_ucp.discover(url): यह कारोबारी या कंपनी की प्रोफ़ाइल को फ़ेच करता है और उसकी पुष्टि करता है._ucp.mcp_call(url, method, params): कारोबारी या कंपनी के एमसीपी एंडपॉइंट को JSON-RPC 2.0 अनुरोध भेजता है.
थिएटर ढूंढना
यह टूल, यूसीपी फ़्लो का पहला चरण है. इससे यह पता चलता है कि कौनसे कारोबारी या कंपनियां मौजूद हैं और वे कौनसी सुविधाएं देती हैं.
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)
इससे क्या होता है:
- यह सर्वर से मिले कारोबारी या कंपनी के यूआरएल की सूची पर काम करता है. इस कोडलैब में, हम बाद के सेक्शन में दो मॉक कारोबारी या कंपनियों को सेट अप करेंगे.
- यह हर यूआरएल के लिए
_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}})) भेजता है. - इसके बाद, यह नतीजों को पार्स करके फ़िल्में और उनके "वैरिएंट" ढूंढता है. "वैरिएंट" से, फ़िल्म के खास शोटाइम और फ़ॉर्मैट के बारे में पता चलता है. यह कुकी, फ़िल्मों को आईडी के हिसाब से ग्रुप करती है, ताकि उपयोगकर्ता को फ़िल्मों की डुप्लीकेट एंट्री न दिखें.
फ़िल्म की जानकारी पाना
यह टूल, किसी थिएटर में दिखाई जा रही किसी फ़िल्म के कैटलॉग की पूरी जानकारी देता है.
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तरीके को कॉल करता है. साथ ही,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)
इससे क्या होता है:
- यह कारोबारी या कंपनी के एमसीपी एंडपॉइंट पर
create_checkoutतरीके को कॉल करता है. - यह उपयोगकर्ता के अनुरोध किए गए
showtime_idऔरquantityको पास करता है. - कारोबारी या कंपनी, कारोबारी या कंपनी की कुंजी से हस्ताक्षर किया गया चेकआउट वापस भेजती है.
ध्यान दें: अगर जवाब के डेटा की जांच की जाती है, तो ap2.merchant_authorization फ़ील्ड में कारोबारी या कंपनी का क्रिप्टोग्राफ़िक हस्ताक्षर होता है. यह हस्ताक्षर, चेकआउट के दौरान कोट की गई कीमत को लॉक कर देता है. इसे बाद में बदला नहीं जा सकता!
खरीदारी पूरी करें
इस टूल में तीन काम होते हैं:
- हमें चेकआउट मिलता है और हम उस पर कारोबारी या कंपनी के हस्ताक्षर की पुष्टि करते हैं.
- AP2 SDK की मदद से, CheckoutMandate और PaymentMandate बनाएं और उन पर हस्ताक्षर करें.
- खरीदारी पूरी करने के लिए, दोनों मैंडेट कारोबारी या कंपनी को भेजें.
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 में अब पांच टूल फ़ंक्शन होने चाहिए. साथ ही, यूसीपी और 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. इसे चलाने लायक बनाएं
यूसीपी का इस्तेमाल करने वाले असली कारोबारियों या कंपनियों के लिए, एजेंट को उनके यूआरएल पर रीडायरेक्ट किया जाता है. इस कोडलैब के लिए, हमें स्थानीय तौर पर जांच करने के लिए दो चीज़ों की ज़रूरत होगी:
- मॉक कारोबारी या कंपनियां: ये लोकल सर्वर होते हैं, जो यूसीपी एंडपॉइंट का सिम्युलेट करते हैं, ताकि आपके पास टेस्ट करने के लिए कुछ हो
- प्रोटोकॉल हेल्पर: ये थिन रैपर होते हैं, जो एचटीटीपी पर कारोबारियों या कंपनियों को कॉल करते हैं. साथ ही, प्रोटोकॉल डेटा और सिग्नेचर के लिए यूसीपी और AP2 एसडीके का इस्तेमाल करते हैं
ध्यान दें: आपको इस कोड को ध्यान से पढ़ने की ज़रूरत नहीं है. ये फ़ाइलें, असल कारोबारियों या कंपनियों और उपयोगकर्ता के वॉलेट की तरह काम करती हैं. उन्हें बिना किसी बदलाव के कॉपी करें.
प्रोटोकॉल हेल्पर
यूसीपी एसडीके, डेटा मॉडल उपलब्ध कराता है. वहीं, 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: यूसीपी की खोज. कारोबारी या कंपनी की सुविधाओं, एमसीपी एंडपॉइंट यूआरएल, स्वीकार किए गए पेमेंट के तरीकों, और सार्वजनिक हस्ताक्षर कुंजी की जानकारी दिखाता है.POST /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)
पहले टर्मिनल पर वापस जाएं और यूसीपी डिस्कवरी की पुष्टि करें:
curl -s http://localhost:8081/.well-known/ucp | uv run python -m json.tool
आपको कारोबारी या कंपनी की सुविधाएं, एमसीपी एंडपॉइंट यूआरएल, पेमेंट हैंडलर, और सार्वजनिक पासकोड दिखना चाहिए.
8. ADK Web की मदद से एजेंट को चलाना
आइए, 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 वेब यूज़र इंटरफ़ेस शुरू करें:
cd ~/adk-agent-commerce
uv run adk web --port 8080 --allow_origins '*'
आपको ऐसा आउटपुट दिखेगा जिससे पता चलेगा कि सर्वर http://127.0.0.1:8080 पर चल रहा है.
एजेंट से बात करें
- यूआरएल पर Ctrl या Cmd क्लिक करके, ADK का वेब यूज़र इंटरफ़ेस (यूआई) खोलें. इसके अलावा, वेब झलक बटन पर क्लिक करके और पोर्ट 8080 पर झलक देखें को चुनकर भी इसे खोला जा सकता है.
- अगर
agent_paymentsको पहले से नहीं चुना गया है, तो ड्रॉप-डाउन मेन्यू से इसे चुनें. आपको चैट इंटरफ़ेस दिखेगा. - "कौनसी फ़िल्में चल रही हैं?" पूछकर देखें
- एजेंट, पर्दे के पीछे थिएटर खोजेगा और कैटलॉग खोजेगा. साथ ही, यूसीपी के ज़रिए दोनों कारोबारियों या कंपनियों से नतीजे इकट्ठा करेगा.
- टिकट बुक करने के लिए कहें: "ओपनहाइमर के लिए शाम 7 बजे के दो टिकट बुक करो".
- जब एजेंट
complete_purchaseको कॉल करने की कोशिश करता है, तब देखें कि ADK Web UI, खरीदारी की जानकारी के साथ पुष्टि करने वाला कार्ड कैसे दिखाता है! - लेन-देन को मंज़ूरी देने के लिए, कार्ड पर मौजूद पुष्टि की गई चेकबॉक्स को चुनें. इसके बाद, सबमिट करें पर क्लिक करें.
- एजेंट खरीदारी की प्रोसेस पूरी करेगा और आपको टिकट कोड के साथ, ऑर्डर की पुष्टि करने वाला ईमेल भेजेगा!
यहां बताया गया है कि पर्दे के पीछे क्या हुआ:
create_checkout→ कारोबारी या कंपनी ने अपनी कुंजी (ap2.merchant_authorization, कीमत लॉक) के साथ साइन किया गया चेकआउट पेज दिखायाcomplete_purchase→ कारोबारी या कंपनी के हस्ताक्षर की पुष्टि की, CheckoutMandate और PaymentMandate बनाया, दोनों पर एसडी-जेडब्ल्यूटी के तौर पर हस्ताक्षर किए, और उन्हें कारोबारी या कंपनी को भेजा- कारोबारी या कंपनी ने दोनों निर्देशों की पुष्टि कर ली है और यह देख लिया है कि वे उस चेकआउट पेज पर ले जाते हैं जिस पर हस्ताक्षर किया गया है → टिकट जारी किए गए (मॉक में)
9. व्यवस्थित करें
लोकल सर्वर को चालू रखने से बचने के लिए, संसाधनों को बंद करें:
adk webचलाने वाले टर्मिनल में, एजेंट सर्वर को रोकने के लिए Ctrl+C दबाएं.merchants.pyचलाने वाले टर्मिनल में, नकली कारोबारियों को रोकने के लिए Ctrl+C दबाएं.- (ज़रूरी नहीं) अगर आपने इस कोडलैब के लिए नया Google Cloud प्रोजेक्ट बनाया है और आपको इसे मिटाना है, तो यहां दिया गया निर्देश चलाएं. साथ ही,
की जगह प्रोजेक्ट आईडी डालें:
gcloud projects delete <YOUR_PROJECT_ID>
10. बधाई हो! 🎉
आपने एक ऐसा ADK एजेंट बनाया है जो कारोबारियों या कंपनियों का पता लगाता है, कैटलॉग ब्राउज़ करता है, और यूसीपी और AP2 का इस्तेमाल करके खरीदारी पूरी करता है.
आपने क्या सीखा
इस कोडलैब में, आपने एक ऐसा ADK एजेंट बनाया है जो सुरक्षित कॉमर्स फ़्लो को मैनेज करता है. आपने जो बनाया है उसकी खास जानकारी और इस्तेमाल किए गए मुख्य कॉन्सेप्ट यहां दिए गए हैं:
आपने क्या बनाया:
- यूसीपी और AP2 की सुविधाओं के साथ पांच एजेंट टूल: खोज, कैटलॉग में खोज, चेकआउट, पेमेंट.
- AP2 मैंडेट पर हस्ताक्षर करना: कारोबारी या कंपनी के हस्ताक्षर वाला चेकआउट (कीमत लॉक करना) + CheckoutMandate और PaymentMandate (उपयोगकर्ता की अनुमति).
- एक से ज़्यादा कारोबारियों या कंपनियों के प्रॉडक्ट खोजना: एक एजेंट, कई थिएटर से क्वेरी करता है और नतीजों को मर्ज करता है.
मुख्य सिद्धांत:
प्रोटोकॉल | यह क्या करता है | यह कैसे काम करता है |
UCP डिस्कवरी | एजेंट, कारोबारियों या कंपनियों और उनकी क्षमताओं के बारे में जानकारी ढूंढता है |
|
यूसीपी एमसीपी | एजेंट, कैटलॉग ब्राउज़ करता है और चेकआउट बनाता है | कारोबारी या कंपनी के एमसीपी एंडपॉइंट को JSON-RPC 2.0 कॉल |
कारोबारी या कंपनी को अनुमति देना | कारोबारी या कंपनी, बताई गई कीमत को लॉक कर देती है | कारोबारी या कंपनी के हस्ताक्षर वाला इनवॉइस, जिसमें लाइन आइटम और कुल रकम शामिल हो |
AP2 CheckoutMandate | उपयोगकर्ता, सटीक चेकआउट को स्वीकार करता है | इस कुकी पर उपयोगकर्ता के हस्ताक्षर होते हैं. इसमें कारोबारी या कंपनी के हस्ताक्षर वाला चेकआउट शामिल होता है |
AP2 PaymentMandate | उपयोगकर्ता शुल्क चुकाने की अनुमति देता है | इस कुकी पर उपयोगकर्ता के हस्ताक्षर होते हैं. यह चेकआउट हैश का रेफ़रंस देती है |
प्रोडक्शन में क्या अलग है?
इस कोडलैब में मॉक का इस्तेमाल किया जाता है. प्रोडक्शन में:
- यूसीपी डिस्कवरी, हार्डकोड किए गए लोकल होस्ट यूआरएल के बजाय किसी रजिस्ट्री के ख़िलाफ़ काम करती है
- एमसीपी एंडपॉइंट को असली कारोबारी या कंपनियां होस्ट करती हैं: एक जैसा JSON-RPC 2.0 प्रोटोकॉल, असली इन्वेंट्री
- AP2 के ज़रूरी दस्तावेज़ों पर, उपयोगकर्ता के भरोसेमंद डिवाइस या भरोसेमंद प्लैटफ़ॉर्म से हस्ताक्षर किए जाते हैं. स्टार्टअप के दौरान एजेंट की जनरेट की गई कुंजी से हस्ताक्षर नहीं किए जाते
- हस्ताक्षर करने के लिए इस्तेमाल की जाने वाली कुंजियां, हर पक्ष की यूसीपी प्रोफ़ाइल से मिलती हैं. हालांकि, नकली कारोबारियों को हर अनुरोध में एजेंट की सार्वजनिक कुंजी मिलती है
- पेमेंट की अनुमति, क्रेडेंशियल देने वाली कंपनी के ज़रिए दी जाती है. यह कंपनी, पेमेंट मैंडेट की पुष्टि करती है और उपयोगकर्ता से सहमति मांगती है
- फ़्रंटएंड, टूल के नतीजों को रिच यूज़र इंटरफ़ेस (यूआई) के तौर पर रेंडर करता है. जैसे, प्रॉडक्ट ग्रिड, चेकआउट की खास जानकारी, पुष्टि करने वाले कार्ड
अगले चरण
- AP2 प्रोटोकॉल स्पेसिफ़िकेशन के बारे में जानें और पेमेंट की सुविधा वाला अपना एजेंट बनाएं
- एजेंटिक कॉमर्स की सुविधा चालू करने के लिए, कारोबारी या कंपनी के लिए यूसीपी लागू करें
- मल्टी-एजेंट कॉमर्स वर्कफ़्लो के लिए, AP2 को A2A से कनेक्ट करना
- क्रिप्टो करंसी से पेमेंट के लिए, AP2 x402 एक्सटेंशन के बारे में जानें