Skip to content

Engine: Agentic UCP

The Universal Commerce Protocol implementation: discovery profile, catalog, cart, checkout and order capabilities, request signing and verification (RFC 9421), capability negotiation, the MCP binding and order webhooks. Server-only; the theme's app/api/ucp/** routes re-export these handlers.

Generated from packages/engine/src/agentic/ucp/: 49 files, 373 exported symbols. Signatures and types are shown as written in the source.

@magenxcommerce/engine/agentic/ucp/_lib/address

packages/engine/src/agentic/ucp/_lib/address.ts

UCP destination + buyer → Magento CartAddressInput.

THE REGION RULE (the oldest gotcha in this codebase, see CLAUDE.md): for any country that exposes available_regions, Magento must receive a numeric region_id. Sending only a free-text region string fails with either "Region is required" or the more confusing "regionId is required", depending on whether the string resolved. The browser checkout solves this with a region <select> populated from GET_COUNTRIES; an agent has no dropdown, so the same resolution is done here — the platform may send "CA", "ca" or "California" and all three resolve to the same id.

Pure and dependency-free (countries are passed in) so the resolution table is directly unit-testable.

CountryOption interface

Minimal shape of a GET_COUNTRIES entry — only what resolution needs.

MemberTypeDescription
two_letter_abbreviation?string | null
available_regions?Array<{ id: number; code: string | null; name: string | null; }> | null

MagentoAddressInput interface

MemberTypeDescription
firstnamestring
lastnamestring
streetstring[]
citystring
region?string
region_id?number
postcodestring
country_codestring
telephonestring
save_in_address_bookboolean

AddressResult type

type AddressResult = | { ok: true; address: MagentoAddressInput } | { ok: false; code: string; message: string; path: string }

resolveRegionId function

resolveRegionId(country: CountryOption | undefined, region: string | undefined): number | null | undefined

Resolve a region string to Magento's numeric id for a country.

Returns undefined when the country has no region list (Magento then accepts a free-text region, e.g. GB), and null when the country DOES have regions but the supplied value matched none — the caller must reject that rather than let Magento produce its opaque error.

findCountry function

findCountry(countries: ReadonlyArray<CountryOption>, countryCode: string): CountryOption | undefined

Find a country entry by ISO alpha-2 code.

buildMagentoAddress function

buildMagentoAddress(destination: UcpDestination, buyer: UcpBuyer | undefined, countries: ReadonlyArray<CountryOption>): AddressResult

Build the Magento address input for a UCP destination.

Magento requires a name and phone on every physical address; UCP carries those on buyer (and optionally on the destination itself), so the two are merged here with the destination taking precedence.

@magenxcommerce/engine/agentic/ucp/_lib/apply

packages/engine/src/agentic/ucp/_lib/apply.ts

Apply a platform's checkout input to the underlying Magento quote.

UCP models update as a FULL RESOURCE REPLACEMENT (PUT), so line_items, when present, is the complete desired set: lines the platform omits are removed. Everything else is applied only when supplied, because a platform legitimately sends partial state on create and on each incremental step.

Ordering is load-bearing. Setting a shipping address resets Magento's selected shipping method (rates are address-dependent), so address must be written before the fulfillment option — otherwise a single PUT carrying both silently drops the selection.

ApplyResult interface

MemberTypeDescription
messagesUcpMessage[]

applyCheckoutInput function

async applyCheckoutInput(cartId: string, ctx: RequestContext, input: UcpCheckoutInput, cart: CheckoutCart | null): Promise<ApplyResult>

Apply input to the cart. Returns business-level messages; Magento transport/GraphQL failures surface as MagentoCallError for the caller to map (they are business outcomes too, just discovered by a throw).

emptyCart function

async emptyCart(cartId: string, ctx: RequestContext, cart: CheckoutCart | null): Promise<void>

Empty a cart — the closest Magento analogue to abandoning a session.

@magenxcommerce/engine/agentic/ucp/_lib/auth

packages/engine/src/agentic/ucp/_lib/auth.ts

Platform authentication + rate limiting for the UCP surface.

SECURITY: this is the ENTIRE authorization boundary for these routes. Unlike every other mutating path in this app, a UCP request carries no magenx_ct cookie and cannot solve a Turnstile challenge (there is no browser), so neither of the existing protections applies. What stands between the public internet and "create carts / set addresses / read prices on this store" is the caller's proof of identity, checked here — one of:

  1. An RFC 9421 request SIGNATURE made with a key the caller publishes in its own UCP-Agent profile (keys[]) — the spec's permissionless onboarding, and the default: any platform with a discoverable profile can transact, nothing is registered in advance, and the verified profile URL is its identity (./request-verify.ts).
  2. A pre-shared API key from UCP_PLATFORM_KEYS — the spec's other option, for platforms onboarded out of band. Optional.

A request with neither is refused (signature_missing). Rules:

  • Fail CLOSED. UCP_ENABLE unset ⇒ the surface is off, and callers get 404 (not 401) so a store that never opted in doesn't advertise an endpoint at all.
  • Compare keys in constant time, against every configured key, so a timing oracle can't recover a credential byte by byte.
  • Never accept the customer token cookie here. A UCP session is always a guest cart; there is no path from an agent credential to a customer's account.
  • Bind the credential to the profile it may speak for. The spec's Identity Binding rule: "Verifiers MUST confirm the authenticated principal is authorized to act on behalf of the profile identified in UCP-Agent." Without it, platform A's key could claim platform B's profile — and the order webhooks would then POST B's orders to whatever webhook_url that profile declares. UCP_PLATFORM_PROFILES maps each key label to the profiles it may claim, and a label with no binding is refused outright (fail closed, like everything else here).

The constant-time comparison, the key parsing and the rate-limit buckets are shared with ACP (../../_lib/platform-auth) — they were duplicated, and a duplicated security boundary is the one most expensive to let drift. What stays here is what is genuinely UCP's: the X-API-Key alternative, the required UCP-Agent profile, and this surface's error shapes.

Platform interface

MemberTypeDescription
labelstringWho the caller is, for logs, the rate-limit bucket and order ownership: the operator-assigned key label, or — for a signed request — the verified profile URL. Never a secret. A key label cannot contain ":" (the key format splits on it) and a URL always does, so the two never collide.
agentProfilestringThe UCP-Agent profile URI the caller identified itself with.

AuthResult type

type AuthResult = | { ok: true; platform: Platform } | { ok: false; status: 400 | 401 | 403 | 404 | 422 | 424 | 429 | 503; code: string; message: string; }

parseProfileUrl function

parseProfileUrl(raw: string): URL | null

Parse a profile URL into its canonical form, or null when it is not one.

Profiles are HTTPS-only (spec, Profile Requirements), and a URL carrying userinfo is refused rather than normalized: it is never a real profile and user@host is a classic way to make one host read as another. URL already lowercases the host and drops a default port; the fragment is stripped because it never reaches the server.

loadProfileBindings function

loadProfileBindings(onInvalid?: (label: string) => void): Map<string, ProfileBinding[]>

Parse UCP_PLATFORM_PROFILES — label=entry|entry,label2=entry — into the profiles each key label may claim.

An entry whose path is empty or / binds the whole origin; anything longer binds that one URL. Invalid entries are dropped (and so bind nothing — the safe direction), never widened into something that matches more. Parsed on every call, like the key list, so it is silent; onInvalid lets the once-only boot warning report what it dropped.

isProfileBound function

isProfileBound(label: string, profile: URL): boolean

True when the credential labelled label may act for profile.

isUcpSurfaceEnabled function

isUcpSurfaceEnabled(): boolean

True when the UCP surface is fully configured and may serve traffic.

BOTH conditions are the switch: the flag alone is not enough, because with no credential configured every operation refuses anyway. This is the ONE predicate every entry point must use — including the discovery profile.

It exists because the profile used to check only isUcpEnabled() while operations checked the flag AND the keys. A store with UCP_ENABLE=1 and no UCP_PLATFORM_KEYS therefore published a full profile — two transports, five operations — while every one of those operations 404'd. Advertising a surface that cannot be used is worse than advertising none: a platform concludes the merchant is broken. Observed on the live store, 2026-07-27.

Since request signatures (permissionless onboarding) became the default way in, the flag alone is that switch again: with it on, any platform that signs with a key from its profile can use the surface, so it is never advertised without being usable. API keys are an optional extra; any configured without a UCP_PLATFORM_PROFILES binding are reported once.

identify function

async identify(request: SignedRequest, profileFallback?: string | null): Promise<AuthResult>

Identify the caller of a UCP request: by signature when it carries one, by API key when it carries one of those, otherwise refused.

A signed request is never downgraded to the key path: if it carries Signature-Input, the signature decides. The profile that supplies the verifying key is the UCP-Agent profile (or, over MCP, the one in meta, which the body digest covers), so a verified request needs no binding — it proved control of that profile's key.

authenticate function

authenticate(headers: Headers, profileFallback?: string | null): AuthResult

Authenticate a UCP request by API key (the pre-shared path).

Order matters: the enabled check comes first so a disabled surface reveals nothing (404 regardless of what credential was presented). The profile binding comes last: it needs the matched key's label, and it is what makes the returned agentProfile trustworthy for everything downstream (negotiation fetches it, order webhooks deliver to what it declares).

profileFallback exists for the MCP binding, which carries the agent profile in the tool call's meta["ucp-agent.profile"] as well as the UCP-Agent header. It only ever supplies the profile — the CREDENTIAL is always read from the request headers, so this can never become a second way in. The profile identifies the caller; it does not authorize them.

checkRateLimit function

checkRateLimit(platformLabel: string): AuthResult | null

Best-effort per-platform rate limit.

See createRateLimiter for the per-instance caveat; the 429 body is built here because UCP's error shape is not ACP's.

resetRateLimits function

resetRateLimits(): void

Test seam: drop accumulated rate-limit state (and the once-only binding warning).

@magenxcommerce/engine/agentic/ucp/_lib/capabilities

packages/engine/src/agentic/ucp/_lib/capabilities.ts

The business capability registry — what this store implements, declared once.

Spec: https://ucp.dev/2026-08-25/specification/overview/

Two consumers must agree on it exactly: the /.well-known/ucp profile (what we advertise) and capability negotiation (what we intersect a platform's profile against, ./negotiation.ts). They used to be one inline object in the profile route, and a second copy here would be the drift this module exists to prevent: a capability advertised but never negotiated, or negotiated but never advertised.

extends is part of the registry rather than of negotiation because it is a property of the extension's schema, which only the business side knows for sure — a platform's profile may omit it, and the intersection still has to prune an extension whose parent did not survive.

CapabilityEntry interface

MemberTypeDescription
versionstring
specstring
schemastring
extends?string[]Parent capabilities, for an extension. Absent on a root capability.

CapabilityRegistry type

type CapabilityRegistry = Record<string, CapabilityEntry[]>

businessCapabilities function

businessCapabilities(): CapabilityRegistry

Every capability this business implements, in the profile's shape.

Order webhooks carry no config here: order.json defines one only for PLATFORMS (their webhook_url), see ./platform-profile.ts.

businessCapabilityRefs function

businessCapabilityRefs(): UcpCapabilityRefs

The registry reduced to { name: [{ version }] }, the response-envelope shape.

relevantCapabilities function

relevantCapabilities(root: string, negotiated?: UcpCapabilityRefs): UcpCapabilityRefs

The capabilities a response for operation type root must declare.

Spec, Response Capability Selection: only capabilities that are (1) in the negotiated intersection AND (2) relevant to the operation — the root capability itself, plus every extension whose extends names it. So a checkout response carries checkout + fulfillment, a cart response carries cart alone (not checkout), an order response carries order alone.

negotiated is the session's intersection. It is undefined only on paths that run without a platform request to negotiate against — the order webhook dispatcher, whose recipient declared the order capability by construction — and then the full business registry stands in for it.

@magenxcommerce/engine/agentic/ucp/_lib/cart-service

packages/engine/src/agentic/ucp/_lib/cart-service.ts

UCP cart capability — the four operations, binding-agnostic.

The REST routes (/api/ucp/carts/*) and the MCP tools (create_cart, get_cart, update_cart, cancel_cart) both call these and only render the outcome, the same split as catalog-service.ts. Magento writes go through the SAME applyCheckoutInput the checkout uses, restricted to what a cart carries (line items and buyer), so a cart line and a checkout line can never be reconciled by two different rules.

ResourceOutcome type

type ResourceOutcome = | { ok: true; body: T | UcpErrorResponse; status: 200 | 201 } /** Nothing to return: a protocol error (REST status, MCP tool error/-32602). */ | { ok: false; status: number; code: string; message: string; invalidParams: boolean; }

CartOutcome type

type CartOutcome = ResourceOutcome<UcpCart>

loadLiveCart function

async loadLiveCart(cartId: string, ctx: RequestContext): Promise< { ok: true; cart: CheckoutCart } | { ok: false; outcome: CartOutcome } >

Load a live cart: shape-checked, not canceled, and still an active quote.

Every "there is nothing here" — malformed id aside — collapses into not_found: an unknown id, a canceled cart, and a quote that already became an order all mean the same thing to a platform (start a new cart).

createCartSession function

async createCartSession(input: UcpCartInput, ctx: RequestContext): Promise<CartOutcome>

getCartSession function

async getCartSession(cartId: string, ctx: RequestContext): Promise<CartOutcome>

updateCartSession function

async updateCartSession(cartId: string, input: UcpCartInput, ctx: RequestContext): Promise<CartOutcome>

cancelCartSession function

async cancelCartSession(cartId: string, ctx: RequestContext): Promise<CartOutcome>

Cancel a cart: empty the quote and tombstone the id.

Magento has no "delete quote" over GraphQL, so — as for cancel_checkout — the quote is emptied. The tombstone is what makes "subsequent operations SHOULD return not_found" true; without it a canceled cart would read back as an empty one. It lives in the shared store (Redis when configured) for 30 days, well past Magento's own quote lifetime.

Returns the cart as it was, per the spec ("MUST return the cart state before deletion").

checkoutInputForCart function

checkoutInputForCart(body: UcpCheckoutInput, cart: CheckoutCart): UcpCheckoutInput

The part of a create_checkout body that still applies once cart_id names the cart. The spec: the business "MUST use cart contents (line_items, context, buyer) and MUST ignore overlapping fields in checkout payload".

So line_items always goes, and the buyer's email goes when the cart already has one. The rest of buyer stays: a cart stores only an email, so names and phone do not overlap — and the address step reads them. context has no cart copy to prefer (Magento keeps none), so it keeps selecting the store view, exactly as on every other request.

readCartId function

readCartId(body: UcpCheckoutInput): | { present: false } | { present: true; id: string } | { present: true; id: null }

Read cart_id off a create_checkout body: absent, a usable id, or invalid.

@magenxcommerce/engine/agentic/ucp/_lib/cart

packages/engine/src/agentic/ucp/_lib/cart.ts

Magento quote → UCP cart resource (the dev.ucp.shopping.cart capability).

A cart IS a Magento guest quote, exactly as a checkout session is, and its id is the same masked quote id. That is what makes cart → checkout conversion (create_checkout with cart_id) cheap and correct by construction: the checkout is the SAME quote, so

  • converting twice returns the same session (the spec's "MUST return the existing checkout" rule), and
  • edits made during checkout are already "reflected back to the cart" — there is nothing to sync.

Pure, like session.ts: everything environmental comes in via options.

CartOptions interface

MemberTypeDescription
taxModeSessionOptions["taxMode"]
fallbackCurrencystring
continueUrlstring
linksUcpLink[]
messages?UcpMessage[]
negotiated?UcpCapabilityRefsThe negotiated intersection; the envelope declares cart's relevant subset.

buildCart function

buildCart(cart: CheckoutCart, options: CartOptions): UcpCart

Project a Magento quote onto the UCP cart resource.

cartNotFound function

cartNotFound(continueUrl?: string, negotiated?: UcpCapabilityRefs): UcpErrorResponse

orderNotFound function

orderNotFound(negotiated?: UcpCapabilityRefs): UcpErrorResponse

@magenxcommerce/engine/agentic/ucp/_lib/catalog-fetch

packages/engine/src/agentic/ucp/_lib/catalog-fetch.ts

Resolving SKUs to Magento products — shared by the catalog capability's lookup operations and by checkout's add-to-cart (for parent_sku).

fetchProductsForSkus function

async fetchProductsForSkus(storeCode: string, ids: string[]): Promise<MagentoCatalogProduct[]>

Fetch the products skus name, by product SKU or variant SKU.

One SKU-filter read resolves every SKU that is a visible product's own SKU. A configurable CHILD is normally "Not Visible Individually", so that filter cannot see it; each SKU still unresolved is then looked up by search, which indexes children's SKUs onto their parent. Callers accept only an exact SKU match from those results, so a fuzzy search hit never resolves.

ids may also be custom-option variant ids; those resolve through their SKU.

resolveParentSkus function

async resolveParentSkus(storeCode: string, skus: string[]): Promise<Map<string, string>>

skus that are configurable children, mapped to their parent SKU.

@magenxcommerce/engine/agentic/ucp/_lib/catalog-route

packages/engine/src/agentic/ucp/_lib/catalog-route.ts

Shared REST handler for the three UCP catalog operations.

Same pipeline as checkout — authenticate, rate limit, negotiate, parse — through the same guard, so the catalog is behind exactly the platform credential the checkout is, never a weaker door. See ../_lib/catalog-service.ts for the operations themselves.

handleCatalogRequest function

async handleCatalogRequest(request: Request, capability: string, operation: ( body: unknown, negotiated?: UcpCapabilityRefs ) => Promise<CatalogOutcome>): Promise<NextResponse>

capability is the operation's own: search, or lookup (lookup + get product).

@magenxcommerce/engine/agentic/ucp/_lib/catalog-service

packages/engine/src/agentic/ucp/_lib/catalog-service.ts

UCP catalog capability — the three operations, binding-agnostic.

Both the REST routes (/api/ucp/catalog/*) and the MCP tools (search_catalog, lookup_catalog, get_product) call these and only render the outcome differently, so neither transport can drift into a second implementation. The mapping rules live in the pure ./catalog.ts; this module adds the Magento reads and the response envelopes.

CatalogOutcome type

type CatalogOutcome = | { ok: true; body: Record<string, unknown> } /** Nothing to return: a protocol error (REST status, MCP JSON-RPC error). */ | { ok: false; status: number; code: string; message: string; invalidParams: boolean; }

searchCatalog function

async searchCatalog(input: unknown, negotiated?: UcpCapabilityRefs): Promise<CatalogOutcome>

The three operations take the caller's negotiated capability intersection (see ./negotiation.ts) only to declare it in the response envelope.

lookupCatalog function

async lookupCatalog(input: unknown, negotiated?: UcpCapabilityRefs): Promise<CatalogOutcome>

getProduct function

async getProduct(input: unknown, negotiated?: UcpCapabilityRefs): Promise<CatalogOutcome>

@magenxcommerce/engine/agentic/ucp/_lib/catalog

packages/engine/src/agentic/ucp/_lib/catalog.ts

UCP catalog capability — the pure layer: request validation, Magento product → UCP product mapping, lookup correlation and get_product option selection.

Spec: https://ucp.dev/2026-08-25/specification/shopping/catalog/

Nothing here imports Apollo, Next or the @/ alias, so every rule below is directly unit-testable; the Magento read lives in ./catalog-service.ts.

IDENTIFIERS ARE SKUs, and that is the contract with checkout: the spec says a catalog variant id "should match the item ID expected by checkout", and checkout's line_items[].item.id is a SKU (see ./apply.ts). So:

  • product id = the product's SKU (a configurable's PARENT SKU)
  • variant id = the purchasable SKU (a configurable's CHILD SKU; for a simple product, the same SKU as the product), plus the chosen values when the product has required custom options (SKU~<option>.<value>, see ./custom-options)

A platform can pass either straight into create_checkout.

DEFAULT_SEARCH_LIMIT const

const DEFAULT_SEARCH_LIMIT = 10

Page size when the platform sends none (the spec RECOMMENDS 10).

MAX_SEARCH_LIMIT const

const MAX_SEARCH_LIMIT = 50

Largest page served; a bigger limit is clamped, which the spec allows.

MAX_LOOKUP_IDS const

const MAX_LOOKUP_IDS = 20

Most identifiers accepted by one lookup. The spec asks for at least 10; each identifier that isn't a visible product's own SKU costs a search, so the cap bounds the fan-out an agent can trigger with one call.

MAX_QUERY_LENGTH const

const MAX_QUERY_LENGTH = 256

Longest search query accepted, in characters.

MagentoCatalogVariant interface

MemberTypeDescription
attributes?Array<{ code?: string | null; value_index?: number | null; label?: string | null; } | null> | null
product?{ uid?: string | null; sku?: string | null; name?: string | null; stock_status?: string | null; image?: { url?: string | null; label?: string | null } | null; price_range?: { minimum_price?: MagentoPrice | null } | null; } | null

MagentoCatalogProduct interface

MemberTypeDescription
__typename?string
uid?string | null
sku?string | null
name?string | null
url_key?string | null
stock_status?string | null
rating_summary?number | null
review_count?number | null
description?{ html?: string | null } | null
image?{ url?: string | null; label?: string | null } | null
media_gallery?Array<{ url?: string | null; label?: string | null; position?: number | null; disabled?: boolean | null; } | null> | null
categories?Array<{ name?: string | null; url_path?: string | null; } | null> | null
price_range?{ minimum_price?: MagentoPrice | null; maximum_price?: MagentoPrice | null; } | null
configurable_options?Array<{ attribute_code?: string | null; label?: string | null; values?: Array<{ value_index?: number | null; label?: string | null; } | null> | null; } | null> | null
variants?Array<MagentoCatalogVariant | null> | null
options?Array<MagentoCustomOption | null> | nullCustom options (CustomizableProductInterface); see ./custom-options.

UcpPrice interface

MemberTypeDescription
amountnumber
currencystring

UcpSelectedOption interface

MemberTypeDescription
namestring
labelstring

UcpInputCorrelation interface

MemberTypeDescription
idstring
match"exact" | "featured"

UcpCatalogVariant interface

MemberTypeDescription
idstring
skustring
titlestring
description{ plain: string }
url?string
priceUcpPrice
list_price?UcpPrice
availability{ available: boolean; status: "in_stock" | "out_of_stock" }
options?UcpSelectedOption[]
media?UcpMedia[]
inputs?UcpInputCorrelation[]

UcpMedia interface

MemberTypeDescription
type"image"
urlstring
alt_text?string

UcpOptionValue interface

MemberTypeDescription
labelstring
available?boolean
exists?boolean

UcpCatalogProduct interface

MemberTypeDescription
idstring
handle?string
titlestring
description{ plain: string }
url?string
categories?Array<{ value: string; taxonomy: "merchant" }>
price_range{ min: UcpPrice; max: UcpPrice }
list_price_range?{ min: UcpPrice; max: UcpPrice }
media?UcpMedia[]
options?Array<{ name: string; values: UcpOptionValue[] }>
selected?UcpSelectedOption[]
variantsUcpCatalogVariant[]
rating?{ value: number; scale_min: number; scale_max: number; count: number; }

UcpCatalogMessage interface

MemberTypeDescription
type"error" | "warning" | "info"
codestring
contentstring
severity?"recoverable" | "unrecoverable"
path?string

CatalogRenderContext interface

What every operation needs from the request context to render URLs.

MemberTypeDescription
storefrontBasestringAbsolute storefront origin plus locale, e.g. https://shop.example/en.
currencystringPresentment currency to fall back on when Magento omits one.

CatalogFilters interface

MemberTypeDescription
categoriesstring[]
priceMinnumber | nullMinor units, in the presentment currency.
priceMaxnumber | null

SearchRequest interface

MemberTypeDescription
querystring | null
filtersCatalogFilters
pagenumber
limitnumber

LookupRequest interface

MemberTypeDescription
idsstring[]
filtersCatalogFilters

GetProductRequest interface

MemberTypeDescription
idstring
selectedUcpSelectedOption[]
preferencesstring[]
filtersCatalogFilters

CatalogRequestError interface

A request the platform got wrong: REST 400, MCP -32602.

MemberTypeDescription
codestring
messagestring

Parsed type

type Parsed = | { ok: true; value: T } | { ok: false; error: CatalogRequestError }

encodeCursor function

encodeCursor(page: number): string

Opaque pagination cursor: the next Magento page, base64url-encoded.

decodeCursor function

decodeCursor(cursor: string): number | null

parseSearchRequest function

parseSearchRequest(body: unknown): Parsed<SearchRequest>

parseLookupRequest function

parseLookupRequest(body: unknown): Parsed<LookupRequest>

parseGetProductRequest function

parseGetProductRequest(body: unknown): Parsed<GetProductRequest>

htmlToPlain function

htmlToPlain(html: string | null | undefined, max = MAX_DESCRIPTION_LENGTH): string

Merchant HTML → plain text.

Only plain is published: the spec lets a platform render html, but it is merchant-authored markup (page-builder output included), so sending it would make every platform's sanitizer part of this store's security boundary.

allVariants function

allVariants(item: MagentoCatalogProduct, ctx: CatalogRenderContext): UcpCatalogVariant[]

Every purchasable variant of a product, before any filtering.

The product's own variants (see baseVariants), each expanded into one variant per combination of its required custom-option values. A product with a required option agents cannot fill keeps its variants, all unavailable.

toSearchProduct function

toSearchProduct(item: MagentoCatalogProduct, filters: CatalogFilters, ctx: CatalogRenderContext): UcpCatalogProduct | null

A search result: every variant the filters admit, the featured one first. Null when the filters exclude every variant (the product is then dropped).

LookupResult interface

MemberTypeDescription
productsUcpCatalogProduct[]
messagesUcpCatalogMessage[]

resolveLookup function

resolveLookup(ids: string[], items: MagentoCatalogProduct[], filters: CatalogFilters, ctx: CatalogRenderContext): LookupResult

Resolve ids against the products Magento returned.

  • An id equal to a product's own SKU resolves to that product; the server picks the featured variant (featured) — except for a product whose SKU IS its only variant's id (a simple product without required custom options), where the match is exact.
  • An id equal to any other variant id — a configurable child's SKU, or a custom-option variant's id — resolves to that variant (exact).

Each product is returned once, carrying every variant some id resolved to, each with its inputs. Unresolved ids are reported as not_found info.

unresolvedIds function

unresolvedIds(ids: string[], items: MagentoCatalogProduct[]): string[]

Which of ids the Magento items do not already resolve (to try by search). Pass SKUs: a custom-option variant id resolves through its SKU.

GetProductResult type

type GetProductResult = | { ok: true; product: UcpCatalogProduct } | { ok: false; message: UcpCatalogMessage }

buildDetailProduct function

buildDetailProduct(request: GetProductRequest, item: MagentoCatalogProduct | null, ctx: CatalogRenderContext): GetProductResult

Full detail for one product, narrowed to the effective option selection.

item is the product request.id resolved to — as its own SKU or as one of its variants' — or null when it resolved to nothing.

parentSkusFor function

parentSkusFor(skus: string[], items: MagentoCatalogProduct[]): Map<string, string>

Which of skus are configurable CHILDREN, mapped to their parent SKU.

Checkout adds items by SKU. A child added on its own lands in the cart as a standalone simple product, not as the configurable with its options chosen, so the add has to name the parent too (parent_sku), exactly as the storefront's own add-to-cart does. A SKU that is itself a visible product in items is left alone: it is sellable as it is.

findProductFor function

findProductFor(id: string, items: MagentoCatalogProduct[]): MagentoCatalogProduct | null

The product id names — by its own SKU, one of its variants' SKUs, or a custom-option variant id built on either.

@magenxcommerce/engine/agentic/ucp/_lib/complete

packages/engine/src/agentic/ucp/_lib/complete.ts

Complete Checkout — the decision layer, shared by REST and MCP.

This is the only place in the surface that moves money, so the rules it encodes are written out rather than implied:

  • NO HANDLER DECLARED ⇒ escalate, exactly as before. Delegated payment is opt-in; with payment_handlers empty this returns requires_escalation and reports any submitted instrument as uncharged.
  • NEVER REPORT AN ORDER AS PAID WITHOUT ASKING STRIPE. Magento returns a client secret whether the intent succeeded, needs 3DS, or was declined. Treating "order placed" as "money taken" would tell a platform the purchase is done when the buyer still has to authenticate.
  • AN AMBIGUOUS FAILURE IS NOT A FAILED PAYMENT. If placeOrder throws, we cannot know whether Magento charged before dying. Saying "declined" would invite a retry that double-charges, so the outcome is reported as unresolved and the idempotency claim is NOT released.
  • ONE CHARGE PER IDEMPOTENCY KEY. Claimed before any chargeable work and released only on failures that provably never reached Stripe.

CompleteOutcome interface

What complete decided, in transport-neutral terms.

status is the UCP status to report; messages explain it; order is set only when an order genuinely exists.

MemberTypeDescription
statusUcpStatus
messagesUcpMessage[]
order?UcpOrderConfirmation

CompleteRecord interface

What one idempotency key holds.

outcome is written the moment the charge resolves, because that is the point after which a retry must never charge again. response is the RENDERED checkout the binding sent back, filled in a moment later by rememberCompleteResponse.

The two are separate because they become knowable at different times, and the later one is the more useful: placeOrder deactivates the quote, so a retry cannot re-read the cart to rebuild a response — replaying the stored one is the only way to honour the binding's "store for 24h+, replay the result" requirement rather than answering a retry with a 404.

MemberTypeDescription
outcomeCompleteOutcome
response?UcpCheckout

peekCompleteResponse function

async peekCompleteResponse(sessionId: string, idempotencyKey: string): Promise<UcpCheckout | null>

The response a previous attempt with this key already produced, if any.

Callers check this BEFORE loading the cart — see the note on CompleteRecord.

rememberCompleteResponse function

async rememberCompleteResponse(sessionId: string, idempotencyKey: string, response: UcpCheckout): Promise<void>

Upgrade a settled record with the response that was actually sent.

Never called for an attempt that did not reach settle — it would resurrect a key the flow deliberately released.

escalate function

escalate(payment: UcpPayment | undefined): CompleteOutcome

The escalation outcome — no handler declared, nothing charged.

completeWithDelegatedPayment function

async completeWithDelegatedPayment(sessionId: string, ctx: RequestContext, payment: UcpPayment | undefined, idempotencyKey: string, cart: CheckoutCart, platform: string, agentProfile?: string): Promise<CompleteOutcome>

Charge the submitted instrument and place the order.

idempotencyKey is required by both bindings before reaching here.

cart (the pre-complete snapshot) and platform (the credential label) are recorded against the placed order so the order capability can serve it back to that platform — see ./order-service.ts. agentProfile (the caller's UCP-Agent profile) is recorded too: its order capability names the webhook_url order events are pushed to — see ./order-webhooks.ts.

@magenxcommerce/engine/agentic/ucp/_lib/constants

packages/engine/src/agentic/ucp/_lib/constants.ts

Protocol constants for the UCP (Universal Commerce Protocol) surface.

Spec: https://ucp.dev/2026-08-25/specification/shopping/checkout/

The whole surface is OFF unless UCP_ENABLE=1 AND at least one platform credential is configured (see _lib/auth.ts). When off, every route — the /.well-known/ucp profile included — 404s, so a store that has not opted in does not advertise an agentic checkout at all.

UCP_VERSION const

const UCP_VERSION = "2026-08-25"

Protocol + capability version we implement (YYYY-MM-DD, per the spec).

UCP_SPEC_BASE const

const UCP_SPEC_BASE = `https://ucp.dev/${UCP_VERSION}`

Base URL of the published specification for this version.

SHOPPING_SERVICE const

const SHOPPING_SERVICE = "dev.ucp.shopping"

Service and capability identifiers declared in /.well-known/ucp.

CHECKOUT_CAPABILITY const

const CHECKOUT_CAPABILITY = "dev.ucp.shopping.checkout"

FULFILLMENT_CAPABILITY const

const FULFILLMENT_CAPABILITY = "dev.ucp.shopping.fulfillment"

CART_CAPABILITY const

const CART_CAPABILITY = "dev.ucp.shopping.cart"

Pre-purchase basket building, converted to a checkout via cart_id.

ORDER_CAPABILITY const

const ORDER_CAPABILITY = "dev.ucp.shopping.order"

Post-purchase order state (Get Order), for orders placed through complete.

CATALOG_LOOKUP const

const CATALOG_LOOKUP = "dev.ucp.shopping.catalog.lookup"

DISCOUNT_CAPABILITY const

const DISCOUNT_CAPABILITY = "dev.ucp.shopping.discount"

Coupon codes and applied discounts, on both cart and checkout.

UCP_ENDPOINT_PATH const

const UCP_ENDPOINT_PATH = "/api/ucp"

Base path the REST binding is served from. The profile publishes this as services[].endpoint; the spec's OpenAPI paths (/checkout-sessions, …) are appended to it by the calling platform.

MAX_BODY_BYTES const

const MAX_BODY_BYTES = 128 * 1024

Request body cap. Agent traffic is unauthenticated by cookie; keep it small.

MAX_LINE_ITEMS const

const MAX_LINE_ITEMS = 100

Upper bound on line items in one create/update call.

isUcpEnabled function

isUcpEnabled(): boolean

True when the operator has switched the UCP surface on.

@magenxcommerce/engine/agentic/ucp/_lib/context

packages/engine/src/agentic/ucp/_lib/context.ts

Environment for a UCP request: which store view to talk to, the legal links the spec requires, and the human handoff URL.

Server-only (it reads the injected shop configuration, ../../_lib/config.ts), which is also why the pure mappers in session.ts/address.ts take their configuration as arguments instead of reaching for it here.

RequestContext interface

MemberTypeDescription
localestring
storeCodestring
baseUrlstring
currencystring
taxModeProductPriceDisplay
linksUcpLink[]
capabilities?UcpCapabilityRefsThe capability intersection negotiated with the caller's profile (see ./negotiation.ts). Undefined only where no platform request is being answered (the order webhook dispatcher); builders then fall back to the business registry. Responses declare the subset relevant to their operation — ./capabilities.ts relevantCapabilities.

resolveLocale function

resolveLocale(language: string | undefined): string

Map a UCP context.language hint onto one of our store views.

Each locale is 1:1 with a Magento store view (the Store header), so this also selects the catalog, prices and currency the agent sees. Unknown or absent languages fall back to the default store rather than erroring — a platform shopping in an unsupported language should still be able to buy.

resolveRequestContext function

resolveRequestContext(ucpContext?: UcpContext): RequestContext

Resolve everything a handler needs from the platform's context hint.

buildContinueUrl function

buildContinueUrl(ctx: RequestContext, sessionId: string): string

Human handoff URL for a session.

Locale-prefixed on purpose: this app ships no locale middleware, so a locale-less path resolves its first segment as [locale] and 404s (the same trap the Stripe/PayPal return URLs hit — see CLAUDE.md).

@magenxcommerce/engine/agentic/ucp/_lib/custom-options

packages/engine/src/agentic/ucp/_lib/custom-options.ts

Required custom options as variant dimensions.

A Magento product can carry per-product "custom options" (a PACKAGING radio, a gift-wrap select) on top of, or instead of, configurable attributes. When one is REQUIRED, addProductsToCart refuses the bare SKU ("The product's required option(s) weren't entered"), so an agent that only ever sees SKUs cannot buy the product at all.

UCP has no custom-option concept, but it has variants: a purchasable combination of option values, each with its own id and price. So every required SELECT-type option becomes one more option dimension, and each combination of its values becomes a variant whose id carries the choice:

    010-02157-21~780.1559      SKU, then ~<option_id>.<option_type_id> per choice

The id is what checkout's line_items[].item.id receives back, and is split again here to send Magento the SKU plus selected_options — the same value uids the storefront's product page sends.

Required TEXT-type options (field, area, date, file) have no finite set of values to enumerate; a product carrying one is not purchasable by an agent.

Dependency-free on purpose: the pure catalog mappers and the shared line-item reconciliation (../../_lib/line-items) both import it.

MagentoCustomOptionValue interface

MemberTypeDescription
uid?string | null
title?string | null
price?number | null
price_type?string | null
sort_order?number | null

MagentoCustomOption interface

MemberTypeDescription
__typename?string
uid?string | null
title?string | null
required?boolean | null
sort_order?number | null
values?Array<MagentoCustomOptionValue | null> | nullPresent on the select types only (drop-down, radio, checkbox, multiple).

CustomChoice interface

One chosen value of one custom option.

MemberTypeDescription
optionIdnumber
valueIdnumber

CustomAxisValue interface

MemberTypeDescription
namestringThe option's title, i.e. the UCP option name.
labelstring
pricenumber
priceTypestring

CustomAxis interface

MemberTypeDescription
namestring
valuesCustomAxisValue[]

CustomOptionModel type

type CustomOptionModel = | { ok: true; axes: CustomAxis[] } /** A required option agents cannot fill: the product is not purchasable. */ | { ok: false }

CHOICE_SEPARATOR const

const CHOICE_SEPARATOR = "~"

Separates the SKU from each <option_id>.<option_type_id> choice.

MAX_CUSTOM_COMBINATIONS const

const MAX_CUSTOM_COMBINATIONS = 50

Most custom-option combinations expanded per product. Above it the product is treated as not purchasable rather than flooding a response with variants.

choiceFromUid function

choiceFromUid(uid: string | null | undefined): CustomChoice | null

Magento's value uid: base64 of custom-option/<option_id>/<option_type_id>.

uidForChoice function

uidForChoice(choice: CustomChoice): string

customOptionModel function

customOptionModel(options: Array<MagentoCustomOption | null> | null | undefined): CustomOptionModel

Required select-type options as variant dimensions, in Magento's order.

combinations function

combinations(axes: CustomAxis[]): CustomAxisValue[][]

Every combination of one value per axis, first axis varying slowest.

variantIdFor function

variantIdFor(sku: string, choices: CustomChoice[]): string

The variant id for sku with choices. Canonical — choices in option-id order — so the catalog and a cart line read back from Magento agree on it.

splitVariantId function

splitVariantId(id: string): { sku: string; choices: CustomChoice[]; }

A variant id back into its SKU and custom-option choices.

An id without a well-formed choice suffix is a plain SKU.

@magenxcommerce/engine/agentic/ucp/_lib/discounts

packages/engine/src/agentic/ucp/_lib/discounts.ts

The UCP discount extension (dev.ucp.shopping.discount) on Magento coupons and cart price rules.

Spec: https://ucp.dev/2026-08-25/specification/shopping/extensions/discount

In: discounts.codes, the COMPLETE desired set (replaces; [] clears). Magento's storefront GraphQL holds one coupon per quote, so the first code is applied and every further one is reported as discount_code_combination_disallowed rather than silently dropped.

Out: discounts.codes (the coupons Magento kept) and discounts.applied, one entry per cart rule Magento reports in prices.discounts, with its per-line allocations from each item's own prices.discounts.

A rejected code is a WARNING, as the spec's examples model it: the cart is still valid without it, so the rest of the update goes ahead.

rejectionCode function

rejectionCode(magentoMessage: string): string

Magento's coupon rejection text → the spec's rejection code (shared with ACP).

discountRejection function

discountRejection(code: string, index: number, magentoMessage: string): UcpMessage

A Magento coupon rejection as a UCP message at $.discounts.codes[index].

applyDiscountCodes function

async applyDiscountCodes(cartId: string, ctx: RequestContext, submitted: unknown): Promise<UcpMessage[]>

Make the cart's coupons match submitted (discounts.codes).

Reads the applied coupon first so an unchanged set — a platform re-sending its codes on every full-replacement update — costs no write and does not reset Magento's totals. Transport failures surface as MagentoCallError for the caller to map, as every other apply step does.

isDiscountNegotiated function

isDiscountNegotiated(negotiated?: UcpCapabilityRefs): boolean

True when the response may carry discounts (negotiated, or no negotiation).

itemsDiscountMinor function

itemsDiscountMinor(cart: CheckoutCart, currency: string): number

The part of the cart's discount Magento allocated to line items, in minor units. What remains of the cart total (shipping discounts) is order-level.

buildDiscounts function

buildDiscounts(cart: CheckoutCart, currency: string): UcpDiscounts | undefined

The response discounts object, or undefined when there is nothing to report.

@magenxcommerce/engine/agentic/ucp/_lib/errors

packages/engine/src/agentic/ucp/_lib/errors.ts

Magento error text → UCP messages[] entries.

UCP draws a hard line between PROTOCOL errors (bad auth, malformed body → non-2xx with a code/content body) and BUSINESS outcomes (out of stock, undeliverable address, declined payment → HTTP 200 with the checkout resource and a messages[] entry). Everything Magento reports about a cart is the second kind, so it is mapped here rather than thrown.

The severity drives what the platform does next: recoverable — platform fixes it over the API and retries requires_buyer_input — needs data the API can't carry; hand off to a human requires_buyer_review— complete, but a human must authorize unrecoverable — the session is dead; start over

Magento's messages are English admin-ish strings with no stable error codes, so matching is by pattern. Keep the list ordered most-specific-first and prefer a conservative fallback over a confident wrong classification.

classifyMagentoError function

classifyMagentoError(message: string): Classification

Classify one Magento error message into a UCP code + severity.

toUcpErrorMessages function

toUcpErrorMessages(messages: ReadonlyArray<string>, path?: string): UcpMessage[]

Build UCP error messages from raw Magento error strings.

classifyStripeError function

classifyStripeError(error: StripeCallError): Classification

Classify a Stripe failure, most specific signal first.

stripeErrorMessage function

stripeErrorMessage(error: StripeCallError): UcpMessage

A Stripe failure as a UCP message, pathed at the offending instrument.

hasUnrecoverable function

hasUnrecoverable(messages: ReadonlyArray<UcpMessage>): boolean

True when any message in the list is terminal for the session.

@magenxcommerce/engine/agentic/ucp/_lib/handler

packages/engine/src/agentic/ucp/_lib/handler.ts

The shared pipeline every UCP route runs: authenticate → rate limit → negotiate → parse, then a single place that turns a Magento cart into the HTTP response.

Keeping this in one module is what stops the five routes from drifting on the things that must never differ: the auth boundary, the error taxonomy, and the shape of a 200.

GuardOk interface

MemberTypeDescription
oktrue
requestIdstring | null
platformPlatform
bodyUcpCheckoutInput
ctxRequestContext

GuardResult type

type GuardResult = GuardOk | { ok: false; response: NextResponse }

UcpFailure interface

A binding-agnostic failure: status + code + message, not yet rendered.

MemberTypeDescription
statusnumber
codestring
messagestring
continueUrl?stringSet on negotiation failures, which the spec answers with a fallback web experience: the storefront the agent can hand the buyer to.

AuthorizeResult type

type AuthorizeResult = | { ok: true; platform: Platform } | { ok: false; failure: UcpFailure }

AdmitResult type

type AdmitResult = | { ok: true; platform: Platform; capabilities: UcpCapabilityRefs } | { ok: false; failure: UcpFailure }

isDiscoveryFailure function

isDiscoveryFailure(failure: UcpFailure): boolean

True for a failure the spec reports as a UCP discovery/version error.

authorize function

async authorize(request: SignedRequest, profileFallback?: string | null): Promise<AuthorizeResult>

The authorization decision, with no transport rendering attached.

Shared by BOTH bindings (REST routes via guard, MCP via its route) so the security boundary is decided in exactly one place — an MCP endpoint that re-implemented this would be a second, weaker door onto the same carts.

request carries the raw body because a signature's Content-Digest is checked against it (see ./request-verify.ts). profileFallback lets MCP supply the agent profile from the tool call's meta; a credential or signature still comes from headers only (see identify).

admit function

async admit(request: SignedRequest, requires: string | null, profileFallback?: string | null): Promise<AdmitResult>

The whole admission decision: authorize, then negotiate with the caller's profile (see ./negotiation.ts). Shared by both bindings for the reason authorize is.

Negotiation runs only once the caller is authenticated and within its rate limit. For a signed caller the profile was already fetched to find its key, so negotiation reads it from the cache.

requires is the root capability of the operation (dev.ucp.shopping. checkout for every checkout operation, …), or null for protocol-level MCP methods that return no UCP resource — those still get the version check.

failureResponse function

failureResponse(failure: UcpFailure, requestId: string | null): NextResponse

REST rendering of an admission failure.

guard function

async guard(request: Request, requires: string, readBody = true): Promise<GuardResult>

Admit and parse a REST request.

requires is the operation's root capability (see admit). readBody is false for GET/DELETE-shaped operations that carry no payload.

The body is read (as raw bytes) BEFORE admission, because a signature is verified against those exact bytes; it is parsed only after.

RespondOptions interface

MemberTypeDescription
requestIdstring | null
httpStatus?200 | 201
messages?UcpMessage[]
statusOverride?UcpStatus
order?UcpOrderConfirmation
delegatedPayment?boolean

renderCheckout function

renderCheckout(cart: CheckoutCart, ctx: RequestContext, options: RespondOptions): UcpCheckout

Project a cart onto the checkout resource, without wrapping it in a response.

Split out from respond for the complete route, which has to keep the rendered resource (to store it against the idempotency key) as well as send it — see rememberCompleteResponse.

respond function

respond(cart: CheckoutCart, ctx: RequestContext, options: RespondOptions): NextResponse

Render a cart as a UCP checkout response.

fetchSessionCart function

async fetchSessionCart(sessionId: string, ctx: RequestContext): Promise<{ ok: true; cart: CheckoutCart } | { ok: false; failure: UcpFailure }>

Load a session's cart, as a binding-agnostic result.

A cart Magento no longer knows about is an ADDRESSING failure (the session id points at nothing) rather than a cart problem, so it can't be reported as a checkout resource — there is no resource. Both bindings therefore surface it as a failure, distinguished by code: checkout_not_found when the quote is gone or dead, upstream_error when Magento itself is unreachable.

loadCart function

async loadCart(sessionId: string, ctx: RequestContext, requestId: string | null): Promise<{ ok: true; cart: CheckoutCart } | { ok: false; response: NextResponse }>

REST rendering of fetchSessionCart.

respondWithFailure function

respondWithFailure(error: unknown, ctx: RequestContext, requestId: string | null, cart: CheckoutCart | null): NextResponse

Turn a thrown Magento failure into a response.

Business outcomes must come back as HTTP 200 with the checkout resource so the platform can reason about (and repair) the cart — that is only possible when we still hold a cart to render; otherwise it degrades to a protocol error.

@magenxcommerce/engine/agentic/ucp/_lib/http

packages/engine/src/agentic/ucp/_lib/http.ts

Request/response plumbing shared by the five UCP REST operations.

The spec splits failures in two, and this module keeps that split honest:

  PROTOCOL errors  → non-2xx with `{ code, content }` (bad auth, malformed
                     body, unknown session). The caller did something wrong.
  BUSINESS outcomes→ HTTP 200 with the full checkout resource and a
                     `messages[]` entry (out of stock, address rejected).
                     The caller did nothing wrong; the cart has a problem.

Returning a business outcome as a 4xx is the single easiest way to break an agent platform, because it discards the resource it needs to reason about.

ucpResponse function

ucpResponse(body: unknown, status: number, headers: Record<string, string> = {}): NextResponse

Every UCP response goes out through here, REST and MCP alike, so it is signed when a signing key is configured (see ./signing.ts).

The body is serialized exactly once and that string is both digested and sent — NextResponse.json would serialize it separately. no-transform stops Next's compression (and any compliant proxy) from gzipping the body, which would change the bytes Content-Digest covers. A disabled surface is never signed: its 404 must not reveal that a signing key exists.

readRequestId function

readRequestId(headers: Headers): string | null

Read the caller's Request-Id, sanitized for safe echoing into a header.

protocolError function

protocolError(status: number, code: string, content: string, requestId: string | null = null, continueUrl?: string): NextResponse

A protocol-level error response (non-2xx).

ucp.status is set explicitly: the envelope defaults it to "success", so an error body that omits it declares itself successful. Success responses leave it off and take the default.

continueUrl is the spec's fallback web experience, sent with discovery and version failures (profile_unreachable, version_unsupported, …) so an agent can still hand the buyer to the storefront.

capabilitiesIncompatibleBody function

capabilitiesIncompatibleBody(content: string, continueUrl: string)

The spec's capabilities_incompatible body: the profile was valid, but the operation's capability is not in the intersection.

A negotiation failure is a BUSINESS outcome, not a transport error, so it rides a 200 as a UCP error response (an MCP result, not a JSON-RPC error), with an empty capability set and the storefront as the way out.

capabilitiesIncompatibleResponse function

capabilitiesIncompatibleResponse(content: string, continueUrl: string, requestId: string | null = null): NextResponse

REST rendering of capabilitiesIncompatibleBody: HTTP 200.

checkoutResponse function

checkoutResponse(checkout: UcpCheckout, status: 200 | 201 = 200, requestId: string | null = null): NextResponse

A successful checkout resource response.

resourceResponse function

resourceResponse(body: Record<string, unknown>, requestId: string | null = null): NextResponse

A successful non-checkout resource (catalog responses).

outcomeResponse function

outcomeResponse<T>(outcome: ResourceOutcome<T>, requestId: string | null): NextResponse

Render a cart/order operation's outcome. A resource and the spec's error_response (e.g. not_found) are both business outcomes and ride 2xx; only "no resource could be addressed at all" is a protocol error.

runOutcome function

async runOutcome<T>(operation: () => Promise<ResourceOutcome<T>>, requestId: string | null, logLabel: string): Promise<NextResponse>

Run a cart/order operation, rendering an unexpected throw as a 500.

BodyResult type

type BodyResult = | { ok: true; value: unknown } | { ok: false; code: string; message: string }

RawBodyResult type

type RawBodyResult = | { ok: true; bytes: Buffer } | { ok: false; code: string; message: string }

readRawBody function

async readRawBody(request: Request): Promise<RawBodyResult>

Read the request body as raw bytes, capped at MAX_BODY_BYTES.

Raw, because a signed request's Content-Digest is over the exact bytes sent: decoding to a string first would silently "repair" invalid UTF-8 and the digest would then be checked against bytes the platform never sent.

parseJsonBody function

parseJsonBody(bytes: Buffer): BodyResult

Parse raw body bytes as JSON.

An empty body is valid (POST /checkout-sessions with no line items is a legal way to open an empty session), and parses to {}.

readJsonBody function

async readJsonBody(request: Request): Promise<BodyResult>

Read and parse a JSON request body, capped at MAX_BODY_BYTES.

@magenxcommerce/engine/agentic/ucp/_lib/idempotency

packages/engine/src/agentic/ucp/_lib/idempotency.ts

Replay protection for UCP's complete.

The store itself is shared with ACP — see ../../_lib/idempotency.ts for the three-layer reasoning and the Redis/in-memory split. This module only binds it to UCP's keyspace.

It used to be in-memory only, with a comment accepting that as a correctness limitation. It was worse than that: behind several replicas a retried complete routed to a second process missed the cache entirely and could charge a second card, leaving Stripe's own Idempotency-Key and Magento's quote deactivation as the only backstops. Pointing UCP at the same shared store ACP already used closes that.

claim const

const claim = store.claim

peek const

const peek = store.peek

settle const

const settle = store.settle

release const

const release = store.release

resetIdempotency function

resetIdempotency(): void

Test seam: drop accumulated in-memory state and any cached Redis client.

cartTombstones const

const cartTombstones

Canceled-cart tombstones (cart capability). Not idempotency at all, but the same shape of record — "this id is settled; answer accordingly" — so it rides the same store under its own prefix rather than growing a second one.

orderRecords const

const orderRecords

Which platform placed which order (order capability). Written by complete, read by Get Order — see ./order-service.ts. Kept for a year: long enough for returns and refunds, the post-purchase states a platform polls for.

@magenxcommerce/engine/agentic/ucp/_lib/magento

packages/engine/src/agentic/ucp/_lib/magento.ts

Magento GraphQL calls behind the UCP routes.

IMPORTANT — allowlist discipline, kept as defense-in-depth. These handlers run server-side and, correctly configured, MAGENTO_GRAPHQL_ENDPOINT (see packages/engine/src/apollo/client.ts) resolves to Magento directly, bypassing the persisted-query proxy. But a real incident (CLAUDE.md, 2026-07-26 / 2026-08-01) showed that a misconfigured runtime var can send every server-side call through the public /api/graphql instead, where it IS hash-checked against api/graphql/_lib/allowed-operations.ts. Treat that as always possible and keep every document here allowlist-safe regardless of which path is actually taken at runtime.

Consequences, both load-bearing:

  1. Only ALREADY-ALLOWLISTED documents may be used here — every operation below is one the browser checkout already runs.
  2. They must be used VERBATIM. Reshaping a document (adding a field, trimming one) changes its hash and 403s until the new allowlist ships. If a UCP response needs a field these documents don't select, derive it or add a NEW allowlisted operation — do not edit these.

MagentoCallError class

A Magento failure carrying the raw messages, so the caller can map them to UCP messages[] (a business outcome) instead of throwing a 500.

resetMagentoClients function

resetMagentoClients(): void

Test seam: drop the memoized clients.

createCart function

async createCart(storeCode: string): Promise<string>

fetchCart function

async fetchCart(cartId: string, storeCode: string, options: { coupons?: boolean } = {}): Promise<CheckoutCart | null>

Load the full checkout view of a cart. Returns null when it doesn't exist.

Configurable lines also get configured_variant (their purchased child SKU), and lines with custom options agent_variant_id, merged in — see withVariantSkus. With coupons, a cart carrying a discount also gets applied_coupons, which the shared document does not select (UCP's discount extension echoes them; ACP has no use for them).

Both supplements are separate reads, issued only when the cart needs them and then in parallel, so a plain cart still costs one round trip.

LineVariant interface

What identifies one cart line as a catalog variant.

MemberTypeDescription
childSku?stringA configurable line's purchased child SKU.
variantId?stringThe custom-option variant id, when the line carries choices.

lineVariants function

lineVariants(items: Array<VariantSkusItem | null>): Map<string, LineVariant>

UcpCartVariantSkus items as LineVariants by line uid. Pure.

withVariantSkus function

withVariantSkus(cart: CheckoutCart, variants: Map<string, LineVariant>): CheckoutCart

Merge line variants into their lines: the child SKU as configured_variant, the custom-option variant id as agent_variant_id. Pure.

addItems function

async addItems(cartId: string, storeCode: string, cartItems: CartItemInput[]): Promise<string[]>

updateItemQuantities function

async updateItemQuantities(cartId: string, storeCode: string, items: Array<{ cart_item_uid: string; quantity: number }>): Promise<void>

removeItem function

async removeItem(cartId: string, storeCode: string, cartItemUid: string): Promise<void>

fetchAppliedCoupons function

async fetchAppliedCoupons(cartId: string, storeCode: string): Promise<string[]>

Coupon codes applied to a cart, via the server-only UcpCartCoupons.

applyCoupon function

async applyCoupon(cartId: string, storeCode: string, couponCode: string): Promise<void>

Apply one coupon. Magento rejects an unusable code with a GraphQL error.

removeCoupon function

async removeCoupon(cartId: string, storeCode: string): Promise<void>

setGuestEmail function

async setGuestEmail(cartId: string, storeCode: string, email: string): Promise<void>

setShippingAddress function

async setShippingAddress(cartId: string, storeCode: string, address: MagentoAddressInput): Promise<void>

setBillingAddress function

async setBillingAddress(cartId: string, storeCode: string, address: MagentoAddressInput): Promise<void>

setShippingMethod function

async setShippingMethod(cartId: string, storeCode: string, carrierCode: string, methodCode: string): Promise<void>

setStripePaymentMethod function

async setStripePaymentMethod(cartId: string, storeCode: string, paymentMethodId: string): Promise<void>

Attach a Stripe PaymentMethod (pm_…) to the quote.

PlacedOrder interface

MemberTypeDescription
orderNumberstring
clientSecretstring | nullPaymentIntent client secret. NEVER returned to a platform — it authorizes confirming the intent from a browser. Used only to look the intent's real status up server-side.

placeOrderWithStripe function

async placeOrderWithStripe(cartId: string, storeCode: string): Promise<PlacedOrder>

Place the order. Magento charges the quote and creates the sales order.

A thrown failure here is genuinely ambiguous about whether money moved, so callers must treat it as "payment state unknown" rather than "not charged" — see the complete flow.

fetchCountries function

async fetchCountries(storeCode: string): Promise<CountryListItem[]>

Country + region list, memoized per store view for an hour.

Magento's allowed-countries/regions are static admin configuration, and the region lookup runs on every address write — refetching it per request would add a full round-trip to the hottest UCP call.

CatalogPage interface

MemberTypeDescription
itemsMagentoCatalogProduct[]
totalCountnumber
totalPagesnumber

CatalogQuery interface

MemberTypeDescription
search?string | null
filter?Record<string, unknown>
pageSizenumber
currentPagenumber

fetchCatalogProducts function

async fetchCatalogProducts(storeCode: string, query: CatalogQuery): Promise<CatalogPage>

fetchGuestOrder function

async fetchGuestOrder(storeCode: string, number: string, email: string, lastname: string): Promise<MagentoOrder | null>

Read a guest order. Null when Magento does not know it under these details — which includes an order since attached to a customer account, since guestOrder refuses those ("Please login to view the order.").

@magenxcommerce/engine/agentic/ucp/_lib/mcp-protocol

packages/engine/src/agentic/ucp/_lib/mcp-protocol.ts

UCP checkout over MCP — the pure protocol layer: tool names, advertised schemas, argument validation, and result construction.

Split from mcp.ts (which dispatches, and therefore reaches Magento) so these rules are directly unit-testable: nothing here imports Apollo, Next, or the @/ alias.

THE RULE THAT MUST NOT DRIFT BETWEEN BINDINGS: a business outcome — out of stock, an undeliverable address, a missing email — is NOT an error. Over REST it is HTTP 200 carrying the checkout resource plus messages[]; here it is a normal tool result carrying the same resource, with isError ABSENT. Flagging it as a tool error throws away the very resource the platform needs in order to repair the cart, which is the fastest way to break an agent. isError is reserved for "there is no resource to return" (unknown session, upstream failure).

MCP_TOOL_NAMES const

const MCP_TOOL_NAMES

McpToolName type

type McpToolName = (typeof MCP_TOOL_NAMES)[number]

CATALOG_TOOL_NAMES const

const CATALOG_TOOL_NAMES = ["search_catalog", "lookup_catalog", "get_product"] as const

The catalog capability's tools. Kept apart from the checkout tools: they take a catalog argument instead of id/checkout, and have no session.

CatalogToolName type

type CatalogToolName = (typeof CATALOG_TOOL_NAMES)[number]

isCatalogToolName function

isCatalogToolName(name: unknown): name is CatalogToolName

CART_TOOL_NAMES const

const CART_TOOL_NAMES = ["create_cart", "get_cart", "update_cart", "cancel_cart"] as const

The cart capability's tools. Same identifier pattern as checkout (top-level id, payload under cart), but a different payload and outcome shape.

CartToolName type

type CartToolName = (typeof CART_TOOL_NAMES)[number]

isCartToolName function

isCartToolName(name: unknown): name is CartToolName

ORDER_TOOL_NAMES const

const ORDER_TOOL_NAMES = ["get_order"] as const

The order capability's one tool.

OrderToolName type

type OrderToolName = (typeof ORDER_TOOL_NAMES)[number]

isOrderToolName function

isOrderToolName(name: unknown): name is OrderToolName

isMcpToolName function

isMcpToolName(name: unknown): name is McpToolName

toolRequiresId function

toolRequiresId(name: McpToolName): boolean

Test seam — REQUIRES_ID is consulted directly everywhere in this module.

McpToolDescriptor interface

MemberTypeDescription
nameMcpToolName | CatalogToolName | CartToolName | OrderToolName
descriptionstring
inputSchema{ type: "object"; properties: Record<string, unknown>; required: string[] }

listTools function

listTools(): McpToolDescriptor[]

The tools/list payload.

ParsedCartCall interface

MemberTypeDescription
idstring | null
cartUcpCartInput

parseCartToolCall function

parseCartToolCall(name: CartToolName, args: unknown): { ok: true; call: ParsedCartCall } | { ok: false; message: string }

Validate a cart tool call. The same identifier rules as checkout: a top-level id on existing-cart tools, never an id inside the payload — the cart id is a bearer credential for the quote, so two disagreeing ids must be refused rather than one silently preferred.

parseOrderToolCall function

parseOrderToolCall(args: unknown): { ok: true; id: string } | { ok: false; message: string }

Validate a get_order call: just a top-level id.

parseCatalogToolCall function

parseCatalogToolCall(args: unknown): { ok: true; catalog: Record<string, unknown> } | { ok: false; message: string }

Read a catalog tool's catalog argument.

ParsedToolCall interface

MemberTypeDescription
idstring | null
checkoutUcpCheckoutInput
idempotencyKeystring | null

ParseResult type

type ParseResult = | { ok: true; call: ParsedToolCall } | { ok: false; message: string }

readAgentProfileFromArgs function

readAgentProfileFromArgs(args: unknown): string | null

Read meta["ucp-agent.profile"] without requiring the rest of the call to parse.

The route calls this before parseToolCall, because authorization has to happen first — which is why the profile is NOT carried on ParsedToolCall. It used to be, computed a second time and read by nobody.

parseToolCall function

parseToolCall(name: McpToolName, args: unknown): ParseResult

Validate a tool call's arguments against the binding's rules.

The checkout object MUST NOT carry an id on operations that already take a top-level one. This is not pedantry: the session id is a bearer credential for a cart, so silently preferring one of two disagreeing ids is how a platform ends up mutating a cart it did not mean to touch.

McpToolResult interface

MemberTypeDescription
contentArray<{ type: "text"; text: string }>
structuredContent?T
isError?true

checkoutResult function

checkoutResult(checkout: UcpCheckout): McpToolResult<UcpCheckout>

A successful tool result.

The checkout goes in structuredContent (the machine-readable channel the binding specifies) AND as a compact text block, because MCP clients are only required to render content.

resourceResult function

resourceResult(kind: "Cart" | "Order", body: Record<string, unknown>): McpToolResult

A cart or order tool result — the resource, or the spec's error_response (not_found). Both are application outcomes, so neither is isError: the platform discriminates on ucp.status, exactly as over REST.

negotiationResult function

negotiationResult(body: Record<string, unknown>): McpToolResult

The spec's capabilities_incompatible outcome as a tool result: a normal result (not isError, not a JSON-RPC error), because a negotiation failure is a business outcome — the UCP error body rides structuredContent.

errorResult function

errorResult(code: string, message: string): McpToolResult

A tool result for "there is no resource to return".

catalogResult function

catalogResult(body: Record<string, unknown>): McpToolResult

A catalog tool result: the UCP response in structuredContent, and a short text summary for clients that only render content. A get_product not_found is an application outcome, so it is NOT flagged isError.

@magenxcommerce/engine/agentic/ucp/_lib/mcp

packages/engine/src/agentic/ucp/_lib/mcp.ts

UCP checkout over the MCP binding — dispatch.

UCP defines the SAME five operations over four transports (REST, MCP, A2A, Embedded); per the spec "all bindings share the same logical operations and response schema". So this is a transport adapter, not a second implementation: every commerce decision comes from session.ts (buildCheckoutSession / deriveStatus) and apply.ts (applyCheckoutInput / emptyCart), and the authorization decision from handler.ts's authorize(). It mirrors the REST route handlers operation-for-operation; where they return an HTTP response, this returns an MCP tool result.

The protocol layer (tool schemas, argument validation, result construction) lives in mcp-protocol.ts — pure, and unit-tested there.

callTool function

async callTool(name: McpToolName, call: ParsedToolCall, platform: string, agentProfile?: string, negotiated?: UcpCapabilityRefs): Promise<McpToolResult>

Run one checkout tool. platform is the authenticated credential's label and agentProfile its UCP-Agent profile, both recorded against any order complete places (see order-service.ts and order-webhooks.ts). negotiated is the capability intersection the result's envelope declares from.

callCartTool function

async callCartTool(name: CartToolName, call: ParsedCartCall, negotiated?: UcpCapabilityRefs): Promise<McpToolResult>

Run one cart tool.

callOrderTool function

async callOrderTool(orderId: string, platform: string, negotiated?: UcpCapabilityRefs): Promise<McpToolResult>

Run get_order for the authenticated platform.

@magenxcommerce/engine/agentic/ucp/_lib/money

packages/engine/src/agentic/ucp/_lib/money.ts

Money conversion between Magento and UCP.

Magento GraphQL returns amounts as floating-point values in MAJOR units ({ value: 19.99, currency: "EUR" }). UCP requires integers in the currency's MINOR unit ("amount": 1999). The exponent is currency-dependent: most ISO 4217 currencies use 2 decimals, a handful use 0 or 3.

Rounding is done once, at the boundary, with Math.round on a scaled value — never by string formatting — so 19.99 * 100 = 1998.9999999999998 still yields 1999.

currencyExponent function

currencyExponent(currency: string | null | undefined): number

ISO 4217 minor-unit exponent for currency (defaults to 2).

toMinorUnits function

toMinorUnits(value: number | null | undefined, currency: string | null | undefined): number

Convert a Magento major-unit amount to UCP minor units.

Returns 0 for null/undefined/non-finite input: UCP totals entries require an integer amount, and emitting a missing total as 0 is safer than emitting NaN (which is not valid JSON and would fail the platform's schema check).

moneyToMinorUnits function

moneyToMinorUnits(money: { value?: number | null; currency?: string | null } | null | undefined, fallbackCurrency?: string | null): number

Convert a Magento MoneyType-shaped object to minor units.

@magenxcommerce/engine/agentic/ucp/_lib/namespace

packages/engine/src/agentic/ucp/_lib/namespace.ts

Namespace authority binding — does the party serving an entity's schema own the namespace in its name?

Spec: https://ucp.dev/2026-08-25/specification/overview/ (Namespace Governance — Authority Binding, Derivation algorithm, Enforcement).

Capability, service and payment-handler names are reverse-domain (dev.ucp.shopping.checkout, com.example.payments.installments), and an entity's schema URL must be served from the domain its name claims. The check proves provenance only — that nobody published under a namespace they don't control — not that the entity is trustworthy.

Platforms MUST apply it to a business profile; "a business SHOULD apply the same check to the platform profile and exclude any entity whose binding fails", which is what ./negotiation.ts uses this for. Pure.

isAuthorityBound function

isAuthorityBound(name: string, schemaUrl: string): boolean

True when schemaUrl's host is the namespace authority of name.

Derivation, step by step from the spec:

  1. parse with a WHATWG parser; it must parse, be https, carry no userinfo (never substring-match the raw URL: https://ucp.dev@evil.example/ has host evil.example);
  2. the host must be a registered domain of at least two labels — no IP literals, no single-label hosts;
  3. lowercase it, strip a trailing dot (WHATWG already yields A-labels), and reverse its labels: ucp.dev → dev.ucp;
  4. valid iff name equals that prefix, or continues it after a . — the label boundary is what stops com.example matching com.examplecorp.*.

@magenxcommerce/engine/agentic/ucp/_lib/negotiation

packages/engine/src/agentic/ucp/_lib/negotiation.ts

Protocol-version and capability negotiation against the caller's profile.

Spec: https://ucp.dev/2026-08-25/specification/overview/ (Request-Time Validation, Intersection Algorithm, Error Handling, Response Capability Selection).

On every request the business must:

  1. read the platform profile named in UCP-Agent (./platform-profile.ts — cached, so this is a map lookup on all but the first request per TTL);
  2. check the platform's ucp.version: "If the platform's version matches the business's version or is a key in supported_versions: the request MAY proceed … Otherwise: Business MUST return a version_unsupported error." We implement exactly one version and publish no supported_versions, so the rule is equality;
  3. intersect capabilities, and refuse an operation whose own capability did not survive with capabilities_incompatible;
  4. declare in each response only the negotiated capabilities relevant to that operation (./capabilities.ts relevantCapabilities).

Runs AFTER authentication and the profile binding (./auth.ts), so every profile fetched here is one an operator bound to a credential: the discovery footprint is fixed by configuration, not by how many URLs strangers send — the spec's "registry of pre-approved platforms", which it exempts from discovery budgets.

Everything except negotiateRequest is pure and unit-tested directly.

PlatformCapabilityEntry interface

A capability entry as read from a platform profile, reduced to what negotiation uses.

MemberTypeDescription
versionstring
extends?string[]

ValidatedPlatformProfile interface

MemberTypeDescription
versionstring
capabilitiesRecord<string, PlatformCapabilityEntry[]>
excluded?string[]Capability names with at least one entry dropped for failing namespace authority binding (see ./namespace.ts) — reported back so a platform learns why a capability it declared did not negotiate.

NegotiationFailureCode type

type NegotiationFailureCode = | DiscoveryFailureCode | "version_unsupported" | "capabilities_incompatible"

NegotiationFailure interface

MemberTypeDescription
codeNegotiationFailureCode
status200 | 400 | 422 | 424 | 503REST status. 400/422/424 are transport errors (MCP JSON-RPC -32001); capabilities_incompatible is a business outcome and rides a 200 with a UCP error body (an MCP result, not an error).
messagestring

Negotiation type

type Negotiation = | { ok: true; version: string; capabilities: UcpCapabilityRefs } | { ok: false; failure: NegotiationFailure }

validatePlatformProfile function

validatePlatformProfile(profile: unknown): { ok: true; profile: ValidatedPlatformProfile } | { ok: false; failure: NegotiationFailure }

Validate the parts of a platform profile negotiation depends on.

Deliberately not a full schema validation: ucp.version and the shape of ucp.capabilities are what the algorithm reads, so those are enforced (a wrong shape there would silently negotiate the wrong thing). services and payment_handlers are required by the profile schema but unused by this business; refusing a platform over them would buy nothing. A capability value is an array of entries per the spec; a lone object is tolerated, as ./platform-profile.ts has always done for the order webhook.

Namespace authority binding (spec, Enforcement: "A business SHOULD apply the same check to the platform profile and exclude any entity whose binding fails"): an entry whose schema URL is missing ("A capability MUST declare a schema") or not served from the domain its name claims is treated as not present — dropped, not a malformed profile, exactly as a platform treats such an entity in ours.

checkProtocolVersion function

checkProtocolVersion(platformVersion: string): NegotiationFailure | null

Spec, Request-Time Validation. Null when the version is acceptable.

The message names the version we implement, as the spec's example does, so a platform engineer reading it knows what to send instead.

intersectCapabilities function

intersectCapabilities(platform: Record<string, PlatformCapabilityEntry[]>): UcpCapabilityRefs

Spec, Intersection Algorithm.

  1. keep each business capability the platform also names;
  2. keep only versions present in BOTH arrays (exact equality — never inferred from date order) and select the latest; drop the capability when none is shared;
  3. prune extensions none of whose parents survived (single parent: it must be present; several: at least one);
  4. repeat 3 until stable, for transitive extension chains.

Parents come from the business registry first (we know our extensions' schemas), falling back to what the platform declared.

negotiate function

negotiate(profile: ValidatedPlatformProfile, requires: string | null): Negotiation

Negotiate a validated profile. requires is the root capability the operation needs, or null for protocol-level calls (MCP initialize, tools/list) that return no UCP resource.

negotiateRequest function

async negotiateRequest(profileUrl: string, requires: string | null): Promise<Negotiation>

Load, validate and negotiate the caller's profile for one request.

@magenxcommerce/engine/agentic/ucp/_lib/order-service

packages/engine/src/agentic/ucp/_lib/order-service.ts

UCP order capability — ownership records and Get Order, binding-agnostic.

AUTHORIZATION is the point of this module. The spec lets a business serve an order to "the platform that originated it" on platform credentials alone, and that is the only grant this surface makes: an agent credential never reaches a customer account, so there is no buyer authorization to honour.

"Originated" has to be recorded, because Magento has no notion of a platform. So when complete places an order it writes an ownership record — which credential placed it, from which checkout, and the email + billing lastname Magento's guestOrder needs to read it back. Get Order then serves an order only to the credential in that record.

An order that exists but belongs to someone else is reported exactly like one that does not exist (not_found, never unauthorized): order numbers are sequential, and a distinguishable answer would let any onboarded platform enumerate which numbers are real orders.

Consequence worth knowing: only orders placed THROUGH complete (delegated payment) are readable. An escalated checkout is finished by the buyer in the browser, and that order is never linked back to the platform.

OrderRecord interface

Who placed an order, and what Magento needs to read it back.

MemberTypeDescription
platformstringWho placed the order: the verified profile URL of a signed platform, or the operator-assigned key label (UCP_PLATFORM_KEYS) — never the key.
checkoutIdstring
emailstring
lastnamestring
storeCodestring
localestring
agentProfile?stringThe UCP-Agent profile URL of the platform that placed the order. Its order capability names the webhook_url order events go to (see ./order-webhooks.ts). Absent on records written before webhooks existed.

OrderOutcome type

type OrderOutcome = ResourceOutcome<UcpOrder>

OrderSnapshot type

type OrderSnapshot = | { ok: true; order: UcpOrder } | { ok: false; notFound: true } | { ok: false; notFound: false; message: string }

What reading a recorded order back from Magento produced.

readOrderRecord function

readOrderRecord(orderId: string): Promise<OrderRecord | null>

Load an order owner record; null when this surface never placed it.

readOrderSnapshot function

async readOrderSnapshot(orderId: string, record: OrderRecord, baseUrl: string, fallbackCurrency: string, negotiated?: UcpCapabilityRefs): Promise<OrderSnapshot>

The current-state UCP order for a recorded order — the one body both Get Order and the order webhooks send, so the two can never disagree.

Takes only what is request-independent: the permalink uses the locale recorded at complete, not whatever the caller happens to carry. negotiated is the Get Order caller's capability intersection; the webhook dispatcher has none, and order is the only capability an order body declares either way, so both render the same envelope.

recordOrder function

async recordOrder(orderNumber: string, record: OrderRecord): Promise<void>

Record that record.platform placed orderNumber.

Never throws: it runs AFTER Magento placed (and possibly charged) the order, where failing the request would hide a real order from the platform. A lost record only costs later reads of this one order, so it is logged loudly.

getOrder function

async getOrder(orderId: string, platform: string, ctx: RequestContext): Promise<OrderOutcome>

Get Order: the current-state snapshot, for the platform that placed it.

@magenxcommerce/engine/agentic/ucp/_lib/order-webhooks

packages/engine/src/agentic/ucp/_lib/order-webhooks.ts

UCP order events — push every order change to the platform that placed it.

Spec: https://ucp.dev/2026-08-25/specification/shopping/order/

The business MUST POST the full current-state order (not a delta) to the webhook_url the platform declares in its profile, MUST sign it (RFC 9421), and MUST retry failed deliveries. Get Order alone is the pull half; this is the push half.

WHY POLLING, AND WHY HERE. Magento has no notion of a platform and no outbound hook for "this guest order was shipped/refunded/canceled" that this headless stack could subscribe to without a custom PHP module. Everything the webhook must say, though, is already what Get Order computes. So the storefront watches the orders UCP placed: it re-reads each one on a cadence, hashes the rendered UCP order, and sends it whenever the hash moves. Same body as Get Order, by construction (readOrderSnapshot).

  complete ──► recordOrder (owner + agent profile) ──► watchOrder (due now)
                                                           │
  dispatcher tick (every UCP_ORDER_WEBHOOK_INTERVAL s) ◄───┘
    └─ lock ─► due orders ─► platform profile ─► webhook_url
                          └─► Magento guestOrder ─► buildOrder ─► sha-256
                              changed? ─► signed POST ─► 2xx: remember hash
                                                       └ else: back off

Delivery is at-least-once. Webhook-Id (and Idempotency-Key, the same value) is derived from the order number and the snapshot hash, so every retry of one state carries one id and the platform can deduplicate.

The watch list, cadence, backoff and replica lock are shared with ACP's order events (../../_lib/order-watch.ts); what is read, rendered, signed and sent is UCP's and lives here. Storage rides the same Redis as the idempotency store (UCP_REDIS_URL, else REDIS_URL), else process memory.

Off unless the surface is on AND UCP_SIGNING_KEY is configured: the spec requires signed webhooks, and an unsigned one is one a platform must reject. UCP_ORDER_WEBHOOKS=0 turns delivery off explicitly.

isOrderWebhookDeliveryEnabled function

isOrderWebhookDeliveryEnabled(): boolean

True when order events may be sent at all.

sendOrderEvent function

async sendOrderEvent(webhookUrl: string, body: string, eventId: string, observedAt: number): Promise<SendResult>

POST one signed order event. Never throws.

processOrder function

async processOrder(orderNumber: string, current: WatchState | null, now: number = Date.now()): Promise<Step>

Look at one watched order once: read it, and deliver it if it changed. Returns when to look again, or next: null to stop watching.

Exported (with its collaborators injectable through the module mocks) as the unit the tests drive; runDispatchCycle only feeds it due orders.

watchOrder function

watchOrder(orderNumber: string): Promise<void>

Start watching an order placed through complete. Called right after the ownership record is written; never throws, because the order already exists and a lost watch only costs the push (Get Order still serves it).

runDispatchCycle function

runDispatchCycle(now: number = Date.now()): Promise<number>

One dispatcher tick: process every due order, under a lock so replicas sharing Redis don't double-send. Returns how many orders were looked at.

startOrderWebhookDispatcher function

startOrderWebhookDispatcher(): void

Start the background dispatcher. Called once from instrumentation.ts in the Node server process. The enabled check runs on every tick, not here, so a store that switches UCP or signing on at runtime starts delivering without a restart.

resetOrderWebhooks function

resetOrderWebhooks(): void

Test seam: drop state, the cached store and the timer.

@magenxcommerce/engine/agentic/ucp/_lib/order

packages/engine/src/agentic/ucp/_lib/order.ts

Magento order → UCP order resource (the dev.ucp.shopping.order capability).

Pure, like session.ts and cart.ts: the route supplies the Magento order and the ownership record written at complete; nothing here reaches the network.

How Magento's model maps onto UCP's three parts:

  line_items   ← order items. `quantity.total` is what is still owed to the
                 buyer (ordered − canceled − refunded), `fulfilled` what has
                 shipped of that, and `status` is derived from the two exactly
                 as the spec defines it.
  fulfillment  ← one expectation for the order's destination (Magento models
                 one shipment destination per order) plus one `shipped` event
                 per Magento shipment, with its tracking.
  adjustments  ← one `refund` per credit memo.

TIMESTAMPS: Magento's GraphQL exposes no creation time for shipments or credit memos. occurred_at uses the record's earliest comment timestamp when it has one, else the order date — a lower bound, never a time in the future.

MagentoOrderItem interface

MemberTypeDescription
idstring
product_name?string | null
product_skustring
quantity_ordered?number | null
quantity_shipped?number | null
quantity_canceled?number | null
quantity_refunded?number | null
product_sale_price?Money | null
discounts?Array<{ amount?: Money | null } | null> | null

MagentoShipment interface

MemberTypeDescription
idstring
numberstring
tracking?Array<{ title?: string | null; number?: string | null; carrier?: string | null; } | null> | null
items?Array< (MagentoLineRef & { quantity_shipped?: number | null }) | null > | null
comments?Array<MagentoComment | null> | null

MagentoCreditMemo interface

MemberTypeDescription
idstring
numberstring
total?{ grand_total?: Money | null } | null
items?Array< (MagentoLineRef & { quantity_refunded?: number | null }) | null > | null
comments?Array<MagentoComment | null> | null

MagentoOrder interface

MemberTypeDescription
numberstring
order_datestring
statusstring
shipping_method?string | null
shipping_address?MagentoOrderAddress | null
billing_address?MagentoOrderAddress | null
total?{ grand_total?: Money | null; subtotal?: Money | null; total_tax?: Money | null; total_shipping?: Money | null; discounts?: Array<{ amount?: Money | null } | null> | null; } | null
items?Array<MagentoOrderItem | null> | null
shipments?Array<MagentoShipment | null> | null
credit_memos?Array<MagentoCreditMemo | null> | null

OrderOptions interface

MemberTypeDescription
checkoutIdstringThe checkout session (masked quote id) the order was placed from.
permalinkUrlstringBuyer-facing URL for this order.
fallbackCurrencystringStore currency, for an order Magento returns without one.
negotiated?UcpCapabilityRefsThe negotiated intersection; the envelope declares order's relevant subset.

toRfc3339 function

toRfc3339(value: string | null | undefined): string | null

Magento's YYYY-MM-DD HH:MM:SS (UTC, as stored) → RFC 3339. Already-ISO input passes through; anything unparseable yields null.

trackingUrl function

trackingUrl(carrier: string | null | undefined, number: string): string | null

deriveLineStatus function

deriveLineStatus(total: number, fulfilled: number): UcpOrderLineItem["status"]

The spec's status derivation, verbatim.

buildOrder function

buildOrder(order: MagentoOrder, options: OrderOptions): UcpOrder

Project a Magento order onto the UCP order resource.

@magenxcommerce/engine/agentic/ucp/_lib/payment

packages/engine/src/agentic/ucp/_lib/payment.ts

What payment this business supports — the one place that answers it.

UCP models payment as a registry of HANDLERS: payment_handlers is an OBJECT keyed by reverse-domain name (e.g. com.stripe.payments), each mapping to an array of handler declarations. It is REQUIRED in two places, which is easy to miss because they are produced by different modules:

  1. the /.well-known/ucp profile (ucp.json#/$defs/business_schema)
  2. EVERY checkout response envelope (ucp.json#/$defs/response_checkout_schema)

Both come from buildPaymentHandlers() here so they can never disagree.

An empty OBJECT, never an empty array: the schema types this as object with propertyNames constrained to reverse-domain names, so [] fails validation.

THE REGISTRY IS THE SWITCH. When it is empty the business is declaring "nothing here to pay with", complete escalates to continue_url, and a submitted instrument is explicitly reported as uncharged. When it declares com.stripe.payments, complete genuinely charges and places an order. Every downstream decision keys off the registry rather than off a scattered set of env checks, so the two halves cannot drift into declaring one thing and doing another.

STRIPE_HANDLER const

const STRIPE_HANDLER = "com.stripe.payments"

Reverse-domain name of Stripe's UCP payment handler.

STRIPE_HANDLER_ID const

const STRIPE_HANDLER_ID = "stripe_payments"

Handler id, echoed by the platform as instrument.handler_id.

Stripe's doc uses this exact value in its example; keep it stable, because a platform that cached our profile matches instruments against it.

buildPaymentHandlers function

buildPaymentHandlers(): UcpPaymentHandlers

The payment handler registry advertised to platforms.

Built per call rather than frozen at module load because it depends on runtime env (the Stripe keys), exactly like UCP_PLATFORM_KEYS. The empty case returns one shared frozen object so the common path allocates nothing.

available_instruments declares card only. Link/Google Pay/Apple Pay ride the same stripe_payment_token credential and would need no new charging code, but declaring an instrument we have never exercised would be a promise we cannot back — add them once each is tested end to end.

isDelegatedPaymentAvailable function

isDelegatedPaymentAvailable(): boolean

True when this business can charge a delegated instrument server-side.

hasSubmittedInstruments function

hasSubmittedInstruments(payment: UcpPayment | undefined): boolean

True when the platform actually submitted an instrument to charge.

unsupportedInstrumentMessage function

unsupportedInstrumentMessage(): UcpMessage

The response to a platform that submitted payment instruments we cannot use.

payment is REQUIRED on the complete request, so a conforming platform will send one — and a platform that already tokenized a card needs to be told the instrument was not used, or it will assume the charge is pending. Silence here is the failure mode: it reads as acceptance.

InstrumentResult type

type InstrumentResult = | { ok: true; token: string } | { ok: false; message: UcpMessage }

selectChargeableInstrument function

selectChargeableInstrument(payment: UcpPayment | undefined): InstrumentResult

Pick the instrument to charge and extract its token.

Every rejection here is recoverable: the platform can fix all of these by re-tokenizing and resubmitting, which is precisely what the severity tells it to do. Nothing reaches Stripe until this passes, so a malformed instrument costs no API call.

@magenxcommerce/engine/agentic/ucp/_lib/platform-profile

packages/engine/src/agentic/ucp/_lib/platform-profile.ts

Platform profile discovery — reading the profile a caller names in UCP-Agent: profile="…", for two consumers:

  • capability negotiation (./negotiation.ts), on every request: the spec says "Businesses MUST fetch and validate the platform profile unless already cached";
  • order webhooks (./order-webhooks.ts): where does this platform want order events?

One loader and ONE cache serve both, so a platform's profile is fetched once per TTL no matter how many requests and webhook ticks need it.

Discovery failures are classified the way the spec's error table does (Overview, Error Handling): a URL that is not fetchable at all is invalid_profile_url (400), a fetch that fails (timeout, non-2xx, a 3xx — redirects are never followed, DNS failure, oversize) is profile_unreachable (424), and content that is not JSON is profile_malformed (422). Schema-level validation belongs to negotiation, which knows what it needs from the document; webhooks only need one field.

Order webhooks — spec: https://ucp.dev/2026-08-25/specification/shopping/order/ The order capability's webhook target lives in the PLATFORM's profile, NOT in our own:

  "dev.ucp.shopping.order": [{ "version": "…",
    "config": { "webhook_url": "https://platform.example/webhooks/ucp/orders" } }]

order.json defines that config only as $defs.platform_schema, with webhook_url required. A business profile carries no such config — which is why a validator that applies the platform rule to /.well-known/ucp reports "requires config.webhook_url to be an HTTPS URL" against a store.

SECURITY: the profile URL and the webhook_url inside it are both chosen by the platform, and this process then connects to them. Both go through the SSRF guard (HTTPS only, public addresses only, no redirects), the profile read is time- and size-capped, and the profile is never logged verbatim.

DiscoveryFailureCode type

type DiscoveryFailureCode = | "invalid_profile_url" | "profile_unreachable" | "profile_malformed" | "discovery_deferred"

ProfileLoad type

type ProfileLoad = | { ok: true; profile: unknown } | { ok: false; code: DiscoveryFailureCode; status: 400 | 422 | 424 | 503; reason: string }

DISCOVERY_RETRY_AFTER_S const

const DISCOVERY_RETRY_AFTER_S = 60

Seconds a caller is told to wait when the discovery budget is spent.

WebhookTarget type

type WebhookTarget = | { ok: true; url: string } /** * `permanent` — the profile was read and declares no usable webhook: the * platform polls Get Order instead, so there is nothing to retry. * Otherwise the profile could not be read right now; try again later. */ | { ok: false; permanent: boolean; reason: string }

readOrderWebhookUrl function

readOrderWebhookUrl(profile: unknown): WebhookTarget

Pull an HTTPS webhook_url out of a parsed platform profile.

Pure, so the validation rule is testable without a network. The message mirrors the conformance validators' wording, so an operator searching logs for the error a platform's tooling shows them lands here.

LoadOptions interface

MemberTypeDescription
refreshOlderThan?numberRefetch when the cached copy is older than this, even within its TTL — signature verification's one-off refresh after an unknown kid (a platform that rotated keys). Floored by the caller at 60 s per the spec.
authenticated?booleanThe caller is already authenticated (negotiation, webhook delivery), so a cache miss draws on the authenticated budget, which unauthenticated signature-verification lookups cannot spend.

loadPlatformProfile function

async loadPlatformProfile(profileUrl: string, now: number = Date.now(), options: LoadOptions = {}): Promise<ProfileLoad>

Load the platform profile at profileUrl, cached.

Successes are reused for 10 minutes and failures for one (the backoff the spec recommends against persistently unavailable endpoints). The URL must already be canonical (parseProfileUrl in ./auth.ts), so one profile maps to one cache entry. A fetch that misses the cache draws on the global discovery budget; a spent budget is not cached, since it says nothing about the profile.

resolveOrderWebhookTarget function

async resolveOrderWebhookTarget(profileUrl: string, now: number = Date.now()): Promise<WebhookTarget>

Resolve where profileUrl's platform wants order events, cached.

resetPlatformProfileCache function

resetPlatformProfileCache(): void

Test seam: forget cached profiles.

primePlatformProfileForTests function

primePlatformProfileForTests(profileUrl: string, profile: unknown): void

Test seam: serve profile for profileUrl without a network fetch.

@magenxcommerce/engine/agentic/ucp/_lib/request-verify

packages/engine/src/agentic/ucp/_lib/request-verify.ts

Inbound request authentication by RFC 9421 HTTP Message Signatures — UCP's permissionless onboarding.

Spec: https://ucp.dev/2026-08-25/specification/signatures/ (REST Request Verification, MCP Transport, Error Handling) and the overview's Identity Resolution Algorithm.

The model: a platform publishes public keys in its own profile's keys[], names that profile in UCP-Agent, and signs each request with one of them. The business fetches the profile, finds the key by keyid and verifies. "The signer's profile (from UCP-Agent) is verified by signature validation; no additional check needed" — the verified profile URL IS the caller's identity. No secret is shared and nothing is registered in advance.

What a signature must bind, in every regime (spec, covered-component rule): the target (@method, @authority, @path, @query when present), the body when present (content-digest + content-type, with the digest checked against the raw bytes), and each of ucp-agent, idempotency-key, signature-agent when the request carries it. A signature that leaves any of those out authenticates nothing and is skipped.

Replay protection is NOT done with timestamps here: the spec puts it at the business layer, through the signed idempotency-key (see ./idempotency.ts). created is optional; an expires in the past is honoured.

The parsing below is a deliberately small, strict subset of RFC 8941 structured fields — exactly what UCP signatures use. Anything outside it (component parameters such as ;key=, unknown derived components) makes that one signature unusable rather than being guessed at.

VerifyFailureCode type

type VerifyFailureCode = | "signature_missing" | "signature_invalid" | "key_not_found" | "digest_mismatch" | "algorithm_unsupported" | DiscoveryFailureCode

VerifyResult type

type VerifyResult = | { ok: true; keyid: string } | { ok: false; status: 400 | 401 | 422 | 424 | 503; code: VerifyFailureCode; message: string }

SignedRequest interface

The parts of an inbound request a signature can cover.

MemberTypeDescription
methodstring
urlURL
headersHeaders
bodyBuffer | nullRaw body bytes, exactly as received; null or empty when there is none.

SignatureInput interface

MemberTypeDescription
labelstring
componentsstring[]Covered component identifiers, unquoted (@method, content-digest, …).
paramsRecord<string, BareItem>
rawstringThe member value exactly as received — the @signature-params line.

parseSignatureInput function

parseSignatureInput(header: string): SignatureInput[] | null

Parse Signature-Input. Null when the header is not a well-formed dictionary of inner lists — a malformed header is not something to guess at.

parseByteDictionary function

parseByteDictionary(header: string): Map<string, Buffer> | null

Parse a dictionary whose members are byte sequences (Signature, Content-Digest).

expectedAuthority function

expectedAuthority(): string

The host every signature must name in @authority: this store's public host from configuration. Behind nginx the request's own Host is internal, and pinning it to the configured host is exactly what stops a signature made for another business being replayed here.

requiredComponents function

requiredComponents(req: SignedRequest): string[]

Components the request's shape obliges a signature to cover.

signatureBase function

signatureBase(req: SignedRequest, input: SignatureInput, authority: string): string | null

The RFC 9421 §2.5 signature base, or null when a component can't be resolved.

eligibleKeys function

eligibleKeys(profile: unknown): Record<string, unknown>[]

The profile's keys usable for signature verification (spec: skip keys marked use:"enc" or whose key_ops omits "verify").

verifyCandidate function

verifyCandidate(req: SignedRequest, input: SignatureInput, signature: Buffer | undefined, profile: unknown, authority: string, now: number = Math.floor(Date.now() / 1000)): Attempt

Verify one candidate signature against a resolved key set.

Pure apart from the crypto: the caller has already fetched the profile. now is seconds since the epoch, injectable for tests.

verifyAgainstProfile function

verifyAgainstProfile(req: SignedRequest, inputs: SignatureInput[], signatures: Map<string, Buffer>, profile: unknown, authority: string = expectedAuthority()): Attempt

Verify every candidate; the request is authenticated when one verifies (RFC 9421 §4.3). The reported failure is the first candidate's.

verifyRequestSignature function

async verifyRequestSignature(req: SignedRequest, profileUrl: string): Promise<VerifyResult>

Authenticate a request by its signature, resolving keys from profileUrl (the canonical UCP-Agent profile). The caller has already established that the request carries Signature-Input.

@magenxcommerce/engine/agentic/ucp/_lib/session-id

packages/engine/src/agentic/ucp/_lib/session-id.ts

The checkout session id contract, in one place.

The session id IS the Magento masked quote id — an opaque token that is also a BEARER CREDENTIAL for that cart (anyone holding it can read and modify the cart, exactly as the browser's localStorage copy can). So it must never be logged in full, and must be shape-checked before it reaches Magento.

Its own module because both transports validate it and neither should own the definition: http.ts (REST) pulls in next/server, which would drag the framework into the MCP binding's — and the unit tests' — import graph.

isValidSessionId function

isValidSessionId(id: string): boolean

@magenxcommerce/engine/agentic/ucp/_lib/session

packages/engine/src/agentic/ucp/_lib/session.ts

Magento cart → UCP checkout session.

This is the heart of the UCP surface: one pure function that projects a Magento CheckoutCart onto the UCP checkout resource, plus the status derivation that tells a platform what to do next.

Deliberately pure and dependency-light (no @/ alias, no #config, no Apollo) so it is directly unit-testable — everything environmental is passed in via SessionOptions by the route handlers.

SessionOptions interface

MemberTypeDescription
taxModeProductPriceDisplayMirrors the merchant's Magento tax display setting (tax.productPriceDisplay).
fallbackCurrencystringStore currency, used when a cart is empty and Magento returns no money field.
continueUrlstringAbsolute URL a human is handed off to (continue_url).
linksUcpLink[]Legal links — mandatory in UCP for compliance.
messages?UcpMessage[]Extra messages to merge in (e.g. errors from the mutation that just ran).
statusOverride?UcpStatusOverrides the derived status (used by cancel/complete).
order?UcpOrderConfirmationOrder confirmation, set once an order exists.
delegatedPayment?booleanTrue when a payment handler is declared, i.e. the platform can complete programmatically. Drives the terminal status (see deriveStatus).
negotiated?UcpCapabilityRefsThe negotiated intersection; the envelope declares checkout's relevant subset.

formatOptionId function

formatOptionId(carrierCode: string, methodCode: string): string

UCP fulfillment option id for a Magento carrier/method pair.

| (not _) is the separator on purpose: carrier codes themselves contain underscores (magenx_storepickup), so an underscore-joined id cannot be split back apart unambiguously.

parseOptionId function

parseOptionId(optionId: string): { carrierCode: string; methodCode: string } | null

Inverse of formatOptionId; null when the id isn't a carrier|method pair.

buildLineItems function

buildLineItems(cart: CheckoutCart, options: Pick<SessionOptions, "taxMode" | "fallbackCurrency">): UcpLineItem[]

Magento cart lines → UCP line items. Shared with the cart capability.

buildTotals function

buildTotals(cart: CheckoutCart, options: Pick<SessionOptions, "taxMode">, shippingAmount: number, hasSelectedMethod: boolean, currency: string): UcpTotal[]

Build the UCP totals breakdown.

The entries must reconcile (subtotal − discount + tax + fulfillment = total), which drives two decisions:

  • The tax line is emitted ONLY when the store displays prices tax-exclusive. On a tax-inclusive catalog the tax is already inside the subtotal, so adding it again would overstate the total by the VAT.
  • The total is Magento's grand_total ONLY once a shipping method has been selected. Before that, Magento folds an auto-selected flat rate into grand_total (see the cart "estimated total" note in CLAUDE.md), which would contradict the fulfillment: 0 line we emit; the pre-shipping estimate is used instead.

deriveStatus function

deriveStatus(cart: CheckoutCart, delegatedPayment = false): { status: UcpStatus; messages: UcpMessage[]; }

Derive the UCP status from what Magento still needs.

The terminal branch depends on whether a payment handler is declared:

  • WITHOUT one (the default), a fully-populated cart lands on requires_escalation — the spec's mechanism for "the agent has done all it can, a human must authorize payment" — carrying the single buyer_authorization_required message.
  • WITH one (Stripe's handler configured), the same cart is genuinely ready_for_complete: the platform can tokenize an instrument and call complete, which will charge it and place the order.

delegatedPayment is passed in rather than read from the environment, so this stays pure and is directly testable in both modes.

buildCheckoutSession function

buildCheckoutSession(cart: CheckoutCart, options: SessionOptions): UcpCheckout

Project a Magento checkout cart onto the UCP checkout resource.

@magenxcommerce/engine/agentic/ucp/_lib/signing

packages/engine/src/agentic/ucp/_lib/signing.ts

Business response signing for the UCP surface (RFC 9421 HTTP Message Signatures, RFC 9530 Content-Digest).

Spec: https://ucp.dev/2026-08-25/specification/signatures/

What this proves, and to whom: a platform that fetched our public key from /.well-known/ucp can check that a checkout response really came from this store and was not altered on the way. It is the OUTBOUND counterpart of the platform credential in ./auth.ts, which authenticates INBOUND requests. Nothing here is a shared secret — only the public half is ever published.

Rules that follow from the spec:

  • The profile's root-level keys[] is the only place keys are published. A key is advertised ONLY while we actually sign with it: no configured (or no usable) private key ⇒ no keys[] and no signature headers, never one without the other. A published key we don't sign with would make every verifier report signature_invalid.
  • Signed components for a response are @status, plus content-digest and content-type when there is a body. The digest is over the exact bytes sent, so the body is serialized once, here, and never again.
  • alg is NOT a signature parameter; the verifier derives it from the published JWK. kid is the key's RFC 7638 thumbprint — deterministic, so rotation needs no extra naming config, and the shape Web Bot Auth requires if that interop is ever opted into.
  • ECDSA signatures are raw r||s (IEEE P1363), not DER.

Configuration (runtime, server-only): UCP_SIGNING_KEY PKCS#8 PEM private key — EC P-256 (ES256, the spec's recommended default and the one every verifier must support), EC P-384, or Ed25519. Literal \n sequences are accepted so the PEM can live in a single-line env value. UCP_SIGNING_PREVIOUS_KEYS Optional. One or more PEM keys (public or private) still published during a rotation grace period, so responses signed just before the switch keep verifying. Never used for signing.

SIGNED_CONTENT_TYPE const

const SIGNED_CONTENT_TYPE = "application/json"

JSON media type used for every signed body; it is a covered component.

UcpJwk interface

A public signing key as published in the profile's keys[].

MemberTypeDescription
kidstring
kty"EC" | "OKP"
crv"P-256" | "P-384" | "Ed25519"
xstring
y?string
use"sig"
alg"ES256" | "ES384" | "EdDSA"

thumbprint function

thumbprint(jwk: { kty: string; crv: string; x: string; y?: string; }): string

RFC 7638 JWK SHA-256 thumbprint over the required members, sorted.

publishedSigningKeys function

publishedSigningKeys(): UcpJwk[]

Keys for the profile's root-level keys[]; empty when signing is off.

isResponseSigningEnabled function

isResponseSigningEnabled(): boolean

True when responses are being signed.

contentDigest function

contentDigest(body: string): string

RFC 9530 Content-Digest value for a body.

signResponse function

signResponse(status: number, body: string | null, created: number = Math.floor(Date.now() / 1000)): Record<string, string>

Signature headers for a response, or {} when signing is off.

body must be the exact string that is sent — the digest is over its bytes. created is injectable for deterministic tests.

signRequest function

signRequest(method: string, url: URL, body: string, headers: Record<string, string>, created: number = Math.floor(Date.now() / 1000)): Record<string, string>

Signature headers for a request this store SENDS (order webhooks), or {} when signing is off.

Covers what the spec requires of a business-signed request: @method, @authority, @path, @query when the URL has one, then each of headers (lower-cased names, e.g. ucp-agent, idempotency-key) and the body's content-digest + content-type. Every covered header must be sent with exactly the value given here — the caller merges the returned headers into the ones it passed.

resetSigningKeysForTests function

resetSigningKeysForTests(): void

Test hook: forget the memoized key set.

@magenxcommerce/engine/agentic/ucp/_lib/stripe

packages/engine/src/agentic/ucp/_lib/stripe.ts

Stripe REST calls for the UCP delegated-payment path.

WHY THIS EXISTS AT ALL. Stripe's com.stripe.payments UCP handler has the PLATFORM collect card details at Stripe's credential provider and hand the business a scoped, server-side-chargeable token. That is the one thing this storefront lacked: every other provider here finishes in the browser, which is why UCP complete escalates. A Stripe token can be charged from a server, so complete can genuinely place an order.

WHAT THIS DELIBERATELY DOES NOT DO: create or confirm a PaymentIntent.

Stripe's handler doc charges the token directly with payment_method_data[card][token]=…&confirm=true. Doing that HERE would mean taking the money outside Magento and then asking Magento to place an order — two systems that can diverge, leaving a charge with no order (or an order with no charge) whenever the second step fails.

Instead this module only converts the token into a PaymentMethod, and the EXISTING setPaymentMethodOnCart + placeOrder path — the very one the browser checkout uses — creates the intent, confirms it and creates the order as one Magento operation. Two consequences worth stating plainly:

  • Magento keeps sole ownership of order/payment atomicity. We add no new way for the two to disagree.
  • We never send an amount. Magento charges the quote total it computed, so a platform cannot influence what is charged by anything it puts in the request body. The whole class of "verify the amount before charging" bugs simply does not arise.

No API version is pinned: the two endpoints used here (create a PaymentMethod from a card token, retrieve a PaymentIntent) are long-stable primitives, and pinning would silently diverge from whatever version the Magento Stripe module negotiates for the charge itself.

StripeConfig interface

MemberTypeDescription
secretKeystring
publishableKeystring
merchantIdstring
environment"sandbox" | "production"

readStripeConfig function

readStripeConfig(): StripeConfig | null

Stripe credentials, or null when delegated payment is not configured.

Reads env per call (never module load) so a container restart picks up new values, matching how UCP_PLATFORM_KEYS behaves.

environment is derived from the key prefix rather than configured separately: a sk_test_ key IS a sandbox, and letting an operator declare "production" while holding a test key would publish a profile that lies to platforms about whether real money moves.

isDelegatedPaymentEnabled function

isDelegatedPaymentEnabled(): boolean

True when the operator has switched delegated payment on AND configured it.

Separate from UCP_ENABLE: a merchant may legitimately want the agentic surface without handing agents a chargeable instrument. Off ⇒ the handler registry stays empty and complete escalates exactly as before, so this whole path is opt-in and the previous behaviour is the default.

StripeCallError class

A Stripe API failure, carrying the parts that decide what the platform does.

createPaymentMethodFromToken function

async createPaymentMethodFromToken(token: string, config: StripeConfig, idempotencyKey: string | null): Promise<string>

Turn the platform's stripe_payment_token into a PaymentMethod id.

The UCP credential is a card token (Stripe's handler doc charges it as payment_method_data[card][token]), and setPaymentMethodOnCart wants a pm_…, so this is the one conversion that makes the delegated credential usable by the existing Magento flow.

PaymentIntentStatus type

type PaymentIntentStatus = | "requires_payment_method" | "requires_confirmation" | "requires_action" | "processing" | "requires_capture" | "succeeded" | "canceled"

PaymentIntentState interface

MemberTypeDescription
idstring
statusPaymentIntentStatus
redirectUrlstring | nullURL the BUYER must visit to authenticate (3DS), when Stripe supplies one.
lastErrorMessagestring | nullStripe's reason when the intent's last attempt failed.
lastErrorCodestring | null
lastDeclineCodestring | null

paymentIntentIdFromClientSecret function

paymentIntentIdFromClientSecret(secret: string): string | null

A PaymentIntent id extracted from a client secret (pi_X_secret_Y → pi_X).

Magento returns the client secret, not the id, and the secret must never be sent to Stripe as an id or leaked to a platform — it authorizes confirming the intent from a browser.

retrievePaymentIntent function

async retrievePaymentIntent(clientSecret: string, config: StripeConfig): Promise<PaymentIntentState | null>

Read the intent's true state after Magento placed the order.

This is what distinguishes "paid" from "the buyer still has to do 3DS" from "declined". Magento hands back a client secret either way, so without this call we would report every placed order as completed — including ones whose payment never actually succeeds.

isIntentSettled function

isIntentSettled(status: PaymentIntentStatus): boolean

Intent states that mean the money is secured (or will settle on its own).

@magenxcommerce/engine/agentic/ucp/_lib/types

packages/engine/src/agentic/ucp/_lib/types.ts

UCP wire types — the JSON shapes exchanged with an agent platform.

Mirrors https://ucp.dev/2026-08-25/schemas/shopping/checkout.json and the fulfillment extension. Only the subset this storefront produces or consumes is modelled; unknown fields sent by a platform are ignored rather than rejected (the spec is designed for forward-compatible extension).

UcpStatus type

type UcpStatus = | "incomplete" | "requires_escalation" | "ready_for_complete" | "complete_in_progress" | "completed" | "canceled"

UcpTotalType type

type UcpTotalType = | "subtotal" | "discount" | "items_discount" | "fulfillment" | "tax" | "fee" | "total"

UcpTotal interface

MemberTypeDescription
typeUcpTotalType
amountnumber
display_text?string

UcpMessageType type

type UcpMessageType = "error" | "warning" | "info"

UcpErrorSeverity type

type UcpErrorSeverity = | "recoverable" | "requires_buyer_input" | "requires_buyer_review" | "unrecoverable"

UcpMessage interface

MemberTypeDescription
typeUcpMessageType
codestring
contentstring
severity?UcpErrorSeverity
path?string

UcpLinkType type

type UcpLinkType = | "privacy_policy" | "terms_of_service" | "refund_policy" | "shipping_policy" | "faq"

UcpItem interface

MemberTypeDescription
idstring
titlestring
pricenumber
image_url?string

UcpLineItem interface

MemberTypeDescription
idstring
itemUcpItem
quantitynumber
totalsUcpTotal[]

UcpBuyer interface

MemberTypeDescription
first_name?string
last_name?string
email?string
phone_number?string

UcpDestination interface

A fulfillment destination — schema.org-style postal address field names.

MemberTypeDescription
id?string
type?"shipping_address"Destination discriminator. Required on every destination a business returns since 2026-08-25; optional (and ignored) on platform requests.
name?string
phone_number?string
street_address?string
extended_address?stringSecond address line, when the platform splits it out.
address_locality?string
address_region?string
postal_code?string
address_country?string

UcpDescription interface

Rich-text content; at least one format must be present.

MemberTypeDescription
plain?string
html?string
markdown?string

UcpFulfillmentOption interface

MemberTypeDescription
idstring
titlestring
description?UcpDescriptionAn object since 2026-08-25, not a string. Must not repeat title.
totalsUcpTotal[]

UcpFulfillmentGroup interface

MemberTypeDescription
idstring
line_item_idsstring[]
options?UcpFulfillmentOption[]
selected_option_id?string | null

UcpFulfillmentMethod interface

MemberTypeDescription
idstring
type"shipping" | "pickup"
line_item_idsstring[]
destinations?UcpDestination[]
selected_destination_id?string | null
groups?UcpFulfillmentGroup[]

UcpFulfillment interface

MemberTypeDescription
methodsUcpFulfillmentMethod[]

UcpContext interface

MemberTypeDescription
language?string
currency?string
address_country?stringLocalization hints. Accepted and echoed on a cart; not used for pricing.
address_region?string
postal_code?string

UcpPaymentHandlers type

type UcpPaymentHandlers = Record<string, unknown[]>

Payment handler registry: reverse-domain name → handler declarations.

An OBJECT, not an array (ucp.json constrains propertyNames to reverse-domain names). The declarations themselves are handler-defined, so they stay unknown here rather than being modelled per handler.

UcpPaymentInstrument interface

A payment instrument submitted by the platform on complete.

Only the fields every handler shares are modelled; handlers extend this with their own (Stripe adds credential.type: "stripe_payment_token"), and unknown fields are preserved rather than rejected.

MemberTypeDescription
id?string
handler_id?string
type?string
selected?boolean
credential?Record<string, unknown>
display?Record<string, unknown>

UcpPayment interface

MemberTypeDescription
instruments?UcpPaymentInstrument[]

UcpOrderConfirmation interface

Order confirmation. permalink_url is required alongside id per the schema.

MemberTypeDescription
idstring
permalink_urlstringAbsolute URL where the buyer can view this order.
label?stringHuman-readable label (the merchant-facing order number, here).

UcpDiscountAllocation interface

Where an applied discount landed: RFC 9535 JSONPath + minor units.

MemberTypeDescription
pathstring
amountnumber

UcpAppliedDiscount interface

MemberTypeDescription
code?stringThe code that triggered it; omitted for automatic discounts.
titlestring
amountnumberTotal reduction, positive, in minor units.
automatic?booleanTrue when a merchant rule applied it with no code.
allocations?UcpDiscountAllocation[]

UcpDiscounts interface

MemberTypeDescription
codes?string[]Request: the complete desired set (replaces; [] clears). Response: what is applied.
applied?UcpAppliedDiscount[]

UcpCheckout interface

MemberTypeDescription
ucp{ version: string; capabilities: UcpCapabilityRefs; payment_handlers: UcpPaymentHandlers; }Response envelope. payment_handlers is REQUIRED here, not just in the profile — see _lib/payment.ts. status is omitted on success, where the schema defaults it to "success"; protocol errors set it explicitly.
idstring
statusUcpStatus
currencystring
line_itemsUcpLineItem[]
totalsUcpTotal[]
linksUcpLink[]
buyer?UcpBuyer
context?UcpContext
messages?UcpMessage[]
fulfillment?UcpFulfillment
discounts?UcpDiscounts
expires_at?string
continue_url?string
order?UcpOrderConfirmation

UcpCheckoutInput interface

Request body for create (POST) and update (PUT). The spec models update as a full resource replacement, so both share one shape; every field is optional because a platform may send only the parts it is changing on create.

MemberTypeDescription
line_items?Array<{ id?: string; item?: { id?: string }; quantity?: number; }>
buyer?UcpBuyer
context?UcpContext
fulfillment?{ methods?: Array<{ destinations?: UcpDestination[]; selected_destination_id?: string | null; groups?: Array<{ id?: string; selected_option_id?: string | null }>; }>; }
payment?UcpPaymentSubmitted payment instruments. Optional on create/update and REQUIRED on complete per the schema — so it must at least be READ on complete, even by a business that charges nothing (see _lib/payment.ts).
discounts?UcpDiscountsDiscount extension. Only codes is read; applied is response-only.
cart_id?stringCart to convert (cart capability; create only). When present the cart's contents win and any overlapping line_items/buyer here are ignored.

UcpCapabilityRefs type

type UcpCapabilityRefs = Record<string, Array<{ version: string }>>

Capability registry echoed in cart/order envelopes: name → [{ version }].

UcpCart interface

MemberTypeDescription
ucp{ version: string; capabilities: UcpCapabilityRefs }No payment_handlers pre-checkout, unlike the checkout envelope.
idstring
line_itemsUcpLineItem[]
currencystring
totalsUcpTotal[]Estimates: no fulfillment line until a shipping method is chosen.
linksUcpLink[]
buyer?UcpBuyer
context?UcpContext
messages?UcpMessage[]
discounts?UcpDiscounts
continue_url?string

UcpCartInput interface

Create/update request. line_items is required and a full replacement.

MemberTypeDescription
line_items?UcpCheckoutInput["line_items"]
buyer?UcpBuyer
discounts?UcpDiscounts
context?UcpContext

UcpErrorResponse interface

The spec's generic error resource (common/types/error_response.json): what a cart or order operation returns when there is no resource — e.g. an unknown id. A business outcome, so it rides HTTP 200 / a non-error MCP result.

MemberTypeDescription
ucp{ version: string; status: "error"; capabilities: UcpCapabilityRefs }
messagesUcpMessage[]
continue_url?string

UcpLineItemQuantity interface

A line item id + step count, as fulfillment events and adjustments cite them.

MemberTypeDescription
idstring
quantitynumber

UcpOrderLineItem interface

MemberTypeDescription
idstring
itemUcpItem
quantity{ original: number; total: number; fulfilled: number }
totalsUcpTotal[]
status"processing" | "partial" | "fulfilled" | "removed"

UcpPostalAddress interface

MemberTypeDescription
street_address?string
extended_address?string
address_locality?string
address_region?string
postal_code?string
address_country?string
first_name?string
last_name?string
phone_number?string

UcpExpectation interface

MemberTypeDescription
idstring
line_itemsUcpLineItemQuantity[]
method_type"shipping" | "pickup" | "digital"
destinationUcpPostalAddress
description?string

UcpFulfillmentEvent interface

MemberTypeDescription
idstring
occurred_atstring
typestring
line_itemsUcpLineItemQuantity[]
tracking_number?string
tracking_url?string
carrier?string
description?string

UcpAdjustment interface

MemberTypeDescription
idstring
typestring
occurred_atstring
status"pending" | "completed" | "failed"
line_items?UcpLineItemQuantity[]
totals?UcpTotal[]
description?string

UcpOrder interface

MemberTypeDescription
ucp{ version: string; capabilities: UcpCapabilityRefs }
idstring
label?string
checkout_idstring
permalink_urlstring
line_itemsUcpOrderLineItem[]
fulfillment{ expectations: UcpExpectation[]; events: UcpFulfillmentEvent[] }
adjustmentsUcpAdjustment[]
currencystring
totalsUcpTotal[]
messages?UcpMessage[]

@magenxcommerce/engine/agentic/ucp/carts/[id]/cancel/route

packages/engine/src/agentic/ucp/carts/[id]/cancel/route.ts

POST /api/ucp/carts/{id}/cancel — UCP "Cancel Cart".

Returns the cart as it was; afterwards the id answers not_found. See cancelCartSession for how that is made true on a Magento quote.

POST function

async POST(request: Request, { params }: RouteContext): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/carts/[id]/route

packages/engine/src/agentic/ucp/carts/[id]/route.ts

GET /api/ucp/carts/{id} — UCP "Get Cart" PUT /api/ucp/carts/{id} — UCP "Update Cart" (full replacement: line_items is the complete desired set)

An unknown, canceled or already-ordered cart answers not_found as the spec's error_response with HTTP 200 — a business outcome, not a 404.

GET function

async GET(request: Request, { params }: RouteContext): Promise<NextResponse>

PUT function

async PUT(request: Request, { params }: RouteContext): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/carts/route

packages/engine/src/agentic/ucp/carts/route.ts

POST /api/ucp/carts — UCP "Create Cart" (dev.ucp.shopping.cart).

A cart is a Magento guest quote, the same thing a checkout session is — see _lib/cart.ts for why that makes create_checkout { cart_id } trivially correct. The operations themselves are shared with MCP in _lib/cart-service.ts.

POST function

async POST(request: Request): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/catalog/lookup/route

packages/engine/src/agentic/ucp/catalog/lookup/route.ts

POST /api/ucp/catalog/lookup — UCP "Lookup Catalog (batch)" (dev.ucp.shopping.catalog.lookup).

POST function

async POST(request: Request): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/catalog/product/route

packages/engine/src/agentic/ucp/catalog/product/route.ts

POST /api/ucp/catalog/product — UCP "Get Product" (dev.ucp.shopping.catalog.lookup).

POST function

async POST(request: Request): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/catalog/search/route

packages/engine/src/agentic/ucp/catalog/search/route.ts

POST /api/ucp/catalog/search — UCP "Search Catalog" (dev.ucp.shopping.catalog.search).

POST function

async POST(request: Request): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/checkout-sessions/[id]/cancel/route

packages/engine/src/agentic/ucp/checkout-sessions/[id]/cancel/route.ts

POST /api/ucp/checkout-sessions/{id}/cancel — UCP "Cancel Checkout".

Magento has no "delete quote" GraphQL mutation, so abandoning a session is modelled as emptying its cart: the quote survives (harmless, and it expires on Magento's own schedule) but holds nothing, so a continue_url opened afterwards correctly shows an empty checkout rather than resurrecting an abandoned order.

Idempotent by construction — removing lines that are already gone is a no-op (see emptyCart), and cancel from any state is legal per the spec.

POST function

async POST(request: Request, { params }: RouteContext): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/checkout-sessions/[id]/complete/route

packages/engine/src/agentic/ucp/checkout-sessions/[id]/complete/route.ts

POST /api/ucp/checkout-sessions/{id}/complete — UCP "Complete Checkout".

Two behaviours, selected by whether a payment handler is declared:

  NO HANDLER (default) — nothing here can be charged server-side, so this
  returns `requires_escalation` with `continue_url` and reports any submitted
  instrument as uncharged. Naturally idempotent: no order is created.

  STRIPE HANDLER CONFIGURED — the platform's `stripe_payment_token` is
  charged and the order placed. See `_lib/complete.ts` for the rules; the
  decision logic lives there so this route and the MCP binding cannot differ.

Idempotency-Key is REQUIRED once charging is possible: the REST binding mandates it on state-modifying operations, and a retried complete must not charge twice. It is deliberately NOT required when escalating, so a platform that worked against the previous behaviour keeps working.

POST function

async POST(request: Request, { params }: RouteContext): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/checkout-sessions/[id]/route

packages/engine/src/agentic/ucp/checkout-sessions/[id]/route.ts

GET /api/ucp/checkout-sessions/{id} — UCP "Get Checkout" PUT /api/ucp/checkout-sessions/{id} — UCP "Update Checkout"

Update is a full resource replacement per the spec: a line_items array, when present, is the complete desired set (see _lib/apply.ts).

GET function

async GET(request: Request, { params }: RouteContext): Promise<NextResponse>

PUT function

async PUT(request: Request, { params }: RouteContext): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/checkout-sessions/route

packages/engine/src/agentic/ucp/checkout-sessions/route.ts

POST /api/ucp/checkout-sessions — UCP "Create Checkout".

Opens a Magento guest quote and applies whatever the platform already knows (line items, buyer, destination, fulfillment choice). The returned session id IS the masked quote id, so no session store is needed and the same cart can later be resumed by a human through continue_url.

With cart_id (cart capability) no quote is created: a cart is already a quote, so the checkout IS that cart and its id is the cart id. Converting the same cart twice therefore returns the same session, as the spec requires, and checkout edits are reflected in the cart because there is only one.

POST function

async POST(request: Request): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/mcp/route

packages/engine/src/agentic/ucp/mcp/route.ts

POST /api/ucp/mcp — the UCP capabilities (checkout, catalog, cart, order) over the MCP binding.

Same five operations and same response schema as the REST routes; only the envelope differs (JSON-RPC 2.0 tools/call instead of HTTP verbs). The commerce logic and the authorization decision are shared — see _lib/mcp.ts.

WHY HAND-ROLLED, NO @modelcontextprotocol/sdk: this server's surface is strictly request/response — a handful of tools, no resources, no prompts, no sampling, no server-initiated messages — so the SDK's session management and SSE machinery would be dependency weight for nothing, and this repo has a standing preference for avoiding wrapper deps (it has twice removed unused ones). MCP's streamable HTTP transport explicitly permits answering a POST with a single JSON response instead of opening a stream, which is all we need. If a future capability requires real streaming or the wider MCP feature surface, swap the SDK in behind this same route.

Batching is rejected: MCP dropped JSON-RPC batch support in 2025-06-18.

POST function

async POST(request: Request): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/orders/[id]/route

packages/engine/src/agentic/ucp/orders/[id]/route.ts

GET /api/ucp/orders/{id} — UCP "Get Order" (dev.ucp.shopping.order).

The current state of an order this platform placed through complete: line quantities and status, shipments with tracking, refunds. An order placed by anyone else reads exactly like one that does not exist — see _lib/order-service.ts for the authorization rule and why.

GET function

async GET(request: Request, { params }: RouteContext): Promise<NextResponse>

@magenxcommerce/engine/agentic/ucp/profile/route

packages/engine/src/agentic/ucp/profile/route.ts

The UCP business profile, served at /.well-known/ucp (rewritten to this route in next.config.ts — a Next App Router segment cannot be named .well-known, since the file-system router ignores dot-prefixed folders).

This is the discovery document: a platform fetches it first to learn which capabilities the business supports and where to call them. Generated from magenx.config.ts at request time, the same pattern as app/llms.txt and robots.ts, so it tracks NEXT_PUBLIC_SITE_URL and the configured footer links automatically.

PUBLIC ON PURPOSE — discovery precedes authentication, so no platform credential is required here. It therefore exposes only non-sensitive information: capability names, versions, the endpoint path, and legal URLs that are already public pages. It still 404s when the surface is switched off, so a store that has not opted in advertises nothing.

keys[] (the root-level JWK Set, the canonical field since 2026-08-25; signing_keys is the legacy name) carries the public half of the response signing key when UCP_SIGNING_KEY is configured, and is omitted otherwise — advertising a key we don't sign with would be worse than advertising none. See _lib/signing.ts.

GET function

async GET(request?: Request): Promise<NextResponse>