Skip to main content






Tutorial: Building UCP powered e-commerce stores
UCP provides a standard way for software agents and platforms to purchase directly from a merchant without becoming the merchant.
Last updated: January 15, 2026
AI agents are becoming capable of performing real tasks on a user’s behalf not just answering questions or making recommendations. They can search, compare products, reason about tradeoffs, and decide on next steps. However, for these agents to reach their full potential, they need a universal set of protocols that enable them to operate in the world without relying on brittle UI automation, custom integrations, or one-off APIs for every service they touch.
The Universal Commerce Protocol (UCP) is one attempt to solve this problem in e-commerce. It provides a standard way for software agents and platforms to purchase directly from a merchant. Instead of scraping pages, simulating clicks, or embedding bespoke SDKs, a client communicates with a store using a shared commerce language. The merchant retains control over pricing, payments, and order creation, while the agent or platform serves as a frontend that helps the user decide what to buy.
At its core, UCP standardizes how the commerce state is represented and updated. A cart, a checkout, a payment option, and an order all have defined schemas and lifecycles. A client does not infer meaning from HTML or guess how totals are computed. It asks the merchant to create or update a checkout session, and the merchant responds with an authoritative object that reflects the true state on its servers. This creates a clear boundary between decision-making and execution, exactly what AI-driven systems need as they move from suggesting actions to executing them.

Table of contents
Table of contentsWhy UCP is neededBasic concepts of UCP Other core pieces of UCPIdentity linkingThe order objectPayments and handlersThe importance of logging for UCP-powered stores Tutorial: Building a store and chatbot with UCP Support Building the Store Server Client responsibilitiesTesting the UCP Agent and chat client end-to-endConclusion
Why UCP is needed
Today, programmatic e-commerce is messy. Every merchant exposes a different set of endpoints, uses disparate field names, calculates prices differently, and expects different steps to complete a purchase. Even when two stores sell similar products, the logic for adding items, selecting payment methods, and placing an order can be inconsistent. For humans, this complexity is hidden behind UI. For software, it quickly becomes a problem. Because there is no shared way to make a purchase, automation often falls back to UI-level approaches. “Computer use” agents try to click through websites and infer meaning from HTML meant for people. While impressive, this approach remains early and fragile, and it breaks easily as interfaces evolve. It is a workaround, not a foundation.
The deeper issue is fragmentation. If every merchant defines purchasing differently, then every agent or platform has to integrate with every store separately. That does not scale. It leads to custom logic, brittle automation, and repeated effort across the ecosystem.
UCP exists to standardize the part that should not vary across markets: the act of buying. Instead of automating user interfaces, it exposes commerce as a structured state with explicit rules and transitions. Clients request changes, merchants return authoritative results, and both sides agree on the meaning of each step.
As AI systems move from suggesting actions to executing them, these kinds of shared protocols become necessary. UCP replaces guesswork with explicit state and makes automated purchasing reliable across many merchants.
Basic concepts of UCP
Before a client (for example, a chatbot like Gemini or ChatGPT) attempts to create a checkout or place an order, it needs to understand the type of store it is interacting with.
UCP handles this through discovery. Every UCP-enabled merchant exposes a standard endpoint at /.well-known/ucp. A client can fetch this once and get a machine-readable description of how to interact with the store.
That discovery response informs the client which UCP version the merchant supports, which commerce services are available, and which capabilities are enabled. It also includes where requests should be sent and which payment handlers the merchant accepts. Nothing about a specific user or purchase appears here. This is a purely declarative statement of what the merchant can do and how it expects to be contacted.
Once discovery is complete, the client knows how to speak to the merchant without guessing. It knows which schemas to expect, which features are safe to use, and which actions are unsupported. This step replaces hardcoded integrations and documentation-driven assumptions with something that software can reason about automatically.
After discovery, all interactions occur via structured JSON objects. The most important of these is the checkout. A checkout is a single object that represents a purchase in progress, including line items, merchant-calculated prices, totals, accepted payment methods, and a status indicating the purchase's lifecycle stage. The client treats these objects as a read-only state. Creation and updates are initiated by sending requests to the merchant, which responds with the current authoritative version. That response reflects the state held on the merchant’s server at that moment. When the state changes, a new version is returned, and the client swaps its local copy and reacts to the updated fields.
Here's a diagram of the lifecycle of the checkout object:

A checkout starts incomplete, moves forward as required information is provided, and eventually transitions to completed when an order has been successfully created. Clients cannot skip steps or force transitions. They can only ask, and the merchant decides whether the request is valid by returning an updated object. Taken together, discovery plus structured state is what makes UCP work. Discovery explains how a client should interact with a store. The schemas define what that interaction looks like. The lifecycle rules ensure that commerce actions occur in a controlled, predictable manner, even when the client is an AI agent rather than a human-operated app.
Other core pieces of UCP
Checkout is only one part of what UCP defines. Once you look past the flow of adding items and completing a purchase, there are a few other parts that matter just as much if you want automated commerce to work end to end. I will briefly cover these concepts; however, if you would like to learn more about these components of UCP, I recommend checking out the official UCP docs.
Identity linking
Before a platform or agent can act on a user's behalf, the merchant must know who the user is and what they are authorized to do. UCP handles this through identity linking. At a high level, this is a standardized way for a user to authorize a platform to access their account on a merchant’s site.
Under the hood, this is built on OAuth. The user is redirected to the merchant, signs in or creates an account, and explicitly grants permission for certain commerce actions. Once this link exists, the platform can perform authenticated operations like accessing saved addresses, applying loyalty benefits, or completing checkouts without asking the user to re-authenticate every time.
The important point is not the OAuth details, but the separation of responsibility. The merchant owns the user account and authorization. The platform gets a token that represents what it is allowed to do. UCP standardizes how that relationship is discovered, negotiated, and used, so platforms do not need a custom account-linking flow for every merchant.
The order object
Once a checkout is completed, the result is an order. In UCP, an order is not just a receipt. It is a long-lived object that represents everything that happens after purchase.
The order captures what was purchased, how much has been fulfilled, and the current status. It also tracks fulfillment expectations, which are the promises shown to the buyer about when and how items will arrive. Separately, it records what actually happened through append-only event logs such as shipments, deliveries, or failed attempts.
UCP also treats post-purchase changes as first-class data. Refunds, returns, cancellations, disputes, and price adjustments are modeled as events that can occur at any point in the order’s lifecycle. This makes the order a single, authoritative source of truth rather than something that has to be reconstructed from emails, dashboards, or ad hoc APIs.
For platforms and agents, this matters because it enables them to reason about the state of a purchase over time. They can answer questions such as what has shipped, what is still pending, or whether a refund has been issued, without relying on merchant-specific conventions.
Payments and handlers
Payments are handled differently from checkout and orders because there is no single payment system used by everyone. UCP does not try to replace card networks, wallets, or processors. Instead, it defines a common way to describe how payments are wired in.
This is done through payment handlers. A handler is a specification that describes who participates in a payment flow, the required setup, how a payment instrument is created, and how it is processed. A handler might represent a card flow, a wallet such as Google Pay, or a merchant-specific method, such as a stored balance.
From the platform’s perspective, this creates a consistent interface. The merchant advertises which handlers it supports and how they are configured. The platform adheres to the handler’s rules to acquire a payment instrument, bind it to a specific checkout, and submit it. The merchant or payment provider processes it and returns a clear result.
By separating the structure of payments from the details of individual providers, UCP enables support for multiple payment methods without creating a new integration model each time. Platforms gain predictability, merchants retain flexibility, and payment systems can evolve independently.
Together, identity linking, orders, and payment handlers complete the picture. Checkout moves a purchase forward, identity establishes who is acting, orders track what happens next, and payments define how money actually moves. UCP ties these pieces together into a coherent protocol rather than a collection of one-off integrations.
The importance of logging for UCP-powered stores
As automation and AI agents drive more activity in stores, it becomes critically important for merchants to understand the retrieval process. Agents interact directly with your backend, sending structured requests for products or categories rather than clicking through web pages. Without detailed, structured logging, it is almost impossible to answer questions such as:
- What are people or agents looking for most?
- Which search queries return useful results, and which fall flat?
- Where in the process do users or agents abandon their shopping journey?
Traditional server logs and analytics do not provide sufficient depth for these new scenarios. They cannot reveal the agent's reasoning process: how search queries are generated, refined, and matched to products, or where misunderstandings and errors occur.
When you can review every search request, every catalog lookup, and every checkout update, you gain the power to optimize both your storefront and the AI agent’s experience. This is not just about catching errors. It is about seeing real behavior and making informed improvements.
W&B Weave is an observability and evaluation tool built by Weights & Biases that provides a clear, visual record of every important action in your commerce backend. This includes searches, recommendations, catalog listings, and checkout steps. You can trace each user or agent journey, see which queries were made, which products were offered, and how decisions unfolded.
With Weave, it is easy to identify which searches succeed and which do not, observe trends in product discovery, and identify where users or agents drop off before completing a purchase. Observability with Weave means you do not have to guess what is happening in your store. You can see it directly, analyze it, and make data-driven improvements.
In the tutorial that follows, you will see how Weave fits into a UCP-powered commerce server and how it makes every search and transaction observable and auditable. This is a crucial foundation for reliable, agent-driven commerce.
Tutorial: Building a store and chatbot with UCP Support
AI agents are moving from answering questions to performing tasks. However, for an agent to reliably buy something, it shouldn't have to scrape a website or guess at UI buttons. It needs a shared language.
This tutorial builds a complete UCP-powered commerce system to demonstrate boundaries:
- The Client captures user intent (what they want)
- The Merchant enforces rules and state (what is allowed)
- UCP is the contract that keeps them separated
By the end, you should have an AI interface that executes real purchases without hardcoded logic or brittle web scraping.
Building the Store Server
We'll start with the merchant. In a UCP architecture, the backend is the absolute system of record.
Unlike a traditional API where a client might calculate a cart total locally, here the server owns every piece of commerce state. The server runs an internal agent that translates natural language (like "add that book") into strict commerce tool calls.
The server performs three specific jobs:
- Discovery: It exposes /.well-known/ucp so clients can learn what it supports without prior integration.
- Agentic logic: It uses an LLM to interpret user requests and call tools like search_products or add_to_checkout.
- State management: It calculates prices, totals, and creates orders. The client never mutates this state directly; it only requests changes.
Prerequisites: Run the following install command and set your Gemini API key:
pip install ucp weave flask google-genai flask-cors
The server code: Notice how the process_agent_request function sits between the user and the logic, turning text into UCP-compliant JSON objects.
"""UCP Store Server - Agent-based Backend (Simplified)Runs on port 5001 - Agent handles shopping requests"""from flask import Flask, jsonify, requestfrom flask_cors import CORSimport uuidimport loggingimport os# UCP SDK importsfrom ucp_sdk.models.schemas.shopping.checkout_resp import CheckoutResponsefrom ucp_sdk.models.schemas.shopping.types.line_item_resp import LineItemResponsefrom ucp_sdk.models.schemas.shopping.types.item_resp import ItemResponsefrom ucp_sdk.models.schemas.shopping.types.total_resp import TotalResponsefrom ucp_sdk.models.schemas.shopping.payment_resp import PaymentResponsefrom ucp_sdk.models.schemas.shopping.types.payment_handler_resp import PaymentHandlerResponsefrom ucp_sdk.models.schemas.shopping.types.order_confirmation import OrderConfirmationfrom ucp_sdk.models.schemas.shopping.types.buyer import Buyerfrom ucp_sdk.models.schemas.ucp import ResponseCheckout as UcpMetadata# Google Gemini (simpler than full ADK)from google import genaifrom google.genai import typesimport weave; weave.init("store-search")app = Flask(__name__)CORS(app)logging.basicConfig(level=logging.INFO)# Check for API keyif not os.getenv("GOOGLE_API_KEY"):print("\n⚠️ WARNING: GOOGLE_API_KEY not set!")print("Set it with: export GOOGLE_API_KEY='your_key_here'")print("Get a key from: https://aistudio.google.com/apikey\n")# ============================================================================# Product Catalog & Storage# ============================================================================PRODUCTS = [{"id": "ebook-001","title": "Principles by Ray Dalio","description": "Life and Work - Learn the secrets that drove one of the world's most successful investors","price": 1499, # $14.99"currency": "USD","category": "business","image_url": "https://via.placeholder.com/150?text=Principles"},{"id": "ebook-002","title": "Zero to One by Peter Thiel","description": "Notes on Startups, or How to Build the Future","price": 1299, # $12.99"currency": "USD","category": "business","image_url": "https://via.placeholder.com/150?text=Zero+to+One"},{"id": "ebook-003","title": "Atomic Habits by James Clear","description": "An Easy & Proven Way to Build Good Habits & Break Bad Ones","price": 1399, # $13.99"currency": "USD","category": "self-help","image_url": "https://via.placeholder.com/150?text=Atomic+Habits"},]PAYMENT_HANDLERS = [PaymentHandlerResponse(id="mock_card_handler",name="com.simpledemo.mock_payment",version="2026-01-11",spec="http://localhost:5001/docs/payment",config_schema="http://localhost:5001/schemas/mock_payment_config.json",instrument_schemas=["https://ucp.dev/schemas/shopping/types/card_payment_instrument.json"],config={"supported_cards": ["visa", "mastercard", "amex"],"test_mode": True})]# In-memory storage (session_id -> checkout)checkouts = {}sessions = {} # session_id -> {checkout_id, conversation_history, etc.}# ============================================================================# Tool Functions# ============================================================================@weave.opdef search_products(query: str = "") -> dict:"""Search for products in the catalogArgs:query: Search query. If empty or generic, returns all products.Returns:dict: Product search results"""try:query_lower = query.lower().strip()# Generic/empty queries - show all productsgeneric_queries = ["", "all", "everything", "anything", "available", "have", "books", "ebooks"]if query_lower in generic_queries or len(query_lower) < 3:logging.info(f"[SEARCH] Showing all products (query: '{query}')")return {"type": "product_results","content": f"Here are all the ebooks we have available:","results": PRODUCTS}# Specific searchresults = [p for p in PRODUCTSif query_lower in p["title"].lower()or query_lower in p["description"].lower()or query_lower in p["category"].lower()]logging.info(f"[SEARCH] '{query}' found {len(results)} products")if len(results) == 0:return {"type": "product_results","content": f"I couldn't find any ebooks matching '{query}'. Here's everything we have:","results": PRODUCTS}return {"type": "product_results","content": f"I found {len(results)} ebook(s) matching '{query}':","results": results}except Exception as e:logging.exception("Error searching products")return {"type": "error", "message": str(e)}def list_categories() -> dict:"""List all available product categoriesReturns:dict: List of categories with product counts"""try:# Get unique categories with countscategories = {}for product in PRODUCTS:cat = product["category"]if cat not in categories:categories[cat] = {"name": cat,"count": 0,"products": []}categories[cat]["count"] += 1categories[cat]["products"].append(product["title"])category_list = list(categories.values())logging.info(f"[CATEGORIES] Listing {len(category_list)} categories")# Format messagecontent = "We have ebooks in these categories:\n"for cat in category_list:content += f"• {cat['name'].title()}: {cat['count']} book(s)\n"return {"type": "categories","content": content,"categories": category_list}except Exception as e:logging.exception("Error listing categories")return {"type": "error", "message": str(e)}def add_to_checkout(session_id: str, product_id: str, quantity: int = 1) -> dict:"""Add product to checkout"""try:# Get sessionif session_id not in sessions:sessions[session_id] = {}session = sessions[session_id]checkout_id = session.get("checkout_id")# Find productproduct = next((p for p in PRODUCTS if p["id"] == product_id), None)if not product:return {"type": "error", "message": f"Product {product_id} not found"}# Get or create checkoutif checkout_id and checkout_id in checkouts:checkout = checkouts[checkout_id]else:checkout_id = str(uuid.uuid4())ucp_metadata = UcpMetadata(version="2026-01-11",capabilities=[{"name": "dev.ucp.shopping.checkout","version": "2026-01-11"}])checkout = CheckoutResponse(ucp=ucp_metadata,id=checkout_id,status="incomplete",line_items=[],currency="USD",totals=[],payment=PaymentResponse(handlers=PAYMENT_HANDLERS,selected_instrument_id=None,instruments=[]),links=[])checkouts[checkout_id] = checkoutsession["checkout_id"] = checkout_id# Add line itemitem_total = product["price"] * quantityline_item = LineItemResponse(id=str(uuid.uuid4()),item=ItemResponse(id=product["id"],title=product["title"],price=product["price"],image_url=product.get("image_url")),quantity=quantity,totals=[TotalResponse(type="subtotal", amount=item_total),TotalResponse(type="total", amount=item_total)])checkout.line_items.append(line_item)# Recalculate totalssubtotal = sum(item.totals[-1].amount for item in checkout.line_items)checkout.totals = [TotalResponse(type="subtotal", amount=subtotal, display_text="Subtotal"),TotalResponse(type="total", amount=subtotal, display_text="Total")]logging.info(f"[ADD_TO_CART] {quantity}x {product['title']} -> checkout {checkout_id}")return {"type": "checkout","checkout": checkout.model_dump(mode="json", by_alias=True)}except Exception as e:logging.exception("Error adding to checkout")return {"type": "error", "message": str(e)}def update_customer_email(session_id: str, email: str) -> dict:"""Update customer email for digital delivery"""try:session = sessions.get(session_id)if not session or "checkout_id" not in session:return {"type": "error", "message": "No checkout session found"}checkout_id = session["checkout_id"]checkout = checkouts.get(checkout_id)if not checkout:return {"type": "error", "message": "Checkout not found"}# Add buyer with emailcheckout.buyer = Buyer(email=email)# No shipping for digital products - just subtotal and totalsubtotal = checkout.totals[0].amountcheckout.totals = [TotalResponse(type="subtotal", amount=subtotal, display_text="Subtotal"),TotalResponse(type="total", amount=subtotal, display_text="Total")]checkout.status = "ready_for_complete"logging.info(f"[EMAIL] Updated for {email}")return {"type": "checkout","checkout": checkout.model_dump(mode="json", by_alias=True)}except Exception as e:logging.exception("Error updating email")return {"type": "error", "message": str(e)}def complete_order(session_id: str, payment_data: dict) -> dict:"""Complete the order - only called when payment data is submitted from client"""try:session = sessions.get(session_id)if not session or "checkout_id" not in session:return {"type": "error", "message": "No checkout session found"}checkout_id = session["checkout_id"]checkout = checkouts.get(checkout_id)if not checkout:return {"type": "error", "message": "Checkout not found"}# Validate email was providedif not checkout.buyer or not checkout.buyer.email:logging.error(f"[ORDER] Cannot complete - no email provided")return {"type": "error", "message": "Email address required before completing order"}# Validate payment data was providedif not payment_data:logging.error(f"[ORDER] Cannot complete - no payment data")return {"type": "error", "message": "Payment information required"}# Mock payment processingtransaction_id = f"txn_{uuid.uuid4().hex[:12]}"# Complete checkoutcheckout.status = "completed"order_id = f"ORD-{checkout_id[:8]}"checkout.order = OrderConfirmation(id=order_id,permalink_url=f"http://localhost:5001/orders/{order_id}")# Clear sessionsession["checkout_id"] = Nonelogging.info(f"[ORDER] {order_id} completed! Txn: {transaction_id}, Email: {checkout.buyer.email}")return {"type": "checkout","checkout": checkout.model_dump(mode="json", by_alias=True)}except Exception as e:logging.exception("Error completing order")return {"type": "error", "message": str(e)}# ============================================================================# Gemini Tools Configuration# ============================================================================TOOLS = [{"function_declarations": [{"name": "search_products","description": "Search for ebooks in the catalog. If query is empty/generic or user asks 'what do you have', show ALL products. Also use this to show products by category.","parameters": {"type": "object","properties": {"query": {"type": "string","description": "Search query. Can be empty to show all products, a category name (business, self-help), or specific keywords. If user asks 'what books are available' or 'show me books', use empty string.","default": ""}},"required": []}},{"name": "list_categories","description": "List all available ebook categories with counts. Use this when user asks about categories or types of books available.","parameters": {"type": "object","properties": {},"required": []}},{"name": "add_to_checkout","description": "Add a product to the shopping cart","parameters": {"type": "object","properties": {"product_id": {"type": "string","description": "Product ID (e.g. 'cookie-001')"},"quantity": {"type": "integer","description": "Quantity to add","default": 1}},"required": ["product_id"]}},{"name": "update_customer_email","description": "Update customer email address for ebook delivery","parameters": {"type": "object","properties": {"email": {"type": "string","description": "Customer email address for ebook delivery"}},"required": ["email"]}}]}]SYSTEM_PROMPT = """You are a helpful ebook shopping assistant. You can help customers:- Browse and search for ebooks in our catalog- Add ebooks to their cart- Collect their email for digital deliveryWe sell digital ebooks that are delivered instantly via email. No shipping address needed!IMPORTANT BEHAVIOR:1. **Be proactive with browsing**: When users ask "what do you have", "what books are available", "show me books", or seem unsure, IMMEDIATELY call search_products with an empty query to show ALL products. Don't ask for more details first - just show them what we have!2. **Categories**: If user asks about categories or types of books, call list_categories to show what's available.3. **Search**: For specific requests like "business books" or "habits", call search_products with that query.4. **Checkout Flow** (CRITICAL):- When customer wants to checkout, you MUST ask for their email address- Once you have their email, call update_customer_email- After email is saved, tell them to click "Proceed to Payment" button to complete their purchase- DO NOT try to complete the order yourself - the payment is handled by the UI- If they ask "how do I pay" or "how do I complete checkout", tell them to use the "Proceed to Payment" buttonBe friendly and conversational. Show products proactively - don't make users work to see what's available!"""# ============================================================================# A2A Message Handler# ============================================================================@weave.opdef process_agent_request(context_id: str, user_text: str, action_data: dict, request_id: str) -> dict:"""Process agent request and return JSON-RPC responseArgs:context_id: Session/context IDuser_text: User's message textaction_data: Additional action data from requestrequest_id: JSON-RPC request IDReturns:dict: JSON-RPC response object"""# Initialize session if neededif context_id not in sessions:sessions[context_id] = {"conversation_history": []}session = sessions[context_id]# Check if this is a payment completion requestif action_data.get("action") == "complete_checkout":payment_data = action_data.get("a2a.ucp.checkout.payment_data")result = complete_order(context_id, payment_data)response_parts = []if result["type"] == "checkout":response_parts.append({"type": "text","text": f"Order confirmed! Your order has been placed successfully."})response_parts.append({"type": "data","data": {"a2a.ucp.checkout": result["checkout"]}})else:response_parts.append({"type": "text","text": f"Error: {result['message']}"})return {"jsonrpc": "2.0","id": request_id,"result": {"contextId": context_id,"parts": response_parts}}# Use Gemini to handle the requestclient = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))# Add user message to historysession["conversation_history"].append({"role": "user","parts": [{"text": user_text}]})response_parts = []max_turns = 5 # Prevent infinite loops# Multi-turn function calling loopfor turn in range(max_turns):# Call Gemini with full conversation historyresponse = client.models.generate_content(model="gemini-2.5-flash",contents=session["conversation_history"],config=types.GenerateContentConfig(system_instruction=SYSTEM_PROMPT,tools=TOOLS,))model_parts = []has_function_call = False# Process responseif response.candidates[0].content.parts:for part in response.candidates[0].content.parts:if part.text:model_parts.append({"text": part.text})elif part.function_call:has_function_call = Truefc = part.function_calllogging.info(f"[FUNCTION_CALL] {fc.name}({fc.args})")model_parts.append({"function_call": {"name": fc.name,"args": dict(fc.args)}})# Execute the functionif fc.name == "search_products":result = search_products(**fc.args)elif fc.name == "list_categories":result = list_categories()elif fc.name == "add_to_checkout":result = add_to_checkout(context_id, **fc.args)elif fc.name == "update_customer_email":result = update_customer_email(context_id, **fc.args)else:result = {"type": "error", "message": "Unknown function"}# Add function response to historysession["conversation_history"].append({"role": "model","parts": model_parts})session["conversation_history"].append({"role": "user","parts": [{"function_response": {"name": fc.name,"response": result}}]})# Store results for final responseif result["type"] == "product_results":response_parts.append({"type": "data","data": {"a2a.product_results": {"content": result.get("content", ""),"results": result.get("results", [])}}})elif result["type"] == "checkout":response_parts.append({"type": "data","data": {"a2a.ucp.checkout": result["checkout"]}})# If no function calls, we're doneif not has_function_call:# Add final model response to historysession["conversation_history"].append({"role": "model","parts": model_parts})# Extract text for responsefor part in model_parts:if "text" in part:response_parts.insert(0, {"type": "text", "text": part["text"]})breakreturn {"jsonrpc": "2.0","id": request_id,"result": {"contextId": context_id,"parts": response_parts}}@app.route("/api", methods=["POST"])def handle_a2a_message():"""Handle A2A messages - parse request and delegate to agent processor"""try:data = request.jsonmethod = data.get("method")if method != "message/send":return jsonify({"error": "Only message/send supported"}), 400params = data.get("params", {})message = params.get("message", {})parts = message.get("parts", [])# Extract session IDcontext_id = message.get("contextId", str(uuid.uuid4()))# Extract text and action datauser_text = ""action_data = {}for part in parts:if part.get("type") == "text":user_text = part.get("text", "")elif part.get("type") == "data":action_data.update(part.get("data", {}))logging.info(f"[A2A] User: {user_text[:60]}...")# Process request and get responseresponse = process_agent_request(context_id, user_text, action_data, data.get("id"))return jsonify(response)except Exception as e:logging.exception("Error handling A2A message")return jsonify({"jsonrpc": "2.0","id": data.get("id"),"error": {"code": -32603,"message": str(e)}}), 500@app.route("/.well-known/ucp")def ucp_discovery():"""UCP discovery endpoint"""return jsonify({"ucp": {"version": "2026-01-11","services": {"com.simpledemo.shopping": {"version": "2026-01-11","spec": "http://localhost:5001/docs","a2a": {"endpoint": "http://localhost:5001/api"}}},"capabilities": [{"name": "dev.ucp.shopping.checkout","version": "2026-01-11","spec": "https://ucp.dev/specification/checkout","schema": "https://ucp.dev/schemas/shopping/checkout.json"}]},"payment": {"handlers": [h.model_dump(mode="json", by_alias=True) for h in PAYMENT_HANDLERS]}})# ============================================================================# Run the server# ============================================================================@weave.opdef main():print("\n" + "="*60)print("📚 UCP Ebook Store Agent Starting...")print("="*60)print("\n📍 Store Agent API: http://localhost:5001")print("📍 UCP Discovery: http://localhost:5001/.well-known/ucp")print("\n📖 Available Ebooks:")for p in PRODUCTS:print(f" - {p['title']} (${p['price']/100:.2f})")print("\nThis is a MERCHANT'S agent-based ebook server")print("Run client_chat.py to interact with this agent")print("\n" + "="*60 + "\n")app.run(debug=True, port=5001)if __name__ == "__main__":main()
The agent layer sits behind an A2A-style message endpoint. The client sends messages such as “show me business books” or “add this to my cart,” and the agent determines which function to call. Those functions return structured data, including UCP checkout objects, which are then sent back to the client as authoritative state. The agent does not bypass UCP. It uses UCP schemas as the output format for all commerce actions.
The key idea to keep in mind is that this backend is not pretending to be a human using a website. It exposes commerce directly as data and state transitions. The agent helps map user intent into those transitions, but the protocol defines the contract. This is what enables a chat-based client, or any other surface, to process real purchases without scraping pages or guessing how checkout works.
Client responsibilities
The client in this architecture is intentionally "thin." It doesn't know how to tax an item, what a product costs, or how to process a credit card. Its responsibilities are strictly discovery, transport, and security.
- Discovery: On startup, it checks /.well-known/ucp to confirm the server supports the "checkout" capability. If the store uses a different version or lacks this capability, the client stops. It never guesses.
- Transport & rendering: It forwards user intent to the agent and renders the returned UCP state (e.g., a Checkout object). It acts as a mirror of the server's state.
- Security: The client owns the user's payment methods. It uses the merchant's advertised handlers to create a payment token, but the raw credentials never touch the merchant's logic until the final handshake.
Here’s the code for the client:
"""UCP Chat Client - Simple Flask + HTMLRuns on port 5000 - Connects to store agent on port 5001"""from flask import Flask, render_template_string, jsonify, requestfrom flask_cors import CORSimport requestsimport uuidapp = Flask(__name__)CORS(app)STORE_AGENT_URL = "http://localhost:5001/api"# Mock payment methods (simulating user's wallet)MOCK_PAYMENT_METHODS = [{"id": "pm_visa_4242","type": "card","brand": "visa","last_digits": "4242","expiry_month": 12,"expiry_year": 2028},{"id": "pm_mastercard_5555","type": "card","brand": "mastercard","last_digits": "5555","expiry_month": 6,"expiry_year": 2027}]HTML_TEMPLATE = """<!DOCTYPE html><html><head><title>UCP Shopping Chat</title><style>* {margin: 0;padding: 0;box-sizing: border-box;}body {font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;background: #f5f5f5;}.container {max-width: 800px;margin: 0 auto;height: 100vh;display: flex;flex-direction: column;background: white;}.header {background: #2563eb;color: white;padding: 20px;text-align: center;}.chat-messages {flex: 1;overflow-y: auto;padding: 20px;}.message {margin-bottom: 20px;display: flex;flex-direction: column;}.message.user {align-items: flex-end;}.message.agent {align-items: flex-start;}.message-bubble {max-width: 70%;padding: 12px 16px;border-radius: 16px;margin: 4px 0;}.user .message-bubble {background: #2563eb;color: white;}.agent .message-bubble {background: #e5e7eb;color: #111827;}.products-container {display: flex;gap: 12px;overflow-x: auto;padding: 12px 0;max-width: 100%;}.product-card {min-width: 200px;border: 1px solid #e5e7eb;border-radius: 8px;padding: 12px;background: white;}.product-card img {width: 100%;height: 120px;object-fit: cover;border-radius: 4px;margin-bottom: 8px;}.product-title {font-weight: 600;margin-bottom: 4px;}.product-price {color: #059669;font-weight: 600;margin-bottom: 8px;}.product-card button {width: 100%;padding: 8px;background: #2563eb;color: white;border: none;border-radius: 4px;cursor: pointer;}.product-card button:hover {background: #1d4ed8;}.checkout-card {border: 1px solid #e5e7eb;border-radius: 8px;padding: 16px;background: white;margin: 12px 0;max-width: 400px;}.checkout-header {font-weight: 700;font-size: 16px;margin-bottom: 12px;padding-bottom: 8px;border-bottom: 1px solid #e5e7eb;}.checkout-item {display: flex;justify-content: space-between;margin: 8px 0;font-size: 14px;}.checkout-total {display: flex;justify-content: space-between;font-weight: 700;margin-top: 12px;padding-top: 8px;border-top: 1px solid #e5e7eb;}.checkout-id {font-size: 11px;color: #6b7280;margin-top: 8px;}.checkout-card button {width: 100%;padding: 12px;margin-top: 12px;background: #059669;color: white;border: none;border-radius: 4px;cursor: pointer;font-weight: 600;}.checkout-card button:hover {background: #047857;}.payment-methods {margin: 12px 0;}.payment-method {border: 1px solid #e5e7eb;border-radius: 4px;padding: 12px;margin: 8px 0;cursor: pointer;display: flex;justify-content: space-between;align-items: center;}.payment-method:hover {border-color: #2563eb;background: #eff6ff;}.payment-method.selected {border-color: #2563eb;background: #eff6ff;}.chat-input {padding: 20px;border-top: 1px solid #e5e7eb;display: flex;gap: 12px;}.chat-input input {flex: 1;padding: 12px;border: 1px solid #e5e7eb;border-radius: 8px;font-size: 14px;}.chat-input button {padding: 12px 24px;background: #2563eb;color: white;border: none;border-radius: 8px;cursor: pointer;font-weight: 600;}.chat-input button:hover {background: #1d4ed8;}.chat-input button:disabled {background: #9ca3af;cursor: not-allowed;}.loading {color: #6b7280;font-style: italic;}</style></head><body><div class="container"><div class="header"><h1>📚 UCP Ebook Store</h1><p>Chat with our AI ebook assistant</p></div><div class="chat-messages" id="messages"><div class="message agent"><div class="message-bubble">🔍 Verifying store capabilities...</div></div></div><div class="chat-input"><input type="text" id="userInput" placeholder="Type your message..." /><button id="sendBtn" onclick="sendMessage()">Send</button></div></div><script>let contextId = null;let selectedPaymentMethod = null;let currentCheckout = null;let ucpProfile = null;let isStoreReady = false;// Verify UCP capabilities on page loadasync function verifyUcpCapabilities() {try {const response = await fetch('/api/ucp-discovery');const profile = await response.json();if (profile.error) {showError('❌ Store not available: ' + profile.error);return false;}ucpProfile = profile;// Check UCP versionif (!profile.ucp || profile.ucp.version !== '2026-01-11') {showError('❌ Store uses unsupported UCP version');return false;}// Check for required capability: dev.ucp.shopping.checkoutconst hasCheckout = profile.ucp.capabilities?.some(cap =>cap.name === 'dev.ucp.shopping.checkout');if (!hasCheckout) {showError('❌ Store does not support UCP checkout');return false;}// Check payment handlersif (!profile.payment || !profile.payment.handlers || profile.payment.handlers.length === 0) {showError('❌ Store has no payment handlers configured');return false;}// All checks passed!console.log('✅ UCP Discovery validated:', profile);console.log('✅ Supported capabilities:', profile.ucp.capabilities.map(c => c.name));console.log('✅ Payment handlers:', profile.payment.handlers.map(h => h.name));isStoreReady = true;return true;} catch (error) {showError('❌ Failed to verify store capabilities: ' + error.message);return false;}}function showError(message) {const messagesDiv = document.getElementById('messages');messagesDiv.innerHTML = `<div class="message agent"><div class="message-bubble" style="background: #fee2e2; color: #991b1b;"><strong>${message}</strong><br><br>Please make sure the store server is running on port 5001.</div></div>`;document.getElementById('userInput').disabled = true;document.getElementById('sendBtn').disabled = true;}// Run verification on page loadwindow.addEventListener('DOMContentLoaded', async () => {const verified = await verifyUcpCapabilities();if (verified) {addMessage('agent', `<div class="message-bubble">✅ Connected to UCP Ebook Store<br><small style="color: #6b7280;">UCP Version: ${ucpProfile.ucp.version}</small><br><small style="color: #6b7280;">Capabilities: ${ucpProfile.ucp.capabilities.map(c => c.name.split('.').pop()).join(', ')}</small><br><br>Hello! I can help you browse ebooks and complete your purchase. Try asking:<br>• "What books do you have?"<br>• "Show me business books"<br>• "What categories are available?"<br><br>When you're ready to checkout, I'll just need your email address!</div>`);}});// Allow Enter key to senddocument.getElementById('userInput').addEventListener('keypress', function(e) {if (e.key === 'Enter') sendMessage();});function addMessage(type, content) {const messagesDiv = document.getElementById('messages');const messageDiv = document.createElement('div');messageDiv.className = `message ${type}`;if (typeof content === 'string') {messageDiv.innerHTML = `<div class="message-bubble">${content}</div>`;} else {messageDiv.appendChild(content);}messagesDiv.appendChild(messageDiv);messagesDiv.scrollTop = messagesDiv.scrollHeight;}function formatCurrency(cents) {return `$${(cents / 100).toFixed(2)}`;}function renderProducts(products) {const container = document.createElement('div');container.className = 'products-container';products.forEach(product => {const card = document.createElement('div');card.className = 'product-card';card.innerHTML = `<img src="${product.image_url}" alt="${product.title}" /><div class="product-title">${product.title}</div><div class="product-price">${formatCurrency(product.price)}</div><button onclick="addToCart('${product.id}')">Add to Cart</button>`;container.appendChild(card);});return container;}function renderCheckout(checkout) {currentCheckout = checkout;const card = document.createElement('div');card.className = 'checkout-card';let html = `<div class="checkout-header">${checkout.status === 'completed' ? '✅ Order Confirmed' : '🛒 Checkout Summary'}</div>`;// Line itemscheckout.line_items.forEach(item => {html += `<div class="checkout-item"><span>${item.quantity}x ${item.item.title}</span><span>${formatCurrency(item.totals[item.totals.length - 1].amount)}</span></div>`;});// Totalscheckout.totals.forEach(total => {if (total.type === 'total') {html += `<div class="checkout-total"><span>${total.display_text || 'Total'}</span><span>${formatCurrency(total.amount)}</span></div>`;} else {html += `<div class="checkout-item"><span>${total.display_text || total.type}</span><span>${formatCurrency(total.amount)}</span></div>`;}});html += `<div class="checkout-id">Checkout ID: ${checkout.id}</div>`;// Buttonsif (checkout.status === 'incomplete') {html += `<button onclick="startPayment()">Proceed to Payment</button>`;} else if (checkout.status === 'ready_for_complete') {html += `<button onclick="showPaymentMethods()">Complete Payment</button>`;} else if (checkout.status === 'completed' && checkout.order) {html += `<div style="margin-top: 12px; font-weight: 600;">Order ID: ${checkout.order.id}</div><a href="${checkout.order.permalink_url}" target="_blank" style="display: block; margin-top: 8px; color: #2563eb;">View Order Details</a>`;}card.innerHTML = html;return card;}function showPaymentMethods() {fetch('/api/payment-methods').then(res => res.json()).then(methods => {const container = document.createElement('div');container.className = 'payment-methods';let html = '<div style="font-weight: 600; margin-bottom: 8px;">Select Payment Method:</div>';methods.forEach(method => {html += `<div class="payment-method" onclick="selectPayment('${method.id}')"><div><div style="font-weight: 600;">${method.brand.toUpperCase()} •••• ${method.last_digits}</div><div style="font-size: 12px; color: #6b7280;">Expires ${method.expiry_month}/${method.expiry_year}</div></div></div>`;});html += '<button onclick="confirmPayment()" style="width: 100%; padding: 12px; margin-top: 12px; background: #059669; color: white; border: none; border-radius: 4px; cursor: pointer; font-weight: 600;">Confirm Purchase</button>';container.innerHTML = html;addMessage('agent', container);});}function selectPayment(methodId) {selectedPaymentMethod = methodId;document.querySelectorAll('.payment-method').forEach(el => {el.classList.remove('selected');});event.target.closest('.payment-method').classList.add('selected');}function confirmPayment() {if (!isStoreReady) {alert('Store is not ready. Please refresh the page.');return;}if (!selectedPaymentMethod) {alert('Please select a payment method');return;}// Verify payment handler compatibilityconst paymentHandler = ucpProfile.payment.handlers.find(h => h.id === 'mock_card_handler');if (!paymentHandler) {alert('Payment handler not supported by this store');return;}console.log('✅ Payment handler verified:', paymentHandler.name);addMessage('user', '<div class="message-bubble">Confirming payment...</div>');fetch('/api/get-payment-token', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({payment_method_id: selectedPaymentMethod})}).then(res => res.json()).then(paymentInstrument => {console.log('✅ Payment instrument created:', paymentInstrument);return sendToAgent(null, {'action': 'complete_checkout','a2a.ucp.checkout.payment_data': paymentInstrument});});}function addToCart(productId) {addMessage('user', '<div class="message-bubble">Adding to cart...</div>');sendMessage(`add ${productId} to cart`);}function startPayment() {addMessage('user', '<div class="message-bubble">I want to proceed to checkout</div>');sendMessage('I want to proceed to checkout');}async function sendToAgent(text, data) {const parts = [];if (text) {parts.push({type: 'text', text: text});}if (data) {parts.push({type: 'data', data: data});}const payload = {jsonrpc: '2.0',id: crypto.randomUUID(),method: 'message/send',params: {message: {role: 'user',parts: parts,messageId: crypto.randomUUID(),kind: 'message',contextId: contextId},configuration: {historyLength: 0}}};try {const response = await fetch('/api/send', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify(payload)});const result = await response.json();if (result.result) {contextId = result.result.contextId;const parts = result.result.parts || [];parts.forEach(part => {if (part.type === 'text' && part.text) {addMessage('agent', `<div class="message-bubble">${part.text}</div>`);}if (part.type === 'data') {if (part.data['a2a.product_results']) {const results = part.data['a2a.product_results'];if (results.results && results.results.length > 0) {addMessage('agent', renderProducts(results.results));}}if (part.data['a2a.ucp.checkout']) {addMessage('agent', renderCheckout(part.data['a2a.ucp.checkout']));}}});} else if (result.error) {addMessage('agent', `<div class="message-bubble">Error: ${result.error.message}</div>`);}} catch (error) {addMessage('agent', `<div class="message-bubble">Error: ${error.message}</div>`);}}function sendMessage(customText) {const input = document.getElementById('userInput');const text = customText || input.value.trim();if (!text) return;if (!customText) {addMessage('user', `<div class="message-bubble">${text}</div>`);input.value = '';}sendToAgent(text, null);}</script></body></html>"""@app.route("/")def index():"""Serve the chat UI"""return render_template_string(HTML_TEMPLATE)@app.route("/api/send", methods=["POST"])def proxy_to_agent():"""Proxy A2A messages to store agent"""try:data = request.jsonresponse = requests.post(STORE_AGENT_URL,json=data,headers={"Content-Type": "application/json"})return jsonify(response.json())except Exception as e:return jsonify({"error": str(e)}), 500@app.route("/api/payment-methods")def get_payment_methods():"""Get mock payment methods"""return jsonify(MOCK_PAYMENT_METHODS)@app.route("/api/ucp-discovery")def get_ucp_discovery():"""Fetch UCP discovery from store agent"""try:response = requests.get(f"{STORE_AGENT_URL.replace('/api', '')}/.well-known/ucp")return jsonify(response.json())except Exception as e:return jsonify({"error": str(e)}), 500@app.route("/api/get-payment-token", methods=["POST"])def get_payment_token():"""Get payment token for selected method"""data = request.jsonmethod_id = data.get("payment_method_id")method = next((m for m in MOCK_PAYMENT_METHODS if m["id"] == method_id), None)if not method:return jsonify({"error": "Payment method not found"}), 404# Create payment instrument with mock tokenpayment_instrument = {**method,"handler_id": "mock_card_handler","credential": {"type": "token","token": f"tok_mock_{uuid.uuid4().hex[:12]}"}}return jsonify(payment_instrument)if __name__ == "__main__":print("\n" + "="*60)print("📚 UCP Ebook Client Starting...")print("="*60)print("\n📍 Client: http://localhost:5000")print("📍 Connects to Ebook Store Agent: http://localhost:5001")print("\n✨ Features:")print(" - Browse ebooks by Ray Dalio, Peter Thiel, James Clear")print(" - Add to cart and checkout")print(" - Instant delivery to your email (no shipping!)")print("\nOpen http://localhost:5000 in your browser!")print("\n" + "="*60 + "\n")app.run(debug=True, port=5000)
Testing the UCP Agent and chat client end-to-end
Once both the store agent and the chat client are running, testing focuses on observability as much as behavior. The goal is to see every meaningful action the agent takes, inspect the data flowing through it, and confirm that the commerce state evolves exactly as expected. This is where Weave comes in.
We initialize Weave at the start of the store server. From that point on, every decorated function and every model call becomes a first-class traceable unit. Each user interaction produces a trace made up of calls, and each call records inputs, outputs, timing, and errors. This gives us a concrete execution record instead of relying on logs or UI behavior.

The first thing we test is discovery and readiness. When the client loads, it fetches the store’s /.well-known/ucp endpoint. That happens outside the agent, but once the user starts interacting, everything funnels through the agent entry point. The process_agent_request function is wrapped with @weave.op, so each incoming message creates a top-level call in Weave. That call becomes the root of the trace for the entire turn.
Next, we test browsing. When the user asks, “What categories of books does this store have?”, the agent calls list_categories. That function is also wrapped with @weave.op. In the Weave trace view, this shows up as a child call under the main request. We can inspect the exact inputs, see the returned category data, and confirm that no extra logic was injected between the request and the response.
We repeat this with product search. Asking “What business books?” results in a search_products call with query = "business". In the trace, we see the query string, the execution time, and the full product list returned by the catalog. The screenshots clearly show this: the function call, followed by a structured result containing product IDs, prices, and metadata. This confirms that the agent is sourcing results from the catalog and not synthesizing them.

From there, we move into checkout creation. When the user says “I want to buy Principles,” the agent calls add_to_checkout. This call creates or updates a checkout object and returns it. In Weave, this appears as another child call, and we can inspect the checkout payload in full: line items, totals, currency, status, and checkout ID. Because the checkout object is returned as data, the client renders it, keeping UI behavior aligned with server state.
We then test the required information handling. When the user attempts to proceed without an email address, the agent prompts for one. Once the email is provided, update_customer_email is called. In the trace, we see the email value passed in and the updated checkout returned with status set to ready for completion. This makes state transitions visible and auditable.
The final test is payment and completion. On the client, the user selects a payment method. The client constructs a payment instrument that matches the handler advertised during discovery and sends a single action message to the agent. In the trace view, this shows up as a process_agent_request call with action_data containing complete_checkout and the full payment payload: handler ID, brand, token credential, and expiration details.

The agent handles this by calling complete_checkout, which is also traced. We can see the payment data coming in, the checkout being validated, and the final checkout object being returned with status set to completed and an attached order confirmation. The screenshots clearly show this: the input payload on the left and the completed checkout on the right.

Because Weave records inputs and outputs for every call, we get a complete, hierarchical view of the interaction. Traces capture the entire purchase lifecycle: user message, agent decision, catalog lookup, checkout mutation, payment completion, and order creation. If something goes wrong, the failure is localized to a specific call with concrete data attached.

This logging approach gives us confidence that the agent is behaving correctly at the protocol level. Each action is explicit, inspectable, and repeatable. Instead of testing by clicking around and hoping nothing breaks, we test by reading traces and verifying that state changes match the UCP model exactly.
Conclusion
UCP exists because software needs clearer interfaces with the real world. As agents take on tasks such as shopping, booking, and account management, the limiting factor shifts from reasoning to coordination. Every merchant system today encodes its own assumptions about flow, state, and completion, and those assumptions are rarely documented in a way that software can safely rely on.
What UCP introduces is a shared language for commerce. Merchants expose their capabilities in a machine-readable way. Agents determine which actions are allowed, the current state, and the possible outcomes before taking any action. Checkout becomes a sequence of explicit state transitions instead of a fragile series of guesses. Orders become durable objects instead of side effects hidden behind redirects and forms. Payments become structured handoffs instead of opaque button clicks.
This matters because autonomy depends on predictability. An agent can act responsibly only if the system in which it operates has clear rules and boundaries. UCP enables merchants to publish those boundaries and agents to respect them. Control stays with the merchant. Credentials stay with the user. The agent coordinates the interaction using a protocol both sides understand.
As agent-driven software becomes more common, protocols like UCP become mandatory. They are the difference between brittle automation and systems that can be reasoned about, tested, and trusted. UCP does not try to make agents cleverer. It makes commerce readable, which turns out to be the harder and more important problem.
Add a comment