@tote/core
On this page (8 sections)
UCP client for Tote: auth tiers, rate limits, retries, endpoint policy. The design is
ADR-001; the public types in src/index.ts are the
contract.
On npm: tote-agent-core. Release steps: scripts/release.md.
Status (T-04): catalog, cart and checkout are implemented and tested offline on fixtures
built from shopify.dev examples. Catalog and cart work at the Anonymous and Token tiers;
checkout needs the Token tier. Signed configs are validated, but Signed calls throw
not_implemented until request signing lands. No code path calls complete_checkout.
Usage
import { createUcpClient, readUntrustedText } from "@tote/core";
const client = createUcpClient({
auth: { tier: "anonymous" },
endpointPolicy: { mode: "discovered" },
agentProfileUrl: "https://tote.example/.well-known/ucp", // TOTE_AGENT_PROFILE_URL, H-04
});
const page = await client.searchCatalog({ query: "trail running shoes", limit: 10 });
for (const product of page.products) {
// Merchant text is UntrustedText. Read it only to show it to the human or inside the
// agent's untrusted envelope.
console.log(readUntrustedText(product.title));
}
Runtime surface
These are the only ways code outside core gets a core-minted value (ADR-001 decision 2):
- Parsers, each taking
unknownand returningResult<T, ParseError>without throwing:parseShopDomain,parseProductId,parseVariantId,parseCartId,parseCountryCode,parseBuyerIpandparseSecret.parseMoney({ amount: "200.00", currency: "USD" })builds price filters and budgets. AParseErrorhas fixedmessageandhinttext per target and never contains the input. readUntrustedText(text), the only reader ofUntrustedText.createHandoffVault(), an in-memory store forcontinue_urlvalues.putreturns aHandoffRefof 128 random bits fromnode:crypto. Only refs from the same vault resolve.createCartRefRegistry(), an in-memory map fromCartRefto the redactedCartIdand its shop. The model sees only theCartRef:cart_plus 128 random bits fromnode:crypto, holding nothing of the cart id or shop.putreturns the same ref for the same cart and shop, and refuses the same cart on another shop withinvalid_input. Only refs from the same registry resolve.toJSON,toStringandutil.inspectgive a placeholder.createUcpClient(config, deps?).depstakes onlyclockandrandom; production callers pass nothing.createHttpTransport,createFixtureTransport(needed for an offline config),UcpError,systemClockand the default retry and timeout policies.
const shop = parseShopDomain("example.myshopify.com"); // from config or tool input
if (!shop.ok) throw new Error(shop.error.message); // message never echoes the input
Test files import fakes from @tote/core/testing: fakeShopDomain, fakeProductId,
fakeVariantId, fakeCartId and fakeBuyerIp run the matching parser and throw on what
it refuses; fakeContinueUrl takes only https://example.invalid/...; fakeCheckoutId
takes only what core's checkout id parser takes (gid://shopify/Checkout/<token> with an
optional ?key=<token>); fakeCartRef() is a well-formed ref no registry knows; fakeUntrustedText wraps any string;
fakeUcpClient(handlers, tier?) rejects any method without a handler, naming the method.
Lint forbids importing this entry from any src/ folder.
What every call does
- Refuses tool names outside
UcpToolName(tool_not_allowed). - Refuses the call when
agentProfileUrlis unset (agent_profile_required). The URL goes out asmeta["ucp-agent"].profileon everytools/call. - Checks the endpoint policy (
endpoint_not_allowed).discoveredallows Global Catalog, configuredextraShops, and shops core itself set asVariant.shopin an earlier response.allowlistallows the listed shops, and Global Catalog only withallowGlobalCatalog.offlinesends everything to the fixture transport. - At the Token tier, refuses a shop call without
options.buyer(buyer_ip_required) and otherwise sendsShopify-Buyer-IP. - Waits for the rate limit: Global Catalog 5 requests per second per client id for Token
and Signed, 1 per second per process for Anonymous (with a one-time warning). Shop
endpoints wait for any
Retry-Afterblock and allow 2 concurrent reads per shop. - Sends with a 15 s per-attempt timeout inside a 60 s budget, and retries per the table in
ADR-001 decision 4: reads retry on 429, 408, 5xx, timeout and network errors with full
jitter;
Retry-Aftersets the minimum wait, and aRetry-Afterabove 30 s fails fast withrate_limitedandretryAfterMs. A JSON-RPC result is never retried. - Reads only
result.structuredContent, neverresult.content.
Auth
- Anonymous: no headers.
- Token: client credentials grant at
https://api.shopify.com/auth/access_token. The JWT is kept in memory, refreshed when less than 10 minutes remain beforeexp(or 50 minutes after minting whenexpis unreadable), one refresh at a time. A 401 refreshes once and retries once. - Signed: the config must be an ECDSA P-256 PKCS#8 key with a key id and a non-empty
development-store allowlist without Global Catalog. Calls return
not_implemented.
Network transport
createHttpTransport() posts JSON-RPC 2.0 tools/call over HTTPS with node:https. It
resolves the host once per attempt, refuses the host when any answer is loopback, private,
link-local, unspecified, multicast or reserved (IPv4-mapped, IPv4-compatible and NAT64 IPv6
forms included), and connects to the accepted address with the original host name as Host
and TLS server name, without a second lookup. Redirects are refused. Global fetch cannot
be used for this, because it has no per-request DNS hook without the undici package.
Catalog parsing
- Global Catalog search always sends
catalog.sources: ["shopify"]. Variants withsource: "external", anExternalMerchantseller or agid://catalog/id are dropped; a product with only such variants is dropped. Variant.shopcomes fromseller.domainonly whenseller.idstarts withgid://shopify/Shop/and the domain passes the shop domain parser. On a shop endpoint (Storefront Catalog) it is the shop the request went to. Never fromurl,seller.urlorcheckout_url.- Prices are
{ amount, currency }minor units. A missing or unknown currency fails the call withinvalid_response. Price filters go out as minor units incatalog.filters.pricewithcatalog.context.currency; mixed currencies omit both. - Merchant text becomes
UntrustedText: control characters (except newline and tab), every format character (zero-width, bidi, soft hyphen, Unicode tag characters) and variation selectors, private-use characters and the Hangul fillers U+115F, U+1160, U+3164 and U+FFA0 dropped, U+2028 and U+2029 turned into newlines,<and>escaped, then truncated on whole escapes (title 200, option 100, description 1000, message 300), so the escaped text stays within the limit. - Page size is clamped to 1..50 and pagination stops at 1,000 results.
lookupCatalogsends 50 ids per request, merges the batches, and refuses more than 1,000 ids per call.
Cart and checkout
Sources: Cart MCP, Checkout MCP and Checkout errors, fetched 2026-11-12.
const buyer = { ip: buyerIp }; // from parseBuyerIp(TOTE_BUYER_IP); Token tier only
const cart = await client.createCart(shop, { lines: [{ variantId, quantity: 2 }] }, { buyer });
const checkout = await client.createCheckout(shop, { cartId: cart.id }, { buyer });
if (checkout.outcome.kind === "escalation") {
// checkout.outcome.continueUrl is the handoff. Put it in the HandoffVault; never log it.
}
- Ids.
CartIdandCheckoutIdareRedacted:toJSONandtoStringgive"[redacted]", and the value is revealed only on the wire. A cart id isgid://shopify/Cart/<token>(the docs example isgid://shopify/Cart/cart_abc123), a checkout idgid://shopify/Checkout/<token>, each with an optional?key=<token>; a token is 1 to 256 letters, digits,_or-. An id that core did not mint is refused withinvalid_input, and a known id used with another shop is refused too. - Lines. 1 to 50 lines (0 allowed on update), quantity an integer from 1 to 10, no variant twice. Checked before any request.
- Tiers. Cart works at every tier. Checkout at the Anonymous tier fails with
configand a hint to setSHOPIFY_CLIENT_IDandSHOPIFY_CLIENT_SECRET, before any I/O. Token-tier calls withoutoptions.buyerfail withbuyer_ip_required, before any I/O. - PUT semantics.
update_cartandupdate_checkoutreplace the whole object. Core sendsline_items({ item: { id }, quantity }, no server line ids) from the input, the input context or else the context it last sent for that id, and the attribution it last parsed (the ten keys the Cart MCP page lists). Nothing else is sent: nocontinue_url,expires_at,totals,messages,ucp,currency,status,buyer,payment,fulfillmentorlinks. When the client holds no state for an id, it reads the cart or checkout first. State is kept in memory for at most 1,000 ids per client. - Concurrency. One mutation at a time per cart id and per checkout id, in call order.
createCheckoutjoins the queue of its cart, so it converts the cart as the last finished update left it. Mutations wait for a shop'sRetry-Afterblock but do not take one of the two read slots. - Retries. Creates retry only on 429 and on failures before any request byte was written.
Updates and cancels retry like reads.
cancel_cartandcancel_checkoutsend onecrypto.randomUUID()asmeta["idempotency-key"], reused on every retry of that call. A JSON-RPC result is never retried. continue_url. Lifted intoContinueUrlon every parse, before anything else is read, and registered with the log scrubber; a value that is not a plainhttpsURL fails withinvalid_response. Core registers a fixed set per URL, all or none: the URL, origin plus path without query or fragment, and the last path segment, the fragment and the first 32 query values when 10 or more characters long (each query value as written and decoded). Later query values are ignored. That is at most 69 values per URL. Cart and checkout ids register the id and its first 32 query values. Merchantmessages[].contentis scrubbed (registered values, longest first, and URL query strings), then becomesUntrustedText.result.contentis never read.- Other spellings of a secret. The scrubber folds the text and every registered value the
same way and matches again: HTML numeric references (
-,-, with or without;) and a short list of named ones (&, ,‐,–,—and others for URL characters) are decoded, percent escapes are decoded (a run that is not valid UTF-8 decodes only its ASCII bytes), Unicode NFKC is applied (NFD and fullwidth forms), every space separator such as U+00A0 becomes a space, U+2010 to U+2015, U+2212 and similar dashes become-, and hidden characters are dropped, repeated until stable. When this finds a secret, the folded text with the secret redacted is returned (merchant text is then still escaped by the sanitizer); otherwise the text keeps its own spelling. A secret spelled another way as a whole, such as an encodedcontinue_url, is redacted as a whole. Not covered: query parameter names, and named references outside the list. - Orphan carts and checkouts. When a
create_cartorcreate_checkoutresult fails withinvalid_responsebut holds an id core can parse, core sendscancel_cartorcancel_checkoutfor it and then rethrows the original error. A failed cancel is logged with the tool name and error code only. - Caps. The log scrubber never removes a registered value. It holds at most 10,000; a
registration that does not fit fails closed with
invalid_responseand registers nothing, so the parse that brought the value fails (public parsers return aParseError). Restart the process to start again. The cart ref registry holds 1,000 carts and the handoff vault 1,000 URLs; when full, the least recently put or used entry is dropped and its ref no longer resolves. A long-running process should create one registry and one vault per session. - Results without money (cart not found, canceled, quantity adjusted) parse without a currency. A cart not found keeps the requested id and has no lines.
Checkout.outcomeis the status as a typed value:escalation(fromrequires_escalation, withcontinueUrlrequired),ready(ready_for_complete; Tote never completes, the buyer continues atcontinueUrl),incomplete,canceled, orotherwith the rawstatus. Branch onoutcome, not onstatus.requires_escalationwithout acontinue_urlfails withinvalid_response. A create that returns no checkout id (Checkout errors page, "Checkout not created") fails withtool_errorand the merchant messages.cancelCartandcancelCheckoutresolve to nothing; core forgets the id's state.
Tests
pnpm test runs offline. test/setup/network-guard.ts makes fetch, TCP connects and DNS
lookups throw in every test file. The agent, mcp and cli vitest configs load the same file.
Contract fixtures in test/fixtures/ are built only from
examples on shopify.dev and carry source: "docs"; test/fixtures.test.ts scans them for
tokens, IP addresses, emails, phone numbers, foreign continue_url hosts and checkout keys.
Docs fixtures replace each continue_url with https://example.invalid/continue and each
checkout key with redacted; each file's note says what was left out.