@artos-commerce/ucp-client
v0.10.0
Published
Build-track Direct UCP client for Artos: typed UCP transport, AP2 mandate signing, checkout orchestration, buyer-account tools, and buyer OAuth so you can build your own commerce-grade UCP client without hand-rolling the envelope, signing, and credential
Readme
@artos-commerce/ucp-client
Build-track Direct UCP client for Artos. A typed UCP transport, AP2 mandate
signing, checkout orchestration, buyer-account tools, and buyer OAuth so you can
build your own commerce-grade UCP client against api.artos.sh — without
hand-rolling the JSON-RPC envelope, the canonical-JSON signing bytes, the AP2
mandates, or the payment-rail rules.
This is the reusable core extracted from the hosted Artos MCP bridge. If you just
want an MCP endpoint for AI agents, point them at the hosted Connect bridge
(https://agent.artos.sh/mcp) and skip this package. Reach for
@artos-commerce/ucp-client when you are building your own
client/integration (the Build track) and want the hard parts — signing,
verification, and rail selection — done correctly for you.
What it does for you
- Transport (
UcpClient): global catalog search (REST) and per-store / buyer-account shopping over the UCP MCP JSON-RPC transport, with the UCP-Agent preamble, idempotency keys, the two-credential auth model, and the 401 silent-refresh relay all handled. - AP2 signing (
Ap2Signer): mints the compact ES256checkout_mandate/payment_mandatethe API requires, over byte-parity canonical JSON. - Verification (
verifyMerchantAuthorization): re-checks the store-signed terms before you authorize a spend. - Checkout orchestration (
createCheckoutHandlers): a singleconfirmPurchasere-prices, verifies, mints the mandate, routes to the$0/ card / crypto rail, and returns a structuredCheckoutOutcome. - Buyer-account tools (
createAccountHandlers): typed wrappers over the buyer's account MCP (get_buyer_context,list_my_orders, wallet balances, coupons, …) — all buyer-bound. - Buyer OAuth (
OAuthClient+createPkce): discover the Authorization Server, build the PKCE authorize URL, and exchange/refresh tokens so a Build-track agent can run buyer sign-in itself.
Install
npm install @artos-commerce/ucp-client
# Only if you need the crypto settlement rail:
npm install @mysten/suiRequires Node 22+ (for global fetch and base64url). @mysten/sui is an
optional peer dependency — card-only integrations don't need it.
Quickstart
import {
UcpClient,
Ap2Signer,
createCheckoutHandlers,
} from '@artos-commerce/ucp-client';
// The crypto rail is import-isolated on the `/crypto` subpath so a card-only
// import of the root barrel never pulls in the optional `@mysten/sui` peer.
import { resolveCryptoDeps } from '@artos-commerce/ucp-client/crypto';
const client = new UcpClient(
{
artosBaseUrl: 'https://api.artos.sh',
platformApiKey: process.env.UCP_PLATFORM_API_KEY!, // "<clientId>.<secret>"
platformProfileUrl: 'https://you.example/.well-known/ucp',
},
{
// The current buyer's OAuth bearer (server-side only — never ship it to a
// browser). Omit for anonymous/card-only sessions.
buyerToken: session.buyerBearer,
// Relay a 401 challenge so the agent can silently refresh its token.
onAuthChallenge: (wwwAuthenticate) => respondWith401(wwwAuthenticate),
},
);
const signer = new Ap2Signer(
JSON.parse(process.env.AGENT_PRIVATE_JWK!), // EC P-256 private JWK
process.env.AGENT_KID!, // must match your published profile's public JWK kid
);
// Optional crypto rail (needs @mysten/sui):
const crypto = resolveCryptoDeps({
agentSuiPrivateKey: process.env.AGENT_SUI_PRIVATE_KEY, // suiprivkey1...
suiNetwork: 'mainnet',
agentMaxSpendAmount: 50_000, // optional client-side cap (minor units)
});
const shop = createCheckoutHandlers({ client, signer, crypto });Search → cart → checkout → buy
// 1. Discover (price filters are MAJOR units; converted to minor for you).
const results = await shop.searchProducts({
query: 'running shoes',
filters: { price: { max: 150, currency: 'USD' } },
});
// 2. Build a checkout (per store, by slug from the search result metadata).
const checkout = await shop.createCheckout({
storeSlug: 'energy-sport',
items: [{ id: 'prod_123', quantity: 1 }],
shippingAddress: { country: 'US', postal_code: '94016' },
});
// 3. Confirm: re-prices, verifies the store signature, mints the AP2 mandate,
// routes the rail, and returns a structured outcome.
const outcome = await shop.confirmPurchase({
storeSlug: 'energy-sport',
checkoutId: checkout.id as string,
paymentMethod: 'artos.card', // omit on a multi-rail store to be asked
});
switch (outcome.status) {
case 'completed':
return renderOrder(outcome.checkout);
case 'escalation_required':
return redirect(outcome.continueUrl); // 3-DS / hosted step
case 'payment_selection_required':
return askBuyerToPickRail(outcome.rails);
case 'error':
return showError(outcome.code, outcome.message);
}confirmPurchase never throws for a business outcome — it always resolves to a
CheckoutOutcome. Transport failures (network / non-2xx / JSON-RPC error) still
throw UcpClientError; an expired buyer bearer throws UcpAuthError carrying
the WWW-Authenticate challenge.
Buyer sign-in (OAuth) and account tools
A Build-track agent can run the buyer-OAuth dance itself instead of relying on the hosted Connect bridge:
import { OAuthClient, createPkce } from '@artos-commerce/ucp-client';
const oauth = new OAuthClient({ artosBaseUrl: 'https://api.artos.sh' });
const pkce = createPkce();
// 1. Send the buyer here to sign in + consent (offline_access by default).
const { url, state } = await oauth.authorizeUrl({
clientId: 'https://you.example/well-known/oauth-client.json',
redirectUri: 'https://you.example/oauth/callback',
codeChallenge: pkce.challenge,
});
// 2. On the redirect (verify `state`), exchange the code for tokens.
const tokens = await oauth.exchangeCode({
code,
codeVerifier: pkce.verifier,
clientId: 'https://you.example/well-known/oauth-client.json',
redirectUri: 'https://you.example/oauth/callback',
});
// 3. Later, silently renew with the rotating refresh token.
const fresh = await oauth.refresh({ refreshToken: tokens.refreshToken! });With tokens.accessToken as the buyerToken, the account tools are typed:
import { createAccountHandlers } from '@artos-commerce/ucp-client';
const account = createAccountHandlers({ client }); // client carries buyerToken
const me = await account.getBuyerContext();
const orders = await account.listOrders({ limit: 10 });The two-credential auth model
The Artos API's identity guard treats the two credentials as answering different
questions: the key authorizes (which stores may this call reach) and the
bearer identifies (which buyer is this). UcpClient encodes the three modes:
platform(default) sends theX-API-Keyand authenticates at any store the credential covers: catalog, cart, checkout create/update,get_order, card completion.buyersends only the bearer, because on these calls the buyer is the principal — cryptoprepare/completeand all/account/*tools. The API resolves the buyer account and enforces their stored authorization + caps.platform+buyersends both: the API authorizes on the key (so a white-label partner credential stays confined to its allowlisted stores) and takes the buyer identity from the bearer. This is what the coupon attach onupdate_checkoutuses.
Either buyer mode falls back to the key alone when the client carries no
buyerToken.
API surface
UcpClient—globalSearch,callGlobalTool,callStoreTool,listAccountTools,callAccountTool,fetchStoreProfile,fetchImage,hasBuyerToken,ucpAgentHeader.Ap2Signer—mintCheckoutMandate,mintPaymentMandate.canonicalJson,verifyDetachedJws,verifyMerchantAuthorization.createCheckoutHandlers— read tools +confirmPurchase.createAccountHandlers— typed buyer-account tools (buyer-bound).OAuthClient,createPkce,DEFAULT_BUYER_SCOPE— buyer OAuth (PKCE).- Helpers:
toMinorUnits,normalizeSearchFilters,resolveRail,availableRails,grandTotal,currencyOf,asAllowanceId,isUcpError,messageOf.
The crypto settlement rail is not on the root barrel (it would eagerly pull
the optional @mysten/sui peer into card-only consumers). Import it from its
dedicated subpaths instead:
@artos-commerce/ucp-client/crypto—resolveCryptoDeps,CryptoDeps.@artos-commerce/ucp-client/sui—SuiSigner,SuiSignerError(needs@mysten/sui).
Subpath entries are also published: @artos-commerce/ucp-client/ucp,
/ap2, /checkout, /account, /oauth, /sui, /crypto.
Security notes
- Money is integer minor units everywhere; only the search-filter / display edge speaks major units.
- Canonical JSON is byte-parity with
artos-apiso a store'smerchant_authorization(and your minted mandates) verify. Don't fork it. - Keep the buyer bearer server-side. This package mints/forwards it from a server; never expose it to a browser.
License
MIT
