How it works

The architecture of this reference implementation, from the blueprint's unmodified runtime down to the processor adapters, with the ports, the environment variables and the tests an engineer needs to run it.

The layers

Anthropic's Claude Commerce Agents blueprint is vendored by setup.sh into vendor/commerce-agents at a pinned commit and never edited. Everything this reference adds sits beside it and is imported into the blueprint's own host code. The diagram reads top to bottom, from the shopper's browser to the processor.

The blueprint's 53 runtime modules on two rings: the inner ring holds the 18 that touch a model (nine import the SDK, nine speak a Messages API shape); the outer ring holds the 35 model-free modules. Sectors are packages. the model CLAUDE · OR ANY commerce_common/agent_sdk.py · tier A (imports the SDK; claude_agent_sdk) · 242 lines · Plumbing the two Agent SDK runtimes share: registering an executor's tools as an in-process MCP server, materializing the repo skills for the SDK, host-side grounding, the hook that ends a turn on a chip-carrying present agent_sdk.py commerce_common/config.py · tier B (speaks an API shape; the thinking effort field, thinking content blocks) · 48 lines · The config fields both roles share, in the section order the role configs continue: identity, models, budgets, capabilities, memory, caps. Fields marked (prompt) render into the static prompt or the tool list, so they ar config.py commerce_common/memory.py · tier A (imports the SDK; anthropic, anthropic.types) · 529 lines · Durable memory: the ``MemoryStore`` contract, the write filter, the post-turn extraction pass with the template each role renders its extraction prompt from, and the ``MemoryRuntime`` the executors consume. Every fact re memory.py commerce_common/prompt_assembly.py · tier B (speaks an API shape; prompt-cache breakpoints, forced tool choice) · 97 lines · Where the cache breakpoints go: after the static system text, after the last tool, and rolling through the conversation on the newest persisted message; and where the per-request context goes: a second system block, behi prompt_assembly.py commerce_common/testing.py · tier B (speaks an API shape; streamed partial tool JSON, the streaming Messages call, the Messages call) · 172 lines · Scripted stand-ins for the two model-client contracts, plus a memory store that counts its reads. ``FakeClient`` plays back ``messages.stream`` and ``FakeCreateClient`` plays back ``messages.create``; both record each re testing.py commerce_common/turn.py · tier B (speaks an API shape; streamed partial tool JSON, thinking content blocks) · 507 lines · Pieces of the Messages API turn loop that both roles use the same way: reading the conversation (latest user text, the exchange memory extraction reads, compaction), running a round (:class:`StreamedRound`, eager dispatc turn.py commerce_common/delegation.py · tier C (model-free; no model dependency) · 41 lines · The delegate contract: an isolated model call behind a tool. A delegate receives a task brief and the session handles, never the conversation or the executor, and returns one schema-validated result; it cannot write, pre delegation.py commerce_common/execution.py · tier C (model-free; no model dependency) · 245 lines · The executor frame both roles extend. A role executor supplies its fence, its handler table, and its wording; this module owns dispatch, the failure ladder, skills, presentation, delegates, memory, and the ``status`` lin execution.py commerce_common/fencing.py · tier C (model-free; no model dependency) · 142 lines · Sanitizing and fencing text the model reads as data. Each role defines one ``Fence``; its label is a source literal, never built from runtime values, so untrusted text cannot reproduce the boundary. Every pattern here is fencing.py commerce_common/grounding.py · tier C (model-free; no model dependency) · 62 lines · Grounding rules: a rule reads the user's message and names one read tool the turn must start with, so an answer of that shape begins from a tool result. Each role lists its rules in precedence order; the runtimes force t grounding.py commerce_common/manifest.py · tier C (model-free; no model dependency) · 153 lines · Resolve a Managed Agent manifest (``agent.yaml``) into a ``/v1/agents`` request body: ``system_file`` is inlined, ``skills[].path`` entries become Skills API references (placeholders until ``skill_ids`` supplies uploaded manifest.py commerce_common/mcp_server.py · tier C (model-free; no model dependency) · 82 lines · Plumbing the two reference MCP servers share: one executor per connection, the registry's descriptions, the outcome-to-result mapping, and the loopback-only bind. The servers verify no credential of their own, so they re mcp_server.py commerce_common/presentation.py · tier C (model-free; no model dependency) · 138 lines · Presentation tools: the component spec the built-ins and deployment extensions share, and the one runner that validates a call, enriches it, and produces its ``ui`` event. The model selects and annotates; every fact on t presentation.py commerce_common/skills.py · tier C (model-free; no model dependency) · 63 lines · Skill loading. A skill is a directory holding ``SKILL.md``: YAML frontmatter with ``name`` and ``description``, then the instructions. The static prompt carries the index and ``load_skill`` returns a body on demand. skills.py commerce_common/streaming.py · tier C (model-free; no model dependency) · 209 lines · The events an agent turn yields to its host, and the outcome type every tool call produces. Hosts render the event types below and ignore any they do not know. streaming.py commerce_common/types.py · tier C (model-free; no model dependency) · 47 lines · Data types both roles share. Role-specific types live in the role packages. types.py commerce_common 16 MODULES · ABC shopping_agent/config.py · tier B (speaks an API shape; the thinking effort field) · 108 lines · Per-deployment settings for the shopping agent; per-request values travel in ``ShoppingSessionContext``. Sections continue ``BaseAgentConfig``'s: capabilities, cart caps, grounding gates. config.py shopping_agent/tools/registry.py · tier B (speaks an API shape; the web_search server tool) · 627 lines · The shopping agent's tool contracts, in a fixed order. The list depends only on the deployment config, so it is the same bytes on every request; whether a capability can serve a call is decided in the executor. A descrip tools/registry.py shopping_agent/backend.py · tier C (model-free; no model dependency) · 132 lines · The StorefrontBackend interface: the one integration surface an adopter implements, mapping each method onto their catalog, cart, profile, order, and policy services. Everything these methods return reaches the model as backend.py shopping_agent/enrichment.py · tier C (model-free; no model dependency) · 254 lines · The built-in components: each payload joined to the session's catalog records, the cart, or an order before it reaches the host. Ids without session provenance are dropped and reported; a component left with nothing cano enrichment.py shopping_agent/executor.py · tier C (model-free; no model dependency) · 187 lines · The shopping agent's tools, one handler each, over the shared executor frame. The Messages API runtime, the SDK toolset, and the MCP server all execute through this class, so a tool result is the same bytes on every path executor.py shopping_agent/fencing.py · tier C (model-free; no model dependency) · 13 lines · The shopping agent's data fence: every tool result built from catalog, review, policy, order, or web content goes back to the model inside it. The mechanism lives in ``commerce_common.fencing``; this module fixes the lab fencing.py shopping_agent/gates.py · tier C (model-free; no model dependency) · 144 lines · The cart gates. A cart write accepts only product ids that catalog or order tools returned this session (or lines already in the cart), holds an add of a product that still has options to choose and points at its variant gates.py shopping_agent/grounding.py · tier C (model-free; no model dependency) · 57 lines · The shopping agent's grounding rules, in precedence order: a store-terms question starts from search_policies, a post-purchase question from get_orders, and a mention of an unseen product id from get_product_details. A r grounding.py shopping_agent/memory.py · tier C (model-free; no model dependency) · 30 lines · The extraction prompt the shopping runtimes hand to ``commerce_common.memory``: what the store may remember about one customer between visits. memory.py shopping_agent/prompt.py · tier C (model-free; no model dependency) · 204 lines · The shopping agent's system prompt: a static half that is cached and a dynamic half appended after the cache breakpoint. The static half depends only on the deployment config and the installed skills; everything per requ prompt.py shopping_agent/serialization.py · tier C (model-free; no model dependency) · 112 lines · The payloads read tools hand the model, built once so every path returns the same bytes. The search header is the one runtime-authored line outside the fence: the result count and a fixed sentence on how to read the resu serialization.py shopping_agent/tools/presentation.py · tier C (model-free; no model dependency) · 55 lines · Payload schemas for the built-in presentation tools: what the model may send. The joins that turn a payload into what the host renders live in ``enrichment``. tools/presentation.py shopping_agent/types.py · tier C (model-free; no model dependency) · 150 lines · The shopping agent's domain models: what a storefront backend returns and the session records the gates and enrichment read. types.py shopping_agent 13 MODULES · BC shopping_agent_runtime/orchestrator.py · tier A (imports the SDK; anthropic) · 259 lines · The shopping agent's turn loop on the Messages API: one model call per iteration, tools dispatched eagerly as their blocks close, presentation calls rendered while they stream, a rolling cache breakpoint through the conv orchestrator.py shopping runtime 1 MODULES · A shopping_agent_sdk/agent.py · tier A (imports the SDK; claude_agent_sdk) · 92 lines · The shopping agent as ``ClaudeAgentOptions``: the static prompt plus the skill adapter, the storefront server as the only tools, and the repo skills materialized for the SDK. ``run_turn`` grounds the message the way the agent.py shopping_agent_sdk/shopping_tools.py · tier A (imports the SDK; claude_agent_sdk) · 75 lines · The shopping tools as an in-process MCP server for the Agent SDK: the registry's contracts minus ``load_skill`` (the SDK's Skill tool replaces it), every call executed by ``ShoppingToolExecutor``, and presentation payloa shopping_tools.py shopping_agent_sdk/_paths.py · tier C (model-free; no model dependency) · 7 lines · Repo paths this runtime reads at import time, resolved from this file. _paths.py shopping SDK 3 MODULES · AC merchant_agent/analysis.py · tier B (speaks an API shape; the code_execution server tool) · 291 lines · The run_analysis contract: the tool definition the orchestrator sees, the system prompt and tool definitions the analysis delegate sees, the SELECT-only check for ``MerchantBackend.execute_analysis_query``, and the metri analysis.py merchant_agent/config.py · tier B (speaks an API shape; the thinking effort field) · 175 lines · Per-deployment settings for the merchant agent; per-request values travel in ``MerchantSessionContext``. Sections continue ``BaseAgentConfig``'s: capabilities (analysis), guardrails, approval, grounding gates. config.py merchant_agent/tools/registry.py · tier B (speaks an API shape; the web_search server tool) · 697 lines · The merchant agent's tool contracts, in a fixed order. The list depends only on the deployment config, so it is the same bytes on every request; whether a capability can serve a call is decided in the executor. A descrip tools/registry.py merchant_agent/backend.py · tier C (model-free; no model dependency) · 182 lines · The MerchantBackend interface: the one integration surface an adopter implements, mapping each method onto their analytics, catalog, inventory, order, pricing, and campaign systems. Everything these methods return reache backend.py merchant_agent/changes.py · tier C (model-free; no model dependency) · 189 lines · The staged-change guardrails and the in-memory ``ChangeLedger`` the example backends build on. Guardrails run when a change is staged and again before it is applied. changes.py merchant_agent/enrichment.py · tier C (model-free; no model dependency) · 394 lines · The built-in merchant components: metric picks resolved to the values tools returned this session, digest items joined to their listing or change records, and a change preview built from the staged record with model text enrichment.py merchant_agent/executor.py · tier C (model-free; no model dependency) · 324 lines · The merchant agent's tools, one handler each, over the shared executor frame. The Messages API runtime, the SDK toolset, the MCP server, and the analysis delegate's reads all execute through this class, so a tool result executor.py merchant_agent/fencing.py · tier C (model-free; no model dependency) · 13 lines · The fence every merchant tool result is returned inside. The mechanism lives in ``commerce_common.fencing``; this module fixes the merchant label and notice wording. fencing.py merchant_agent/gates.py · tier C (model-free; no model dependency) · 191 lines · The merchant gates and the wording every path returns when one holds. Staged writes accept only listing and campaign ids that tools returned this session; a price or restock write that names a listing with options is poi gates.py merchant_agent/grounding.py · tier C (model-free; no model dependency) · 56 lines · The merchant agent's grounding rules, in precedence order: a performance question starts from get_business_snapshot, and an apply request with nothing staged this session starts from get_pending_changes. :func:`change_re grounding.py merchant_agent/memory.py · tier C (model-free; no model dependency) · 30 lines · The extraction prompt the merchant runtimes hand to ``commerce_common.memory``: what the assistant may remember about one operation between sessions, keyed by merchant id. memory.py merchant_agent/prompt.py · tier C (model-free; no model dependency) · 213 lines · The merchant agent's system prompt: a static half that is cached and a dynamic half appended after the cache breakpoint. The static half depends only on the deployment config and the installed skills; everything per requ prompt.py merchant_agent/serialization.py · tier C (model-free; no model dependency) · 80 lines · The search_listings result, built once so every path returns the same bytes. The header is the one runtime-authored line outside the fence: the result count and a fixed sentence on how to read the results as text matches serialization.py merchant_agent/tools/presentation.py · tier C (model-free; no model dependency) · 30 lines · Payload schemas for the built-in presentation tools: what the model may send. The joins that turn a payload into what the portal renders live in ``enrichment``. tools/presentation.py merchant_agent/types.py · tier C (model-free; no model dependency) · 359 lines · Merchant domain types shared by the orchestrator, the MerchantBackend interface, and the examples: listings, metrics, analysis results, inventory and order health, pricing, campaigns, staged changes, and session state. A types.py merchant_agent 15 MODULES · BC merchant_agent_runtime/analysis.py · tier A (imports the SDK; anthropic) · 341 lines · The analysis delegate: a separate model loop, run inside the analysis tool call, whose tools are the merchant read tools plus a submission tool and, per deployment, a SELECT-only query method and the hosted code sandbox. analysis.py merchant_agent_runtime/orchestrator.py · tier A (imports the SDK; anthropic) · 299 lines · The merchant agent's turn loop on the Messages API: one model call per iteration, tools dispatched eagerly as their blocks close while delegate progress lines stream, presentation calls rendered while they stream, a roll orchestrator.py merchant runtime 2 MODULES · A merchant_agent_sdk/agent.py · tier A (imports the SDK; claude_agent_sdk) · 146 lines · The merchant agent as ``ClaudeAgentOptions``: the static prompt plus the SDK adapters, the merchant server as the only tools, the repo skills, and, when analysis is enabled, the delegate as a subagent restricted to the r agent.py merchant_agent_sdk/merchant_tools.py · tier A (imports the SDK; claude_agent_sdk) · 98 lines · The merchant tools as an in-process MCP server for the Agent SDK: the registry's contracts minus ``load_skill`` and ``run_analysis`` (the SDK's Skill tool and a subagent take those roles), every call executed by ``Mercha merchant_tools.py merchant_agent_sdk/_paths.py · tier C (model-free; no model dependency) · 7 lines · Repo paths this runtime reads at import time, resolved from this file. _paths.py merchant SDK 3 MODULES · AC What the colours mean Red · talks to Claude directly (9) imports Anthropic's kit; swap to change the AI Violet · uses a Claude-only trick (9) cache marks, a forced first read, web search Green · works with any AI, or none (35) rules, gates, cards, skills; keep as they are inner ring: red and violet · outer ring: green each wedge is one package (a folder of parts) HOVER OR CLICK A DOT FOR WHAT THAT PART DOES
Inner ring: touches a model. Outer ring: model-free. Everything that makes the product safe sits on the outer ring: the provenance rule, the cart gates, the fences, the presentation contract, the skills. The full inventory with every module's purpose and line count is in the project's docs/MODULES.md; the script that produced it is in the reference.
red · talks to Claude directly (9)violet · uses a Claude-only trick (9)green · works with any AI, or none (35)
  shopper's browser                          staff's browser
  web/storefront (Next.js)                   web/portal (Next.js)
  chat, cart panel, "Pay securely" button,   payments panel, staged changes
  status poll after the button is pressed
          |                                          |
          v                                          v
  merchant API (FastAPI, one process per merchant; verticals/<merchant>/api/main.py)
  /api/brand  /api/chat  /api/cart/*  /api/merchant/*  /checkout/*  /store/checkout/*  /pay/*
  /.well-known/ucp  /api/ucp/mcp  /api/mcp  /acp/*  /webhooks/*
          |
          v
  the blueprint (vendor/commerce-agents, unmodified)
    ShoppingAgent and MerchantAgent turn loops, executor, gates, fences
    skills registry and load_skill, presentation tools, memory
    StorefrontBackend (11 required + 3 optional)   MerchantBackend (16 required + 3 optional)
          |                                          |
          v                                          v
  this reference
    psp_commerce/integration/  one mixin per checkout model -> checkout_handoff
    commerce_core/tender.py    present_tender_options (the tender card)
    commerce_core/merchant.py  PaymentsOpsMixin (metrics, disputes, SQL tables)
    psp_commerce/thirdparty/   UCP discovery, the MCP endpoint, ACP, the feed
    psp_commerce/webhooks.py   Stripe and Adyen signature verification
          |
          v
    psp_commerce/gateway.py    PaymentGateway protocol
    verticals/registry.py      gateway_for(): the real adapter when its variables are set,
                               the simulated gateway otherwise (GATEWAY_MODE=simulated forces it)
          |
          v
    psp_commerce/adapters/     stripe.py  adyen.py  worldpay.py  cybersource.py  clover.py  mock.py
          |
          v
    the processor's test environment (live), or local pages served by the API (simulated)

The blueprint's runtime

The blueprint runs one model in a loop with a fixed tool list. Each round, the model writes text and asks for tool calls; an executor (ShoppingToolExecutor for the shopping side) runs each call against the merchant's backend, applies the gates, fences the results and returns them; the round that carries the follow-up chips ends the turn. The static system prompt and the tool list are built once per deployment, so the expensive part of every request is identical bytes.

The gates are code, and they hold regardless of what the model does. A cart write must name a product id that a catalog or order tool returned in this conversation; tests/test_checkout_handoff_turn.py::test_cart_write_needs_provenance shows an invented id refused before the backend sees it. Quantities and line counts are capped. Every tool result is fenced (normalized, stripped of invisible characters, labeled as data). Identity is bound at session start and no tool argument names a user.

A merchant connects by implementing two backends. StorefrontBackend (vendor/commerce-agents/shopping-agent/core/shopping_agent/backend.py) has eleven required functions: search_products, get_product_details, get_cart, add_to_cart, update_cart_item, remove_from_cart, get_preferences, get_orders, get_order, search_policies and get_fulfillment_options; and three optional ones: checkout_handoff, get_account_context and get_disclosure. MerchantBackend (vendor/commerce-agents/merchant-agent/core/merchant_agent/backend.py) has sixteen required functions: get_business_snapshot, query_metrics, get_campaign_performance, search_listings, get_listing, get_inventory_alerts, get_order_issues, get_pricing_context, stage_listing_update, stage_price_update, stage_inventory_action, stage_promotion, stage_campaign, get_pending_changes, apply_change and discard_change; and three optional ones: execute_analysis_query, get_analysis_schema and get_merchant_context. Every write on the merchant side is staged, and apply_change runs only after a person approves in the host's own tool.

Skills and load_skill

A skill is one SKILL.md file with a name, a one-line description and a page of rules. The system prompt carries only the index (name and description); when a request matches, the model calls the blueprint's load_skill tool and the body enters its context for the rest of the flow. The blueprint ships five shopping skills (search-discovery, purchase-research, planning-goals, customer-care, memory-personalization) and five merchant skills (performance-insights, inventory-operations, catalog-listings, pricing-promotions, marketing-campaigns). This reference adds tender-and-loyalty and payments-operations in psp_commerce/skills/. Both runtimes take a single skills directory, so psp_commerce/skills_dir.py assembles the blueprint's five and the reference's one per role into .skills/<role>/ (ignored by git, rebuilt when a source is newer).

How a skill loads: a request arrives, the assistant scans a five-line index in its standing instructions, the matching entry lights up, a load-skill call brings that page of rules into context alongside the first data read, and the flow runs with those rules. "Compare the top two tents, I care about space and setup" The index, in standing instructions customer-care memory-personalization planning-goals purchase-research search-discovery ◀ matches load_skill the page enters context get_product_details ×2 same round as the load Comparison card 2 to 4 finalists, pros and cons, price gap from the server, "what the extra money buys" in the text, per the skill CHIPS END THE TURN The five shopping entries above are the real index; a merchant's assistant carries a different five. A payment company adds one to each.
The request lights one line of the index. The assistant loads that page and makes its first data read in the same round.

Presentation tools

A card is a tool call. The model chooses which card and which items; a server-side hook fills in the values. The shopping side registers present_products, present_comparison, present_plan, present_guide, present_order_status, checkout, present_suggestions and, when enabled, present_disclosure; the merchant side registers present_metrics, present_digest, present_change_preview and present_suggestions. search_products, load_skill, present_plan and present_suggestions are the blueprint's tools; no processor supplies them.

This reference adds one card through the blueprint's PresentationExtension hook: present_tender_options in commerce_core/tender.py. The model's payload carries at most a 200-character note. The enrich hook reads the cart and the customer's loyalty tier, calls the backend's psp_tender_options, and the gateway computes every reward, split, balance and points figure for that subtotal. An empty cart, or a backend with no gateway, gets a refusal instead of a card with no figures (tests/test_tender_extension.py).

checkout_handoff and the URL the model never sees

The blueprint's checkout tool renders the cart. When a backend implements checkout_handoff, the executor calls it after the model's tool call and attaches the returned CheckoutHandoff(url, label) to the card's handoffs list. The URL therefore appears in the UI event the browser renders and in no request body sent to the model. tests/test_checkout_handoff_turn.py::test_checkout_url_reaches_ui_but_never_the_model scripts a search, add and checkout turn and asserts exactly that, on the system text, the tools and the whole transcript, and on the stored transcript the host keeps for the next turn. tests/test_runtime_agnostic.py asserts the same on the model-agnostic loop.

The three run paths, and another model

The demo merchants run the blueprint's Messages API runtime (ShoppingAgent from shopping_agent_runtime, MerchantAgent from merchant_agent_runtime). scripts/console.py runs the same backend, skills and tender card on the Claude Agent SDK path. commerce_core/mcp_server.py mounts the blueprint's storefront tools through its executor beside the platform tools, the shape a hosted deployment uses.

psp_commerce/runtime/ is a rewrite of the shopping turn loop against a ModelProvider contract (provider.py: one complete() call per round, the Messages API block format as the canonical shape). providers.py implements Anthropic, an OpenAI-compatible endpoint (OpenAI, Azure, Ollama, vLLM through base_url), Gemini, and a scripted provider for tests. Everything below the model (prompt builders, tool contracts, executor, gates, skills) is the blueprint's code imported unchanged. Claude was run live; the OpenAI and Gemini providers are unit-tested against the documented wire shapes and were not run live in this repository.

The processor layer

The PaymentGateway protocol

psp_commerce/gateway.py defines PaymentGateway, a structural protocol: any class with these methods satisfies it, and nothing subclasses anything.

Group Methods Record returned
registry now, merchant MerchantAccount with its Tender list and LoyaltyProgram
hosted page create_checkout_session, get_checkout_session, sessions_for CheckoutSession with checkout_url and expires_at
server-side API create_payment_intent, get_payment_intent, authorize_payment, intents_for PaymentIntent
drop-in create_client_session, get_client_session, complete_client_session, client_sessions_for, available_tenders ClientSession with client_key, payment_methods, session_data
pay by link create_payment_link, get_payment_link, payment_links_for PaymentLink with url
a platform's credential authorize_delegated Transaction, or DelegatedCredentialUnsupported
tender card tender_options rows with reward, split, per_installment, balance, points
back office transactions, transaction, transactions_for_customer, settlement_batches, disputes, metric_series, payments_summary Transaction, Dispute, batches, series

Every method runs server-side in the host. None is a tool the model can call.

Adapters

psp_commerce/adapters/_base.py holds what every real adapter is built from: ProcessorClient, a small synchronous httpx client with a per-request header hook for the processor's signature scheme; Ledger, the adapter's own record of what it created and what the processor reported back; and BaseAdapter, the shared implementation of the reporting methods over psp_commerce/reporting.py. Each adapter file says in its docstring which endpoint each method maps to and what the live runs found:

What a real processor adapter is made of: the contract, the signed HTTP client, the four checkout models and payment links, delegated credentials, a webhook-fed ledger with shared reporting, and the tests and smoke run that prove it. The contract PaymentGateway: one interface hosted · server · drop-in · link tender rows for a cart delegated credentials transactions · settlements · disputes SAME FOR SIX PROCESSORS The signed HTTP client Stripe: bearer key, idempotency keys Adyen: API key · Worldpay: basic auth CyberSource: digest + keyed signature the processor: HMAC over key, id, time, body Clover: OAuth bearer, PAKMS, Ecommerce token THE SIGNED BYTES ARE THE SENT BYTES The calls, model by model hosted: create a session or a pay-by-link page → URL server: intent, then authorize with the page's token drop-in: client session / capture context / SDK id link: a processor payment link for the cart delegated: Google Pay payload, shared payment token ONE METHOD EACH; SIX BODIES The ledger and the shared arithmetic what the adapter created + what webhooks reported (signatures verified) list endpoints where they exist (Stripe, CyberSource search, Worldpay queries, Clover) metrics, batches and the summary computed once for the mock and every adapter What proves it, and what does not yet tests: every request's path, auth and body asserted against a stand-in server Stripe run live in test mode (6 Sep 2026): four models, reads, a captured test payment not yet: the other five against a test environment (psp_smoke.py, with credentials) Live or simulated gateway_for(merchant) returns the processor's adapter when its variables are set and the in-memory gateway otherwise; the brand route reports gateway_mode, so a demo is never mistaken for a sandbox run.
One contract, six bodies. The processor-specific part of an adapter is its authentication scheme and its request bodies; everything above them (the tender card, the merchant agent's numbers, the checkout pages, the third-party endpoints) is shared.
Adapter Base URL and authentication Variables that switch it on
stripe.py https://api.stripe.com/v1, bearer secret key, form-encoded, Stripe-Version: 2026-03-25.dahlia STRIPE_SECRET_KEY
adyen.py https://checkout-test.adyen.com/v72, X-API-Key, JSON ADYEN_API_KEY, ADYEN_MERCHANT_ACCOUNT
worldpay.py https://try.access.worldpay.com, basic auth, versioned media types WORLDPAY_USERNAME, WORLDPAY_PASSWORD, WORLDPAY_ENTITY
cybersource.py https://apitest.cybersource.com, HTTP Signature with Digest CYBERSOURCE_MERCHANT_ID, CYBERSOURCE_KEY_ID, CYBERSOURCE_SECRET_KEY
clover.py https://apisandbox.dev.clover.com (platform REST), https://scl-sandbox.dev.clover.com (Ecommerce), https://token-sandbox.dev.clover.com (tokenization); bearer tokens; CLOVER_ENV=production for the live hosts CLOVER_MERCHANT_ID, CLOVER_ACCESS_TOKEN

tests/test_adapters_http.py runs every adapter against a mock transport that asserts the path, the authentication header and the body, and answers with the documented response shape.

The simulated gateway

psp_commerce/adapters/mock.py defines MockGateway, an in-memory implementation of the whole protocol on top of commerce_core/gateway.py's SimulatedGateway: hosted sessions that expire after fifteen minutes, payment intents, client sessions, payment links, and a deterministic history of transactions, settlements and disputes seeded from the merchant id so demos and tests are stable. Its pages are served by the merchant API itself. It carries a simulated_processor label, and its authorize_delegated accepts only the credential providers the real adapter for that processor declares, so a simulated Adyen merchant refuses a Stripe shared payment token the same way the live adapter would.

Choosing the gateway

verticals/registry.py holds the five merchant accounts (MID-100-NORTHSTAR, MID-700-LUMEN, MID-800-AURORA, MID-900-BEACON, MID-950-ENCORE) with their tenders and loyalty programs. gateway_for(merchant_id, base_url) returns the merchant's adapter when that adapter's available() reports its variables are set and GATEWAY_MODE is anything other than simulated; a MissingCredentials error or an absent variable falls back to MockGateway. gateway_mode() names the result, and verticals/_host.py puts it on GET /api/brand as gateway_mode: simulated|live with a one-line gateway_note.

The four checkout integration models

CHECKOUT_MODEL selects the model at boot (hosted by default; server, dropin or link). psp_commerce/gateway.py::checkout_model_from_env reads it, psp_commerce/integration/__init__.py::mixin_for returns the mixin, and each merchant's build_backend composes a class with the mixin ahead of the store (type(f"LumenHome{model}", (mixin, LumenHomeStore), {}) in verticals/lumen_home/api/backend.py). Every mixin implements checkout_handoff and open_checkout; the latter feeds the cart panel through verticals/_host.py::cart_extras_for, which adds checkout_url, checkout_label, checkout_expires_at, checkout_status_url and, for drop-in, the dropin block to every cart payload.

Shopper Assistant (the model) Store server PSP hosted page “check out” checkout(note) create_checkout_session(lines, customer,return_url) checkout_url · expires in 15 min checkout card + button (URL added after the model's call) opens the page · picks a tender · pays redirect + webhook: order · transaction next turn: “the cart is now an order” PCI: SAQ A · the PSP renders, collects, authorizes · the store learns by webhook
The processor renders, collects and authorizes. The store holds no card data. This is the model the first cut of this reference assumed, and the one Clover, Adyen, Stripe and Worldpay each create with a single call.
Shopper Assistant (the model) Store server Store checkout page PSP API “check out” checkout(note) create_payment_intent(lines, customer) intent id (created) checkout card → /store/checkout/{pi_…} opens the store's page · enters details POST /store/checkout/{pi_…}/pay{tender} authorize_payment(intent, tender, capture) transaction: captured next turn: “the cart is now anorder” PCI: SAQ D unless the PSP's tokenizer is used on the page · the store renders and collects · the PSP authorizes
The store renders and collects; the processor authorizes. The processor is invisible in the link and sees one authorization request. The store carries the page and, unless it uses the processor's tokenizer, the deeper PCI scope.
Shopper Assistant (the model) Store server Store page + PSP drop-in PSP “check out” checkout(note) create_client_session(lines, customer) session id · client key · payment methods · session data checkout card → /store/checkout/{cs_…} (+ dropin block) opens the store's page · the component mounts collects and completes inside thePSP's frame webhook: completed · order · transaction next turn: “the cart is now anorder” PCI: SAQ A (iframe) or A-EP (hosted fields) · the PSP's component renders and collects · the PSP authorizes
The store's page, the processor's component. The component collects and completes inside the processor's frame; the webhook is the signal the store trusts. Adyen's Drop-in, Stripe's embedded Checkout, CyberSource's Unified Checkout, the processor's Checkout.js, Clover's iframe and Worldpay's Checkout SDK all fit here.
Shopper Assistant (the model) Store server PSP pay-by-link page “check out” checkout(note) create_payment_link(lines, customer) link URL · expiry checkout card → the payment link opens the link · pays webhook: paid · order · transaction next turn: “the cart is now an order” PCI: SAQ A · the hosted model with a URL that travels
The hosted model with a URL that travels. Stripe Payment Links, Adyen Pay by Link, CyberSource Pay by Link, Clover Hosted Checkout links, the processor Checkout Pages links and Worldpay Hosted Payment Pages all fit. The same link is what an agent hands a shopper when it uses the processor's own tools, which is why this model reappears in the third-party section.
Model Mixin What the card's button opens Who authorizes Demo page and completion (psp_commerce/checkout_pages.py)
hosted HostedCheckoutMixin the processor's page from create_checkout_session the processor, on its page /checkout/{cko_…}, POST /checkout/{id}/complete, GET /checkout/{id}/status
server ServerSideCheckoutMixin the merchant's own route /store/checkout/{pi_…}; a payment intent is created when the card is staged, and staging the same lines again reuses it the merchant's server, through authorize_payment POST /store/checkout/{id}/pay, GET /store/checkout/{id}/status
dropin DropInCheckoutMixin /store/checkout/{cs_…} with the processor's component mounted from client_key and payment_methods the processor, from its component; the webhook confirms POST /psp/dropin/{id}/complete, GET /psp/dropin/{id}/status
link LinkCheckoutMixin a processor-hosted link from create_payment_link the processor, on the link's page /pay/{plink_…}, POST /pay/{id}/complete, GET /pay/{id}/status

In every model the tender card's rows come from gateway.tender_options and are identical; tests/test_integration_models.py::test_tender_card_is_identical_across_models asserts it. The demo completion routes stand in for what a real processor reports by webhook; on a live adapter the merchant-owned pages still render, and the payment itself happens with the processor.

The return leg after a live payment

On the simulated gateway the hosted page is local and the storefront polls <checkout_url>/status. On a live processor the checkout URL is the processor's page on another origin, so three things change, all in commerce_core/hosted_checkout.py and verticals/_host.py.

First, the processor's return address is the merchant API's GET /checkout/return. The Stripe adapter sets success_url to /checkout/return?session_id={CHECKOUT_SESSION_ID}; the Adyen adapter sets returnUrl to /checkout/return, and Adyen appends sessionId and sessionResult. The route reads the session through gateway.get_checkout_session, which on Stripe calls GET /checkout/sessions/{id} and records the order when payment_status is paid, and on Adyen hands sessionResult to record_session_result and then calls GET /sessions/{id}?sessionResult=. The page tells the shopper whether the payment was received and links back to STORE_URL.

Second, the storefront polls checkout_status_url on the merchant API (/checkout/{id}/status for the hosted model, /pay/{id}/status for a link; status_url_for in verticals/_host.py) every 2.5 seconds after the button was pressed (web/storefront/components/CartPanel.tsx), so the store notices the payment without a reload.

Third, the note the assistant reads. install_hosted_checkout queues one note per completed session, whichever route first observes the payment (the return page, the status poll, or the demo completion route), through on_completed, which verticals/_host.py implements by appending to pending_app_events on each of the customer's live sessions. The blueprint delivers those events to the model on its next turn. tests/test_demo_paths.py::test_return_leg_notifies_the_assistant_once covers the return route with Stripe's and Adyen's parameter names and the once-only rule. A verified webhook (psp_commerce/webhooks.py) queues the same note.

The third-party layer

Every merchant serves the Universal Commerce Protocol (UCP) over the Model Context Protocol (MCP) and the Agentic Commerce Protocol (ACP) from the same StorefrontBackend and gateway its own assistant uses (psp_commerce/thirdparty/, installed by verticals/_host.py).

One MCP server and one UCP/ACP endpoint serving two audiences: the store's own hosted assistant and platform agents, both from the same storefront adapters and the same hosted checkout link, with the remaining protocol work marked. THE SAME ADAPTERS Ten merchants' StorefrontBackend catalog · stock · cart · policies · orders written once for the store's own assistant Clover inventory · own platform · Shopify UCP BUILT MCP server · UCP endpoint · ACP endpoint list_merchants · search · stock · stage_checkout /.well-known/ucp · /api/ucp/mcp · /acp/… payment handlers declared per processor BUILT · NO AUTH YET ON THE MCP SERVER The store's own hosted assistant Managed Agents: the manifest names the server Platform agents Google's surfaces, ChatGPT, Copilot, any MCP client The same checkout, or a handler credential tenders intact · the order joins the same ledger WHAT IS BUILT, AND WHAT IS NEXT UCP endpoint discovery with payment handlers search · cart · checkout · orders Shopify's client runs against it BUILT · VARIANTS 1 AND 2 ACP endpoint + feed checkout sessions with handlers a shared payment token charged link-out when the PSP cannot BUILT · VARIANTS 5 AND 6 Agent verification Visa TAP signatures · Agent Pay tokens AP2 mandates (now at FIDO) the acquirer's job, a new signature NEXT · NETWORK SEATS Order join + evidence every transaction records the agent's identity and credential for the dispute that follows BUILT · agent_id, credential
Adapters first, then the server and the endpoints, then verification. Each step reuses the one before it.

scripts/platform_agent.py is the client side: scripted, or driven by Claude, an OpenAI model or Gemini through the provider contract, against these merchants or a Shopify store. Platform agents over UCP and ACP covers the whole layer, the eight ways a platform can pay, and Claude Code as a client.

The web apps and the vendored vertical apps

web/storefront and web/portal are Next.js forks of the blueprint's retail web apps. One build serves any merchant: the app reads NEXT_PUBLIC_API_URL, calls /api/brand for the store's name, mark, colors, processor, checkout model and gateway mode, and themes itself. The storefront adds the tender card (components/generative/TenderOptions.tsx) and the checkout button with its status poll (components/CartPanel.tsx); the portal adds the payments panel (components/views/PaymentsPanel.tsx). They serve Northstar Outfitters and Lumen Home.

Aurora Escapes, Beacon Wireless and Encore Seats use the blueprint's own travel, telecom and entertainment apps from vendor/commerce-agents/examples/<vertical>/storefront-web and merchant-web, pointed at this reference's API. Shopify's example runs from vendor/claude-for-commerce-examples/storefront (its own API and web app) against a real store named by SHOP_DOMAIN. Every company, brand, product and person in the five demo merchants is fictional.

scripts/run_demo.py <northstar|lumen|aurora|beacon|encore> [--all|--merchant|--api-only] starts a merchant's API and web apps, sets MERCHANT_BASE_URL and STORE_URL, and gives each web port its own Next.js build directory. The platform run scripts call it.

Ports

Merchant Processor API Storefront Portal
Shopify's example (fakestore-ai.myshopify.com) Shopify 8004 3005 not started by the reference
Northstar Outfitters Clover 8010 3010 3110
Lumen Home Stripe 8016 3016 3116
Aurora Escapes Adyen 8017 3017 3117
Beacon Wireless Worldpay 8018 3018 3118
Encore Seats CyberSource 8019 3019 3119

.mcp.json at the root registers lumen-home (http://localhost:8016/api/ucp/mcp) and aurora-escapes (http://localhost:8017/api/ucp/mcp) as MCP servers for Claude Code.

The tests

Sixty-nine tests run with no credentials in about ten seconds; every model call is scripted.

source .venv/bin/activate
python -m pytest -q
File What it proves
tests/test_checkout_handoff_turn.py the checkout URL reaches the UI event and no request to the model; an invented product id is refused
tests/test_integration_models.py the hosted, server and drop-in models on one merchant: what the card links to, which page opens, who authorizes, and identical tender rows
tests/test_adapters_http.py every adapter's requests and the documented responses through a mock transport; the CyberSource signature; the Stripe and Adyen webhook verifiers
tests/test_thirdparty.py Shopify's own UcpClient and ShopifyStorefrontBackend, vendored unchanged, shop at the Stripe merchant; ACP completes with a delegated token; a credential the processor cannot charge is refused; the payment-link model
tests/test_demo_paths.py the return leg notifies once; the cart payload names a local status URL; the MCP handshake; the platform agent script, scripted and on a scripted provider
tests/test_runtime_agnostic.py the model-agnostic loop never sees the URL; grounding by prefetch; the OpenAI and Gemini conversions
tests/test_verticals_boot.py every merchant boots simulated and reports its own store
tests/test_gateway.py, test_tender_extension.py, test_payments_ops.py, test_clover_storefront.py, test_mcp_server.py the simulated gateway, the tender card, the payments view, the Clover catalog mapping, the platform MCP server

Each platform folder's test.sh runs the subset for that merchant, boots the API, checks discovery and the MCP handshake, has a scripted platform agent stage a checkout, and, when the processor's variables are set, runs scripts/psp_smoke.py against the processor's test environment.

platforms/adyen/test.sh