Skip to content
agent engineering

Topic

Universal Commerce Protocol (UCP)

An open protocol that enables interoperability between AI agents, businesses, and payment providers. UCP provides unified APIs for the entire shopping lifecycle—from product discovery through post-purchase support.

What is UCP?

The Universal Commerce Protocol solves fragmented commerce experiences by providing a common language and functional primitives for consumer surfaces, businesses, and payment providers, in the words of the UCP project. Instead of building custom integrations for each retailer, agents use UCP's standardized APIs to handle shopping across any participating merchant.

Checkout

Checkout sessions with cart management and tax calculation

Identity Linking

OAuth-based account connection without sharing credentials

Order Management

Real-time webhooks for status updates, tracking, and support

Industry Backing
Google developed UCP with Shopify, Etsy, Wayfair, Target, and Walmart, and over 20 partners endorsed it at launch, including Stripe, Visa, Mastercard, and American Express (Google Developers Blog, January 2026). Businesses remain the Merchant of Record.

Architecture

UCP Commerce Flow
UCP APIUCP APIUCP APIAI agentfind me running shoes under $150and order the best matchShopify merchantcatalog · checkout · identity ·ordersTarget merchantcatalog · checkout · identity ·ordersWayfair merchantcatalog · checkout · identity ·ordersPayment provider (Stripe, etc.)Agent Payments Protocol (AP2)
One agent request fans out to merchants over the UCP API; payments settle through an agent-payments provider.

Protocol Stack

Layer Protocol Purpose
Commerce UCP Checkout, orders, identity, catalog
Payments AP2 (Agent Payments Protocol) Secure agent-initiated payments
Agent Communication A2A Agent-to-agent task delegation
Tool Access MCP Agent-to-tool integration
Transport REST / JSON-RPC HTTPS-based communication

Checkout API

UCP's checkout capability creates and manages checkout sessions, including cart management and tax calculation. The samples and endpoints below follow the REST binding in the UCP specification. The platform finds the business's endpoint in its profile at /.well-known/ucp, names its own profile in a UCP-Agent header, and lets the buyer review the checkout in a trusted UI before the order is placed:

UCP Checkout Flow
# UCP checkout over the REST binding
# (operations and fields per ucp.dev/latest/specification/shopping/checkout/rest/)

# 1. Discover the business: its profile lists services, capabilities, keys
profile  = GET https://shop.example/.well-known/ucp
endpoint = profile.ucp.services["dev.ucp.shopping"]
               .find(s => s.transport == "rest").endpoint

# Every request names the platform's own profile
headers = {
    "UCP-Agent":       'profile="https://agent.example/.well-known/ucp"',
    "Request-Id":      uuid(),
    "Idempotency-Key": uuid()     # fresh key whenever the body changes
}

# 2. Find a product (catalog search; prices in minor units)
results = POST {endpoint}/catalog/search {
    query:   "running shoes",
    filters: { price: { max: 15000 } },
    context: { address_country: "US" }
}
variant = results.products[0].variants[0]

# 3. Create a checkout session
checkout = POST {endpoint}/checkout-sessions {
    line_items: [ { item: { id: variant.id }, quantity: 1 } ]
}
# -> 201, status "incomplete"; messages say what is missing:
#    { code: "missing", path: "$.buyer.email", severity: "recoverable" }

# 4. Update is a full replacement: resend everything to keep
checkout = PUT {endpoint}/checkout-sessions/{checkout.id} {
    line_items:  checkout.line_items,      # with their ids
    buyer:       { email: ..., first_name: ..., last_name: ... },
    fulfillment: { methods: [ { type: "shipping",
                                destinations: [ user.address ] } ] }
}
# Totals are typed amounts in minor units:
# [ {type: "subtotal", amount: 12000}, {type: "tax", amount: 990},
#   {type: "total", amount: 12990} ]

# 5. The status decides the next step
switch checkout.status:
    "incomplete":          resolve checkout.messages, update again
    "requires_escalation": hand the buyer to checkout.continue_url
    "ready_for_complete":  show a trusted review UI; the buyer confirms

# 6. Complete with an instrument from checkout.ucp.payment_handlers
checkout = POST {endpoint}/checkout-sessions/{checkout.id}/complete {
    payment: { instruments: [ instrument ] },
    signals: { "dev.ucp.buyer_ip": client_ip }
}
# "completed"            -> checkout.order.id, checkout.order.permalink_url
# "complete_in_progress" -> GET the session with backoff until it settles
# Order updates then arrive by webhook (see Order Management)
import uuid
import httpx

# Operations, headers and fields per the UCP REST binding:
# https://ucp.dev/latest/specification/shopping/checkout/rest/
PLATFORM_PROFILE = "https://agent.example/.well-known/ucp"

class UCPCheckoutClient:
    def __init__(self, endpoint: str, access_token: str | None = None):
        self.endpoint = endpoint.rstrip("/")
        self.access_token = access_token  # only for user-authenticated calls
        self.http = httpx.AsyncClient()

    @classmethod
    async def discover(cls, business: str, **kwargs) -> "UCPCheckoutClient":
        """Read the REST endpoint from the business's UCP profile."""
        async with httpx.AsyncClient() as http:
            r = await http.get(f"https://{business}/.well-known/ucp")
            r.raise_for_status()
        services = r.json()["ucp"]["services"]["dev.ucp.shopping"]
        rest = next(s for s in services if s["transport"] == "rest")
        return cls(rest["endpoint"], **kwargs)

    async def _send(self, method: str, path: str, body: dict | None = None) -> dict:
        headers = {
            "UCP-Agent": f'profile="{PLATFORM_PROFILE}"',
            "Request-Id": str(uuid.uuid4()),
            "Idempotency-Key": str(uuid.uuid4()),  # reuse only to retry the same body
        }
        if self.access_token:
            headers["Authorization"] = f"Bearer {self.access_token}"
        r = await self.http.request(method, self.endpoint + path, json=body, headers=headers)
        r.raise_for_status()                      # protocol errors (4xx/5xx)
        data = r.json()
        if data["ucp"].get("status") == "error":  # business outcome, sent as HTTP 200
            raise RuntimeError(data["messages"])
        return data

    async def create_checkout(self, line_items: list[dict]) -> dict:
        return await self._send("POST", "/checkout-sessions", {"line_items": line_items})

    async def update_checkout(self, checkout_id: str, checkout: dict) -> dict:
        """Full replacement: send every field the session should keep."""
        return await self._send("PUT", f"/checkout-sessions/{checkout_id}", checkout)

    async def complete_checkout(self, checkout_id: str, payment: dict, signals: dict) -> dict:
        return await self._send("POST", f"/checkout-sessions/{checkout_id}/complete",
                                {"payment": payment, "signals": signals})

    async def cancel_checkout(self, checkout_id: str) -> dict:
        return await self._send("POST", f"/checkout-sessions/{checkout_id}/cancel", {})

async def prepare_purchase(ucp: UCPCheckoutClient, variant_id: str, buyer: dict, address: dict) -> dict:
    checkout = await ucp.create_checkout([{"item": {"id": variant_id}, "quantity": 1}])
    checkout = await ucp.update_checkout(checkout["id"], {
        "line_items": [
            {"id": li["id"], "item": {"id": li["item"]["id"]}, "quantity": li["quantity"]}
            for li in checkout["line_items"]
        ],
        "buyer": buyer,  # email, first_name, last_name
        "fulfillment": {"methods": [{"type": "shipping", "destinations": [address]}]},
    })
    total = next(t["amount"] for t in checkout["totals"] if t["type"] == "total")
    print(f"Total: {total / 100:.2f} {checkout['currency']}")  # minor units

    match checkout["status"]:
        case "ready_for_complete":
            return checkout  # show in a trusted review UI; the buyer places the order
        case "requires_escalation":
            return {"handoff_url": checkout["continue_url"]}
        case _:  # "incomplete", e.g. no fulfillment option selected yet
            raise ValueError([m["content"] for m in checkout.get("messages", [])])

async def place_order(ucp: UCPCheckoutClient, checkout_id: str, instrument: dict, buyer_ip: str) -> dict:
    """Called from the review UI once the buyer confirms."""
    checkout = await ucp.complete_checkout(
        checkout_id,
        payment={"instruments": [instrument]},  # built per checkout["ucp"]["payment_handlers"]
        signals={"dev.ucp.buyer_ip": buyer_ip},
    )
    if checkout["status"] == "completed":
        return checkout["order"]  # id, permalink_url
    return checkout  # "complete_in_progress": GET the session with backoff
using System.Net.Http.Json;
using System.Text.Json.Nodes;

// Operations, headers and fields per the UCP REST binding:
// https://ucp.dev/latest/specification/shopping/checkout/rest/
public sealed class UcpCheckoutClient(HttpClient http, string endpoint, string platformProfile)
{
    public string? AccessToken { get; set; }  // only for user-authenticated calls

    public static async Task<string> DiscoverRestEndpointAsync(HttpClient http, string business)
    {
        var profile = await http.GetFromJsonAsync<JsonObject>($"https://{business}/.well-known/ucp")
            ?? throw new InvalidOperationException("No UCP profile");
        return profile["ucp"]!["services"]!["dev.ucp.shopping"]!.AsArray()
            .First(s => (string?)s!["transport"] == "rest")!["endpoint"]!.GetValue<string>();
    }

    public Task<JsonObject> CreateCheckoutAsync(JsonArray lineItems) =>
        SendAsync(HttpMethod.Post, "/checkout-sessions", new JsonObject { ["line_items"] = lineItems });

    // Full replacement: send every field the session should keep
    public Task<JsonObject> UpdateCheckoutAsync(string id, JsonObject checkout) =>
        SendAsync(HttpMethod.Put, $"/checkout-sessions/{id}", checkout);

    public Task<JsonObject> CompleteCheckoutAsync(string id, JsonObject payment, JsonObject signals) =>
        SendAsync(HttpMethod.Post, $"/checkout-sessions/{id}/complete",
            new JsonObject { ["payment"] = payment, ["signals"] = signals });

    public Task<JsonObject> CancelCheckoutAsync(string id) =>
        SendAsync(HttpMethod.Post, $"/checkout-sessions/{id}/cancel", new JsonObject());

    private async Task<JsonObject> SendAsync(HttpMethod method, string path, JsonObject? body = null)
    {
        using var request = new HttpRequestMessage(method, endpoint.TrimEnd('/') + path);
        request.Headers.Add("UCP-Agent", $"profile=\"{platformProfile}\"");
        request.Headers.Add("Request-Id", Guid.NewGuid().ToString());
        request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString()); // reuse only to retry the same body
        if (AccessToken is not null) request.Headers.Authorization = new("Bearer", AccessToken);
        if (body is not null) request.Content = JsonContent.Create(body);

        using var response = await http.SendAsync(request);
        response.EnsureSuccessStatusCode();                 // protocol errors
        var result = await response.Content.ReadFromJsonAsync<JsonObject>()
            ?? throw new InvalidOperationException("Empty response");
        if ((string?)result["ucp"]?["status"] == "error")  // business outcome, HTTP 200
            throw new InvalidOperationException(result["messages"]?.ToJsonString());
        return result;
    }
}

// Usage
var http = new HttpClient();
var endpoint = await UcpCheckoutClient.DiscoverRestEndpointAsync(http, "shop.example");
var ucp = new UcpCheckoutClient(http, endpoint, "https://agent.example/.well-known/ucp");

var checkout = await ucp.CreateCheckoutAsync(new JsonArray(
    new JsonObject { ["item"] = new JsonObject { ["id"] = variantId }, ["quantity"] = 1 }));
var id = checkout["id"]!.GetValue<string>();

checkout = await ucp.UpdateCheckoutAsync(id, new JsonObject
{
    ["line_items"] = new JsonArray(checkout["line_items"]!.AsArray().Select(li => (JsonNode)new JsonObject
    {
        ["id"] = li!["id"]!.GetValue<string>(),
        ["item"] = new JsonObject { ["id"] = li["item"]!["id"]!.GetValue<string>() },
        ["quantity"] = li["quantity"]!.GetValue<int>()
    }).ToArray()),
    ["buyer"] = new JsonObject { ["email"] = "jane@example.com", ["first_name"] = "Jane", ["last_name"] = "Doe" },
    ["fulfillment"] = new JsonObject
    {
        ["methods"] = new JsonArray(new JsonObject
        {
            ["type"] = "shipping",
            ["destinations"] = new JsonArray(shippingAddress)  // street_address, postal_code, address_country, ...
        })
    }
});

var total = checkout["totals"]!.AsArray().First(t => (string?)t!["type"] == "total")!["amount"]!.GetValue<long>();
Console.WriteLine($"Total: {total / 100m:0.00} {checkout["currency"]}");  // minor units

switch ((string?)checkout["status"])
{
    case "ready_for_complete":
        // Show a trusted review UI; once the buyer confirms:
        var done = await ucp.CompleteCheckoutAsync(id, payment,
            new JsonObject { ["dev.ucp.buyer_ip"] = buyerIp });
        if ((string?)done["status"] == "completed")
            Console.WriteLine($"Order {done["order"]!["id"]}: {done["order"]!["permalink_url"]}");
        break;
    case "requires_escalation":
        Console.WriteLine($"Finish at {checkout["continue_url"]}");
        break;
    default:  // "incomplete": checkout["messages"] say what is missing
        break;
}

Checkout Endpoints

Dynamic Pricing
Checkout session responses carry the business's line items and totals, and discounts are handled by an optional discount extension (UCP specification).

Identity Linking

UCP's identity linking uses the OAuth 2.0 Authorization Code flow with PKCE to link user accounts without sharing credentials. Users authorize agents to access their merchant accounts:

Identity Linking Flow
# UCP identity linking: OAuth 2.0 Authorization Code flow with PKCE
# (ucp.dev/latest/specification/common/identity-linking/)

# 1. Which scopes does the business gate? Read its UCP profile
profile = GET https://shop.example/.well-known/ucp
gated   = profile.ucp.capabilities["dev.ucp.common.identity_linking"][0]
              .config.scopes
# e.g. { "dev.ucp.shopping.order:read": {}, "dev.ucp.shopping.order:manage": {} }
scopes  = ["dev.ucp.shopping.order:read"]   # only what the agent will call

# 2. Find the authorization server
issuer   = GET https://shop.example/.well-known/oauth-protected-resource
               .authorization_servers[0]    # default: the business domain
metadata = GET {issuer}/.well-known/oauth-authorization-server
assert metadata.issuer == issuer            # byte-for-byte

# 3. Send the user to the business's own consent screen
verifier = random(); state = random()
redirect(metadata.authorization_endpoint +
    "?response_type=code&client_id=agent-app" +
    "&redirect_uri=https://agent.example/callback" +
    "&scope=dev.ucp.shopping.order:read" +
    "&code_challenge=" + S256(verifier) + "&code_challenge_method=S256" +
    "&state=" + state)

# 4. Callback: https://agent.example/callback?code=...&state=...&iss=...
assert callback.state == state
assert callback.iss == metadata.issuer      # RFC 9207 mix-up defence

# 5. Exchange the code (client auth per token_endpoint_auth_methods_supported)
tokens = POST metadata.token_endpoint {
    grant_type: "authorization_code", code: callback.code,
    redirect_uri: "https://agent.example/callback", code_verifier: verifier
}
# -> access_token, token_type "Bearer", expires_in, refresh_token, scope

# 6. User-authenticated calls carry the token
order = GET {endpoint}/orders/{order_id}
    Authorization: Bearer {tokens.access_token}
    UCP-Agent: profile="https://agent.example/.well-known/ucp"
# 401 identity_required / 403 insufficient_scope -> link again with the
# scope named in the WWW-Authenticate challenge

# 7. When the user unlinks: revoke at metadata.revocation_endpoint (RFC 7009)
import base64
import hashlib
import secrets
import time
from dataclasses import dataclass
from urllib.parse import urlencode, urlsplit

import httpx

# Discovery, flow and scopes per the UCP identity linking spec:
# https://ucp.dev/latest/specification/common/identity-linking/

@dataclass
class LinkedIdentity:
    business: str
    access_token: str
    refresh_token: str | None
    scopes: list[str]
    expires_at: float

class UCPIdentityLinker:
    def __init__(self, client_id: str, client_secret: str, redirect_uri: str):
        self.client_id = client_id
        self.client_secret = client_secret  # confidential client (client_secret_basic)
        self.redirect_uri = redirect_uri
        self.http = httpx.AsyncClient()
        self.pending: dict[str, dict] = {}  # state -> flow data

    async def gated_scopes(self, business: str) -> dict:
        """Scopes the business gates behind user auth (its UCP profile)."""
        r = await self.http.get(f"https://{business}/.well-known/ucp")
        r.raise_for_status()
        linking = r.json()["ucp"]["capabilities"].get("dev.ucp.common.identity_linking", [])
        return linking[0].get("config", {}).get("scopes", {}) if linking else {}

    async def discover(self, business: str) -> dict:
        """RFC 9728 for the issuer, then RFC 8414 (OIDC discovery only on 404)."""
        issuer = f"https://{business}"
        r = await self.http.get(f"https://{business}/.well-known/oauth-protected-resource")
        if r.status_code == 200:
            issuer = r.json()["authorization_servers"][0]
        u = urlsplit(issuer)
        r = await self.http.get(f"{u.scheme}://{u.netloc}/.well-known/oauth-authorization-server{u.path}")
        if r.status_code == 404:
            r = await self.http.get(f"{issuer}/.well-known/openid-configuration")
        r.raise_for_status()
        metadata = r.json()
        if metadata["issuer"] != issuer:  # byte-for-byte, no normalising
            raise ValueError("Issuer mismatch")
        return metadata

    async def start(self, business: str, wanted: list[str]) -> str:
        """Return the authorization URL to send the user to."""
        gated = await self.gated_scopes(business)
        scopes = [s for s in wanted if s in gated]  # never a superset
        metadata = await self.discover(business)
        verifier = secrets.token_urlsafe(64)
        challenge = base64.urlsafe_b64encode(
            hashlib.sha256(verifier.encode()).digest()
        ).rstrip(b"=").decode()
        state = secrets.token_urlsafe(32)
        self.pending[state] = {"business": business, "verifier": verifier, "metadata": metadata}
        return metadata["authorization_endpoint"] + "?" + urlencode({
            "response_type": "code",
            "client_id": self.client_id,
            "redirect_uri": self.redirect_uri,
            "scope": " ".join(scopes),
            "code_challenge": challenge,
            "code_challenge_method": "S256",
            "state": state,
        })

    async def callback(self, code: str, state: str, iss: str) -> LinkedIdentity:
        flow = self.pending.pop(state, None)
        if flow is None:
            raise ValueError("Unknown state")  # CSRF
        metadata = flow["metadata"]
        if iss != metadata["issuer"]:
            raise ValueError("iss mismatch")  # RFC 9207 mix-up defence
        r = await self.http.post(metadata["token_endpoint"], auth=(self.client_id, self.client_secret), data={
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": self.redirect_uri,
            "code_verifier": flow["verifier"],
        })
        r.raise_for_status()
        return self._identity(flow["business"], r.json())

    async def refresh(self, identity: LinkedIdentity) -> LinkedIdentity:
        metadata = await self.discover(identity.business)
        r = await self.http.post(metadata["token_endpoint"], auth=(self.client_id, self.client_secret), data={
            "grant_type": "refresh_token",
            "refresh_token": identity.refresh_token,
        })
        r.raise_for_status()
        tokens = r.json()
        tokens.setdefault("refresh_token", identity.refresh_token)
        tokens.setdefault("scope", " ".join(identity.scopes))
        return self._identity(identity.business, tokens)

    async def unlink(self, identity: LinkedIdentity) -> None:
        """Revoking the refresh token also invalidates its access tokens (RFC 7009)."""
        metadata = await self.discover(identity.business)
        await self.http.post(metadata["revocation_endpoint"], auth=(self.client_id, self.client_secret), data={
            "token": identity.refresh_token,
            "token_type_hint": "refresh_token",
        })

    @staticmethod
    def _identity(business: str, tokens: dict) -> LinkedIdentity:
        return LinkedIdentity(
            business=business,
            access_token=tokens["access_token"],
            refresh_token=tokens.get("refresh_token"),
            scopes=tokens.get("scope", "").split(),
            expires_at=time.time() + tokens["expires_in"],
        )

# A user-authenticated call: Bearer token plus the usual UCP-Agent header
async def get_order(endpoint: str, order_id: str, identity: LinkedIdentity) -> dict:
    async with httpx.AsyncClient() as http:
        r = await http.get(f"{endpoint}/orders/{order_id}", headers={
            "Authorization": f"Bearer {identity.access_token}",
            "UCP-Agent": 'profile="https://agent.example/.well-known/ucp"',
        })
    if r.status_code in (401, 403):  # identity_required / insufficient_scope
        raise PermissionError(r.headers.get("WWW-Authenticate"))
    r.raise_for_status()
    return r.json()
OAuth Identity Linking
BusinessAgent platformUserBusinessAgent platformUserlink my store accountdiscover OAuth metadata (RFC 9728, RFC 8414)open authorization URL (PKCE S256, state, scopes)sign in and approve scopesredirect to callback with code and statetoken request (code + PKCE verifier)access and refresh tokensaccount linked
OAuth 2.0 authorization code flow with PKCE, as UCP's identity linking specifies: the user signs in with the business, and the platform never sees the credentials.
Scopes
Request minimal scopes needed. A business lists the scopes it gates behind user sign-in in the config.scopes of its identity-linking capability; the well-known ones are dev.ucp.shopping.order:read, dev.ucp.shopping.order:manage and dev.ucp.shopping.checkout:manage. A platform requests only the gated scopes for the operations it will call.

Order Management

UCP's order capability lets businesses push asynchronous updates about an order's lifecycle (shipping, delivery, returns) to a webhook URL the platform provides (UCP order specification). Each webhook carries the full current order rather than a delta, so the platform works out what changed by comparing fulfillment events and adjustments with the copy it already has:

Order Management with Webhooks
# UCP order webhooks (ucp.dev/latest/specification/shopping/order/)

# 1. No registration call: the platform's own UCP profile carries the URL,
#    and the business reads it during capability negotiation
#    "dev.ucp.shopping.order": [{ "version": "2026-08-25",
#        "config": { "webhook_url": "https://agent.example/webhooks/ucp/orders" } }]

# 2. Each webhook POSTs the FULL current order, not a delta
#    Headers: Webhook-Id, Webhook-Timestamp, UCP-Agent,
#             Content-Digest, Signature-Input, Signature
function handleWebhook(request):
    # Authenticate: RFC 9421 signature with a key the business publishes
    profile_url = parse_dictionary(request.headers["UCP-Agent"]).profile
    sig_input   = parse(request.headers["Signature-Input"])  # keyid, components
    profile     = GET profile_url                            # cache it
    key         = profile.keys.find(k => k.kid == sig_input.keyid)
    if not key: return 401
    if request.headers["Content-Digest"] !=
            "sha-256=:" + base64(sha256(request.raw_body)) + ":":
        return 401
    if not verify_rfc9421(request, sig_input, key):  # ES256 is the baseline
        return 401

    order = JSON.parse(request.raw_body)
    # Authorize: only the business the order was placed with may update it
    if store.business_for_checkout(order.checkout_id) != profile_url:
        return 403
    if store.seen(request.headers["Webhook-Id"]): return 200  # redelivery

    enqueue(order)      # acknowledge with 2xx fast, process asynchronously
    return 200

# 3. Work out what changed against the copy you already have
function process(order):
    for event in order.fulfillment.events not seen before:  # append-only
        switch event.type:                                   # open string
            "shipped", "in_transit": notify(event.carrier, event.tracking_url)
            "delivered":             notify(event.description)
            "failed_attempt", "undeliverable": notify("Delivery problem")
    for adj in order.adjustments not seen before:
        if adj.type == "refund" and adj.status == "completed":
            notify("Refunded " + amount(adj.totals, "total"))  # minor units
    store.save(order)
import base64
import hashlib
import json
import re

import httpx
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request

# Webhook shape and verification steps per the UCP order spec
# (https://ucp.dev/latest/specification/shopping/order/) and
# Message Signatures (https://ucp.dev/latest/specification/signatures/)
app = FastAPI()

async def signer_key(profile_url: str, kid: str) -> dict | None:
    """Public JWK from the signer's UCP profile (top-level keys[]); cache this."""
    async with httpx.AsyncClient() as http:
        r = await http.get(profile_url)
        r.raise_for_status()
    return next((k for k in r.json().get("keys", []) if k["kid"] == kid), None)

async def authenticate(request: Request, body: bytes) -> str:
    """Verify the RFC 9421 signature; return the signer's profile URL."""
    agent = re.search(r'profile="(https://[^"]+)"', request.headers.get("UCP-Agent", ""))
    keyid = re.search(r'keyid="([^"]+)"', request.headers.get("Signature-Input", ""))
    if not (agent and keyid):
        raise HTTPException(401, "Missing UCP-Agent or Signature-Input")
    key = await signer_key(agent.group(1), keyid.group(1))
    if key is None:
        raise HTTPException(401, "key_not_found")

    # Content-Digest binds the raw body bytes (RFC 9530, sha-256)
    digest = "sha-256=:" + base64.b64encode(hashlib.sha256(body).digest()).decode() + ":"
    if request.headers.get("Content-Digest") != digest:
        raise HTTPException(401, "digest_mismatch")

    # Rebuild the RFC 9421 signature base from the covered components
    # ("@method" "@authority" "@path" "content-digest" "content-type")
    # and check Signature against the JWK. Every verifier must support
    # ES256; use an RFC 9421 library rather than hand-rolling this step.
    if not verify_http_message_signature(request, key):
        raise HTTPException(401, "signature_invalid")
    return agent.group(1)

@app.post("/webhooks/ucp/orders")
async def order_webhook(request: Request, background: BackgroundTasks):
    body = await request.body()  # raw bytes; never re-serialize before verifying
    signer = await authenticate(request, body)
    order = json.loads(body)

    # Authorization: the signer must be the business this order belongs to
    if await db.business_for_checkout(order["checkout_id"]) != signer:
        raise HTTPException(403, "Signer does not own this order")
    if await db.webhook_seen(request.headers["Webhook-Id"]):
        return {"status": "duplicate"}  # retried delivery

    background.add_task(process_order, order)  # 2xx now, work afterwards
    return {"status": "accepted"}

async def process_order(order: dict):
    """The payload is the full current order; diff it against the stored copy."""
    previous = await db.orders.get(order["id"]) or {}
    seen_events = {e["id"] for e in previous.get("fulfillment", {}).get("events", [])}
    seen_adjustments = {(a["id"], a["status"]) for a in previous.get("adjustments", [])}

    for event in order["fulfillment"].get("events", []):
        if event["id"] in seen_events:
            continue
        match event["type"]:  # open string; the spec's common values
            case "shipped" | "in_transit":
                await notify(order, f"On its way with {event.get('carrier', 'the carrier')}",
                             link=event.get("tracking_url"))
            case "delivered":
                await notify(order, event.get("description", "Your order was delivered"))
            case "failed_attempt" | "undeliverable" | "returned_to_sender":
                await notify(order, "There is a problem with the delivery",
                             link=event.get("tracking_url"))

    for adj in order.get("adjustments", []):
        if (adj["id"], adj["status"]) in seen_adjustments:
            continue
        if adj["type"] == "refund" and adj["status"] == "completed":
            amount = next(t["amount"] for t in adj.get("totals", []) if t["type"] == "total")
            await notify(order, f"Refunded {-amount / 100:.2f} {order['currency']}")  # minor units

    await db.orders.save(order)

Order Update Types

Endpoint Method Purpose
/checkout-sessions POST Create a checkout session
/checkout-sessions/{id} GET Get session details
/checkout-sessions/{id} PUT Update the session
/checkout-sessions/{id}/complete POST Complete purchase
/checkout-sessions/{id}/cancel POST Cancel the session
Type Kind Meaning
shipped Fulfillment event Handed to carrier
in_transit Fulfillment event In the delivery network
delivered Fulfillment event Received by the buyer
failed_attempt Fulfillment event A delivery attempt failed
refund, return, cancellation Adjustment Post-order events, independent of fulfillment; the type is an open string, so businesses may use other values

Integration with MCP

UCP defines an MCP binding: a business can expose checkout as the MCP tools create_checkout, get_checkout, update_checkout, complete_checkout and cancel_checkout at the MCP endpoint in its profile. A platform's own MCP server can call them and hand the buyer a review UI before the order is placed:

MCP + UCP Integration
import uuid

import httpx
from mcp import ClientSession, types
from mcp.client.streamable_http import streamablehttp_client
from mcp.server import Server

# Tool names, the meta object and structuredContent results follow the
# UCP checkout MCP binding:
# https://ucp.dev/latest/specification/shopping/checkout/mcp/
PLATFORM_PROFILE = "https://agent.example/.well-known/ucp"
server = Server("shopping-agent")

async def ucp_mcp_endpoint(business: str) -> str:
    """The business's MCP endpoint, from its UCP profile."""
    async with httpx.AsyncClient() as http:
        r = await http.get(f"https://{business}/.well-known/ucp")
        r.raise_for_status()
    services = r.json()["ucp"]["services"]["dev.ucp.shopping"]
    return next(s["endpoint"] for s in services if s["transport"] == "mcp")

async def call_business(business: str, tool: str, arguments: dict, token: str | None) -> dict:
    """Call a UCP tool (create_checkout, complete_checkout, ...) on the business."""
    meta = {
        "ucp-agent": {"profile": PLATFORM_PROFILE},
        "idempotency-key": str(uuid.uuid4()),  # required for complete and cancel
    }
    headers = {"Authorization": f"Bearer {token}"} if token else None
    async with streamablehttp_client(await ucp_mcp_endpoint(business), headers=headers) as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            result = await session.call_tool(tool, {"meta": meta, **arguments})
    return result.structuredContent  # the UCP payload

def text_result(text: str) -> types.CallToolResult:
    return types.CallToolResult(content=[types.TextContent(type="text", text=text)])

@server.call_tool()
async def call_tool(name: str, arguments: dict) -> types.CallToolResult:
    business = arguments["business"]
    token = await get_linked_token(business)  # from identity linking; None = guest

    if name == "start_checkout":
        checkout = await call_business(business, "create_checkout", {"checkout": {
            "line_items": [{"item": {"id": arguments["item_id"]}, "quantity": arguments.get("quantity", 1)}],
            "buyer": arguments["buyer"],
            "fulfillment": {"methods": [{"type": "shipping", "destinations": [arguments["shipping_address"]]}]},
        }}, token)

        if checkout["status"] == "requires_escalation":
            return text_result(f"The store needs you to finish here: {checkout['continue_url']}")
        if checkout["status"] != "ready_for_complete":
            return text_result("Still missing: " + "; ".join(m["content"] for m in checkout.get("messages", [])))

        # The buyer reviews and places the order in a trusted UI, not the model
        total = next(t["amount"] for t in checkout["totals"] if t["type"] == "total")
        return types.CallToolResult(
            content=[types.TextContent(type="text", text=f"Ready for review: {total / 100:.2f} {checkout['currency']}")],
            structuredContent=checkout,
            _meta={"ui": {"resourceUri": "ui://checkout-review", "data": {"business": business, "checkout": checkout}}},
        )

    if name == "place_order":
        # Called by the review UI once the buyer confirms
        checkout = await call_business(business, "complete_checkout", {
            "id": arguments["checkout_id"],
            "checkout": {"payment": arguments["payment"]},  # instruments from a payment handler
        }, token)
        if checkout["status"] == "completed":
            return text_result(f"Order placed: {checkout['order']['id']} ({checkout['order']['permalink_url']})")
        return text_result(f"Checkout status: {checkout['status']}")

    raise ValueError(f"Unknown tool: {name}")

@server.list_tools()
async def list_tools() -> list[types.Tool]:
    return [
        types.Tool(
            name="start_checkout",
            description="Start a checkout at a UCP business and show it to the buyer for review",
            inputSchema={
                "type": "object",
                "properties": {
                    "business": {"type": "string", "description": "Business domain"},
                    "item_id": {"type": "string"},
                    "quantity": {"type": "integer"},
                    "buyer": {"type": "object"},
                    "shipping_address": {"type": "object"},
                },
                "required": ["business", "item_id", "buyer", "shipping_address"],
            },
        ),
        types.Tool(
            name="place_order",
            description="Place a reviewed order; called by the review UI after the buyer confirms",
            inputSchema={
                "type": "object",
                "properties": {
                    "business": {"type": "string"},
                    "checkout_id": {"type": "string"},
                    "payment": {"type": "object"},
                },
                "required": ["business", "checkout_id", "payment"],
            },
        ),
    ]
Combined with MCP Apps
Use MCP Apps to provide interactive checkout confirmation UI, letting users review and approve purchases before completing.

Key Principles

Merchant of Record

Retailers remain the Merchant of Record with full ownership of the customer relationship. UCP facilitates commerce without disintermediating merchants.

Surface Agnostic

UCP works across any surface: chat agents, voice assistants, browser extensions, mobile apps. The protocol doesn't assume any specific UI.

Open & Extensible

UCP is an open standard with no vendor lock-in. Merchants can extend the protocol for custom capabilities while maintaining compatibility.

Privacy Preserving

User credentials never pass through agents. OAuth-based identity linking ensures secure, scoped access with user control.

Protocol Comparison

Protocol Purpose Relationship to UCP
UCP Commerce operations Core protocol for shopping
MCP Tool integration Agent accesses UCP via MCP tools
A2A Agent communication Delegate shopping to specialized agents
AP2 Agent payments Payment processing layer for UCP
OAuth 2.0 Authorization Identity linking foundation

Security Considerations

Audit Logging
Log all commerce operations with user ID, merchant, action, and timestamp. This supports dispute resolution and fraud detection.

Industry Support

UCP is backed by major industry players (Google Developers Blog, January 2026):

Co-Developers

Google, Shopify, Etsy, Wayfair, Target, Walmart

Endorsers at Launch

Adyen, American Express, Mastercard, Stripe, Visa, and others (launch, January 2026)

Learn More
Visit ucp.dev for the full specification and implementation guides.

Related Topics