Packages Source: packages/core/README.md

@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 unknown and returning Result<T, ParseError> without throwing: parseShopDomain, parseProductId, parseVariantId, parseCartId, parseCountryCode, parseBuyerIp and parseSecret. parseMoney({ amount: "200.00", currency: "USD" }) builds price filters and budgets. A ParseError has fixed message and hint text per target and never contains the input.
  • readUntrustedText(text), the only reader of UntrustedText.
  • createHandoffVault(), an in-memory store for continue_url values. put returns a HandoffRef of 128 random bits from node:crypto. Only refs from the same vault resolve.
  • createCartRefRegistry(), an in-memory map from CartRef to the redacted CartId and its shop. The model sees only the CartRef: cart_ plus 128 random bits from node:crypto, holding nothing of the cart id or shop. put returns the same ref for the same cart and shop, and refuses the same cart on another shop with invalid_input. Only refs from the same registry resolve. toJSON, toString and util.inspect give a placeholder.
  • createUcpClient(config, deps?). deps takes only clock and random; production callers pass nothing.
  • createHttpTransport, createFixtureTransport (needed for an offline config), UcpError, systemClock and 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

  1. Refuses tool names outside UcpToolName (tool_not_allowed).
  2. Refuses the call when agentProfileUrl is unset (agent_profile_required). The URL goes out as meta["ucp-agent"].profile on every tools/call.
  3. Checks the endpoint policy (endpoint_not_allowed). discovered allows Global Catalog, configured extraShops, and shops core itself set as Variant.shop in an earlier response. allowlist allows the listed shops, and Global Catalog only with allowGlobalCatalog. offline sends everything to the fixture transport.
  4. At the Token tier, refuses a shop call without options.buyer (buyer_ip_required) and otherwise sends Shopify-Buyer-IP.
  5. 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-After block and allow 2 concurrent reads per shop.
  6. 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-After sets the minimum wait, and a Retry-After above 30 s fails fast with rate_limited and retryAfterMs. A JSON-RPC result is never retried.
  7. Reads only result.structuredContent, never result.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 before exp (or 50 minutes after minting when exp is 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 with source: "external", an ExternalMerchant seller or a gid://catalog/ id are dropped; a product with only such variants is dropped.
  • Variant.shop comes from seller.domain only when seller.id starts with gid://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 from url, seller.url or checkout_url.
  • Prices are { amount, currency } minor units. A missing or unknown currency fails the call with invalid_response. Price filters go out as minor units in catalog.filters.price with catalog.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. lookupCatalog sends 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. CartId and CheckoutId are Redacted: toJSON and toString give "[redacted]", and the value is revealed only on the wire. A cart id is gid://shopify/Cart/<token> (the docs example is gid://shopify/Cart/cart_abc123), a checkout id gid://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 with invalid_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 config and a hint to set SHOPIFY_CLIENT_ID and SHOPIFY_CLIENT_SECRET, before any I/O. Token-tier calls without options.buyer fail with buyer_ip_required, before any I/O.
  • PUT semantics. update_cart and update_checkout replace the whole object. Core sends line_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: no continue_url, expires_at, totals, messages, ucp, currency, status, buyer, payment, fulfillment or links. 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. createCheckout joins the queue of its cart, so it converts the cart as the last finished update left it. Mutations wait for a shop's Retry-After block 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_cart and cancel_checkout send one crypto.randomUUID() as meta["idempotency-key"], reused on every retry of that call. A JSON-RPC result is never retried.
  • continue_url. Lifted into ContinueUrl on every parse, before anything else is read, and registered with the log scrubber; a value that is not a plain https URL fails with invalid_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. Merchant messages[].content is scrubbed (registered values, longest first, and URL query strings), then becomes UntrustedText. result.content is 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 (&#45;, &#x2d;, with or without ;) and a short list of named ones (&amp;, &nbsp;, &hyphen;, &ndash;, &mdash; 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 encoded continue_url, is redacted as a whole. Not covered: query parameter names, and named references outside the list.
  • Orphan carts and checkouts. When a create_cart or create_checkout result fails with invalid_response but holds an id core can parse, core sends cancel_cart or cancel_checkout for 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_response and registers nothing, so the parse that brought the value fails (public parsers return a ParseError). 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.outcome is the status as a typed value: escalation (from requires_escalation, with continueUrl required), ready (ready_for_complete; Tote never completes, the buyer continues at continueUrl), incomplete, canceled, or other with the raw status. Branch on outcome, not on status. requires_escalation without a continue_url fails with invalid_response. A create that returns no checkout id (Checkout errors page, "Checkout not created") fails with tool_error and the merchant messages.
  • cancelCart and cancelCheckout resolve 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.