Skip to content

agentic-commerce

Terminal window
npx skills add https://github.com/crystallizeapi/ai --skill agentic-commerce

Agentic Commerce on Crystallize

Agents shop a store in three places: a remote MCP server that Claude, ChatGPT and other hosts connect to; WebMCP tools in the shopper’s own browser tab; and an on-site assistant in the store. All three run on the same code as the storefront: Discovery for the catalogue and ranking, the Shop API for baskets, orders and bookings. No Core, no extra state.

This is the active half. Being found and quoted (JSON-LD, llms.txt, Markdown twins, crawlers) is in [[seo-geo]]; the storefront it runs inside is [[storefront]].

Built and running on two Crystallize stores, Tools Universe (18 tools, typed ETIM specs, rentals) and a camera store (15 tools, typed lens and camera specs), September–November 2026, on Next.js 16 and the MCP TypeScript SDK with @modelcontextprotocol/ext-apps. WebMCP is designed but not shipped by either: it is an early preview behind a Chrome flag.

Three surfaces, one code path

Remote MCP server WebMCP On-site assistant
Agent Claude, ChatGPT, VS Code, any MCP host The agent in the shopper’s browser (Gemini in Chrome, extensions) Your own model loop, in the store’s UI
Where it runs app/api/mcp/route.ts, stateless Streamable HTTP The store’s pages app/api/assistant/route.ts, streaming
Who the shopper is OAuth access token (optional, lazy) The page’s session (cookies) The page’s session
Basket cartId passed between calls, a hand-off link to pay The page’s cart cookie The page’s cart cookie
Results MCP Apps cards, else Markdown with links The page updates as the agent works The store’s own product cards

Use the same tool names and arguments on all three (snake_case: search_products, get_product, add_to_cart, view_cart, checkout), so an agent that knows one surface knows the others. Call the same server-side functions the storefront’s actions call.

What an agent needs from the model

  • Typed specs. Numbers with units, booleans and selections, not a label/value table. Discovery indexes each as its own filter field: a numeric in a nested piece is <component>_<piece>_<field>_number, a boolean is <…>_<field>, and each selection option is its own field <…>_<field>_<optionKeyCamel> filtered with exists: true. “18V impact driver over 200 Nm” then becomes three hard filters instead of a fuzzy text match where 12 V and 150 Nm score almost as well. See [[content-model]] and [[query]].
  • One unit per numeric where possible: Discovery range filters ignore the unit.
  • Unset booleans read false. An agent filter for “without Bluetooth” must not match products that just don’t say.
  • Taxonomy topics for product types, brands, platforms, trades, in every language: they are what the parser matches words against, from Discovery facets.
  • A taste vector per shopper for ranking: rebuilt from Shop API order history per call, sent as context.userTaste, with { signal: relevance } added when there is a text term ([[vector-ranking]]).

The MCP server, in short

  • Stateless: every request builds a fresh server; nothing is stored. Every tool takes lang, which sets market, currency, VAT and links.
  • lang picks only a public market. A contract market comes from the signed-in shopper’s session on the server, never from a tool argument: a market identifier works as a key to its price list, so an agent that can pass one can read the contract price ([[pricing]]).
  • Search parses the shopper’s words into typed-spec, platform, brand and type filters, generated from the content model, not from a word list; what is left goes to fuzzy text. When filters plus leftover words find nothing, rerun without the words.
  • “Did you mean”: up to four suggestions, each with the exact arguments to run it, when the words missed, matched far too much, or a spec was too strict.
  • Server instructions tell the model to show products only through tool calls, never as prose lists or hand-built links.
  • Annotations on every tool: reads are readOnlyHint: true; checkout is destructiveHint: true.

Tool list, the parser and the instructions: references/mcp-server.md.

Checkout rules

  • Prefer the hand-off. The basket tools return a checkoutUrl that opens the basket in the shopper’s browser, where they review and pay. checkout places the order directly, and is only called when the shopper explicitly asks.
  • checkout is destructive (destructiveHint: true), so hosts ask before running it.
  • Signed-in limits. Invoice and quote checkout only for a signed-in trade buyer, after the same credit check the storefront does. A guest card order needs the shopper’s email and name: the tool asks for them rather than inventing them.
  • The same Shop API flow as the storefront: setCustomer, setMeta, place, confirmCartBooking, createFromCart with pipelines and payments, confirmCartBooking again once cart.orderId is set. See [[storefront]] references/cart-checkout.md.
  • A real payment never happens inside the conversation in these builds: card orders in the demos are recorded as paid. A production store hands off to its payment page ([[payments]]).

Baskets without sessions

A conversation has no cookies. add_to_cart without a cartId creates a basket and returns its id; later basket calls pass it back. The hand-off route adopts it in the browser:

// app/mcp/cart/route.ts: `checkoutUrl` = /mcp/cart?id=…&lang=…&as=…
export async function GET(request: NextRequest) {
const q = request.nextUrl.searchParams;
const lang = isLang(q.get("lang") ?? "") ? (q.get("lang") as Lang) : "en";
const id = q.get("id");
const jar = await cookies();
const { cart } = id
? await shop<{ cart: { id: string; state: string } | null }>(
`query($id: UUID!) { cart(id: $id) { id state } }`,
{ id },
).catch(() => ({ cart: null }))
: { cart: null };
if (cart?.state === "cart") {
// A signed-in conversation's link carries a signed note (`as`) of the shopper, bound to this cart.
const claims = q.get("as") ? await readHandoff(q.get("as")!, siteUrl(request)) : null;
if (claims?.cart === cart.id) signInAs(jar, claims.sub); // keeps the company's prices and invoice checkout
jar.set("cart", cart.id, { httpOnly: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 30 });
}
return Response.redirect(new URL(`/${lang}/cart`, siteUrl(request)), 303);
}

Two more hand-off routes: /mcp/view?skus=… (the store’s own cards for a list of SKUs, for hosts without MCP Apps) and /mcp/buy?sku=… (add one variant to this browser’s basket). Keep /mcp/* hand-off routes out of the language proxy and disallowed in robots.txt.

Sign-in

Search, product detail and the basket work without an account. Tools that act for a shopper (whoami, my_orders, recommendations, bookings) need an OAuth access token: the route answers 401 with WWW-Authenticate: resource_metadata=… for those tools only, and the host starts sign-in. Once signed in, every ranking uses the shopper’s taste, prices follow their price lists and VAT display, and baskets belong to their customer.

The Crystallize MCP server’s own OAuth tokens work only on Core, so a shop still needs an identity provider for shoppers. The demos run a small stateless authorization server where “signing in” picks a demo customer: references/oauth.md.

Product cards (MCP Apps)

Tools that return products point at a UI resource (_meta.ui.resourceUri); hosts that support MCP Apps render it as cards under the tool call, with Add to basket buttons that call the same tools. The text result depends on the host: hosts that render cards get a short “N cards rendered, don’t repeat them” text, the others get Markdown with a link to /mcp/view and an Add-to-basket link per product. Claude’s hosted apps render cards but identify as Claude-User rather than declaring the capability. Details: references/mcp-apps.md.

WebMCP (early preview)

WebMCP lets a page declare its own tools to the browser’s agent. Early preview: Chromium 146+ behind chrome://flags/#enable-webmcp-testing, under a draft Community Group spec; no major browser supports it natively yet. The declarative form attributes are ignored elsewhere, so they are safe to ship now; imperative tools feature-detect first. Add toolname/tooldescription to the search and add-to-basket forms, never toolautosubmit on a financial form, and register imperative tools (filters, product, cart) with read-only and consequential hints. Prerequisites: labelled native controls, live-region errors and security headers. references/webmcp.md.

On-site assistant

A streaming model loop over the store’s own tools, answered as NDJSON to a drawer: text deltas, tool status, and product rails rendered as the store’s own cards. Small, fast model by default, low effort, prompt caching on the rules and taxonomy, the last round without tools so the reply always ends in words. references/on-site-assistant.md.

Pitfalls

Symptom Cause Fix
Agent recommends 12 V when asked for 18 V Specs searched as text Parse the words into typed-spec filters
“Without X” returns products that don’t mention X Unset booleans read false Treat false as not stated; filter on true or on the option field
Model lists products in prose under rendered cards Text result repeats the cards Detect UI hosts; thin text result; server instructions
Model builds its own /mcp/view links or tables Instructions don’t forbid it “The only way to show products is a tool call”
Hosts never prompt for sign-in Auth error returned from inside a tool handler 401 with WWW-Authenticate from the HTTP route, before the SDK
Basket lost between calls Cookie-based cart in a conversation cartId in every basket tool; hand-off link to adopt it
Signed-in basket re-priced as a guest in the browser Hand-off link without the shopper A signed, cart-bound as note on checkoutUrl
Order placed without the shopper asking checkout not marked destructive, or described as the default destructiveHint: true; describe the checkoutUrl as the default
Taste ranking ignores the query rankBy without relevance Add { signal: relevance } when there is a term
Cards show no images Media host missing from the resource CSP resourceDomains: [site, "https://media.crystallize.com"]
OAuth consent popup can’t report back Cross-Origin-Opener-Policy: same-origin on the OAuth pages Exclude the OAuth routes from COOP

Live examples

References

File Read it when
references/mcp-server.md Building the MCP endpoint, its tools, instructions, spec parser, “Did you mean”
references/oauth.md Shopper sign-in: lazy 401, RFC 9728/8414 metadata, DCR, CIMD, PKCE
references/mcp-apps.md Product cards, host detection, the resource CSP, updateModelContext
references/webmcp.md Browser-side tools and agentic forms (early preview)
references/on-site-assistant.md A chat assistant in the store on the same tools

[[storefront]] for the Discovery and Shop API code these tools call, and the checkout flow; [[seo-geo]] for the passive half; [[vector-ranking]] for taste and rankBy; [[content-model]] and [[taxonomy]] for typed specs and topics; [[payments]] for the payment page the hand-off leads to; [[bookable-resources]] for bookings.


Reference Details

Product cards with MCP Apps

MCP Apps let a tool point at an HTML resource that the host renders in a sandboxed iframe under the tool call. For a store, that means product cards with packshots, key specs, price with its VAT label, stock and Add to basket, instead of a Markdown list. Claude (web, desktop, mobile), ChatGPT, VS Code and Goose render them.

Crystallize’s own MCP server has a product-overview app (ui://crystallize/product-overview.html); it is a good starting point for the markup.

One resource, many views

One HTML document renders every result the server produces: product carousels, a product detail with its variants and spec sheet, the basket with quantity steppers, domain views (platforms, rentals, campaigns). The tool’s structuredContent says which (kind: "products", kind: "cart", …).

import { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
export const UI_RESOURCE_URI = "ui://my-store/cards.html";
registerAppResource(
server,
"My Store cards",
UI_RESOURCE_URI,
{ description: "Interactive product cards, product detail and basket views.", mimeType: RESOURCE_MIME_TYPE },
async () => ({
contents: [
{
uri: UI_RESOURCE_URI,
mimeType: RESOURCE_MIME_TYPE,
text: appHtml(site),
// The client script comes from the store, images from the Crystallize CDN.
_meta: {
ui: { csp: { resourceDomains: [site, "https://media.crystallize.com"] }, prefersBorder: false },
},
},
],
}),
);
// Every tool that returns products or the basket:
registerAppTool(server, "search_products", { /* … */ _meta: { ui: { resourceUri: UI_RESOURCE_URI } } }, handler);
  • The resource CSP lists the store’s origin and the media host, nothing else. With a custom media domain, list that instead. Missing it means cards without images.
  • Serve the ext-apps client bundle from the store’s origin (public/mcp-app.js), refreshed by a script when the package is upgraded, rather than from a third-party CDN.
  • Ask Discovery for chat-sized images: variants(types: "webp", maxWidth: 500).

The app

The app talks to the host through the ext-apps App client. Buttons call the same tools the model uses, links open through the host, and basket changes are reported back to the model:

const app = new App({ name: "My Store", version: "1.0.0" }, {}, { autoResize: true });
app.ontoolinput = ({ arguments: args }) => {
if (args?.cartId) state.cartId = args.cartId;
if (args?.lang) state.lang = args.lang;
};
app.ontoolresult = (result) => show(result?.structuredContent, result);
app.onhostcontextchanged = (ctx) => applyCtx(ctx); // theme and host style variables
const call = (name, args) => app.callServerTool({ name, arguments: args });
async function tellModel(c) {
await app.updateModelContext({
content: [
{
type: "text",
text: `Basket ${c.cartId}: ${c.count} items, ${c.total}. Pass cartId=${c.cartId} to basket tools. Checkout: ${c.checkoutUrl}`,
},
],
structuredContent: { cartId: c.cartId, count: c.count, total: c.total, checkoutUrl: c.checkoutUrl },
});
}
// Add to basket: the same tool the model calls, with the cartId the app has seen.
el.addEventListener("click", async () => {
const res = await call("add_to_cart", { sku, cartId: state.cartId ?? undefined, lang: state.lang });
state.cartId = res.structuredContent?.cartId ?? state.cartId;
await tellModel(res.structuredContent);
});
// Links open through the host; fall back to a new window.
app.openLink({ url }).catch(() => window.open(url, "_blank"));
await app.connect();
  • Use the host’s style variables (--color-text-primary, --font-*, --border-radius-*) for text outside the cards, with light-dark() fallbacks, so the app follows the host’s light or dark theme. Keep the store’s own look inside the cards.
  • Show “Did you mean” suggestions as chips that call search_products with their arguments.
  • A Checkout in store button opens the checkoutUrl hand-off (../SKILL.md).

Host detection: what the text result says

The text result of a product tool is what the model reads. If the host renders cards and the text also lists the products, the model repeats them in prose. If the host doesn’t render cards and the text is thin, the shopper sees nothing. So detect the host per call:

import { getUiCapability } from "@modelcontextprotocol/ext-apps/server";
const isUi = (tool?: ServerContext) => {
// 2026-07-28 clients send their capabilities on every request.
const declared = Boolean(getUiCapability(server.server.getClientCapabilities()));
// Claude's hosted apps (web, desktop, mobile, Cowork) render cards but identify as Claude-User.
const ua = tool?.http?.req?.headers.get("user-agent") ?? "";
const ui = declared || /^Claude-User\b/i.test(ua);
if (process.env.MCP_DEBUG) console.log(`[mcp] ui=${ui} declared=${declared} ua=${ua || "?"}`);
return ui;
};

Then, in the result:

  • Cards on screen: one paragraph that says so and gives the model just enough to reason and point: “Results for impact driver · 18 V: 6 product cards rendered for the user with pictures, key specs, prices, stock and Add-to-basket buttons. Do not repeat them — reply with one or two sentences (your pick and why). Shown: Name [variant] (SKU, 18 V · 226 Nm, €199, in stock); …”. Add the “Did you mean” labels and their arguments.
  • No cards: Markdown whose first line links to /mcp/view?skus=… (“See these with pictures →”), then each product as **[name](url)**, SKU, key specs, price, availability and [Add to basket](buyUrl). No Markdown images: most hosts don’t render them, or render them huge.
  • Both carry the same structuredContent, which the app renders.

2025-era clients in stateless mode don’t send capabilities, and get the Markdown. MCP_DEBUG=1 logs the detection per call; check it with each host you support.

Image blocks

get_product also returns the packshot as an image content block (WebP, about 500 px). Claude shows it inline even without MCP Apps. Fetch it with a short timeout and skip it above about 1.5 MB.

The view page for hosts without cards

/mcp/view?lang=…&skus=… renders the storefront’s own product cards in the tool’s order, with a title. It is the link the Markdown fallback starts with, so a shopper on any host is one click from pictures and prices. It is noindex and disallowed in robots.txt.

A shopper-facing MCP server on Discovery and the Shop API

A Model Context Protocol server inside the storefront, at /api/mcp. Claude (web, desktop, mobile, Claude Code), ChatGPT, VS Code and other MCP hosts connect to it as a custom connector. It reads only Discovery and the Shop API, keeps no state, and calls the same functions as the storefront’s server actions.

This is a shopper’s server, not the Crystallize MCP server (which is for developers working on a tenant).

Code is trimmed from two working stores on @modelcontextprotocol/server and @modelcontextprotocol/ext-apps, Next.js 16.

Layout

Piece Where
Endpoint (Streamable HTTP, stateless) app/api/mcp/route.ts
Tools, resources, prompt, server instructions lib/mcp/server.ts
Question → filters (typed specs, brands, types) lib/mcp/understand.ts, a pure module with unit tests
“Did you mean” suggestions lib/mcp/suggest.ts, pure, unit-tested
Search, cards, detail, basket views lib/mcp/catalogue.ts
Basket and order operations without cookies lib/mcp/shop.ts, the same Shop API calls as the server actions
MCP App (cards) lib/mcp/ui.ts, client bundle served from the store
OAuth lib/mcp/{auth,env,metadata}.ts, app/oauth/*, app/.well-known/*
Hand-off pages app/mcp/{view,buy,cart}
Spec model for the parser A JSON file generated from the content model

Keep /api/*, /oauth/*, /.well-known/* and /mcp/{view,buy,cart} out of the language proxy.

The endpoint

Stateless Streamable HTTP: every request builds a fresh server from a factory, so it runs on serverless functions. The route parses the body itself, so it can answer 401 for protected tools before the SDK sees the request (see oauth.md), and adds CORS, because hosts call from their own origins:

import { createMcpHandler, type AuthInfo } from "@modelcontextprotocol/server";
export const maxDuration = 60;
const handler = createMcpHandler((ctx) => buildServer({ authInfo: ctx.authInfo, site: siteUrl(ctx.requestInfo) }), {
onerror: (error) => console.error("[mcp]", error),
});
const CORS: Record<string, string> = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
"Access-Control-Allow-Headers":
"Content-Type, Authorization, Accept, Mcp-Session-Id, MCP-Protocol-Version, Last-Event-ID",
"Access-Control-Expose-Headers": "Mcp-Session-Id, WWW-Authenticate",
"Access-Control-Max-Age": "86400",
};
async function serve(req: Request): Promise<Response> {
let parsedBody: unknown;
if (req.method === "POST") {
const text = await req.text();
try {
parsedBody = text ? JSON.parse(text) : undefined;
} catch {
return withCors(
Response.json(
{ jsonrpc: "2.0", error: { code: -32700, message: "Parse error" }, id: null },
{ status: 400 },
),
);
}
req = new Request(req.url, { method: req.method, headers: req.headers, body: text }); // the body was consumed
}
const authInfo = await bearer(req); // verified access token, or undefined; an invalid one answers 401
if (!authInfo && callsProtectedTool(parsedBody)) return challenge(req, "Sign in to use this tool");
return withCors(await handler.fetch(req, { authInfo, parsedBody }));
}
export const POST = serve;
export const GET = serve;
export const DELETE = serve;
export const OPTIONS = () => new Response(null, { status: 204, headers: CORS });

Tools

Every tool takes lang, which sets market, currency, price variant, VAT, names and links. Without it, a signed-in shopper gets their own market and everyone else the default.

Tool Does Annotations
search_products Free text plus category, brand, topics, structured specs, stock and price bounds. Words become filters (below). Cards, facets, suggestions readOnlyHint
show_products Cards for an explicit list of SKUs, in order: the model’s own shortlist readOnlyHint
get_product One product by SKU or path (any language): every variant with SKU, price, volume price, stock; the typed spec sheet; the packshot as an image block readOnlyHint
similar_products nearestTo in a vector vocabulary readOnlyHint
list_categories, list_brands The taxonomy with counts, in the market’s language, with the ids the search accepts readOnlyHint
Domain tools Whatever the catalogue needs: battery platforms and what fits a tool, rentals and availability, campaigns readOnlyHint for reads
add_to_cart Adds a variant by SKU; creates a basket when there is no cartId; returns the basket with cartId and checkoutUrl not read-only, not destructive
update_cart_line Sets a quantity; 0 removes the line (and cancels a booking) idempotentHint
view_cart Lines, bookings, totals, checkoutUrl readOnlyHint
suggest_add_ons Accessories and consumables for what is in the basket readOnlyHint
checkout Places the order, with the storefront’s checkout flow destructiveHint
whoami, my_orders, recommendations Signed in only: the shopper, their orders, their personal ranking readOnlyHint

Register tools that return products as MCP App tools (mcp-apps.md):

const langArg = z
.enum(["en", "no", "sv", "nl"])
.optional()
.describe("Market and language: en (EUR), no (NOK), sv (SEK), nl (EUR). Prices, names and links follow it.");
const cartIdArg = z
.string()
.uuid()
.optional()
.describe("Basket id from an earlier add_to_cart call, so items land in the same basket.");
registerAppTool(
server,
"search_products",
{
title: "Search products",
description:
"Search the catalogue. Put the user's words in `query` as they are: numbers with units ('18V', 'over 60 Nm', 'under 2 kg'), option and yes/no names, brands and product types become hard filters on the typed specs and the taxonomy; the remaining words are a typo-tolerant text search. Returns product cards, facets and 'Did you mean' suggestions with ready-made arguments.",
inputSchema: z.object({
query: z.string().min(1).max(160).optional(),
category: z.string().optional(),
brand: z.string().optional(),
topics: z
.array(z.string())
.max(4)
.optional()
.describe(`Taxonomy filters. Valid ids — ${topicHint(vocab)}.`),
specs: z
.array(
z.object({
field: z.string().describe("'<group>.<field>', e.g. 'drilling.torqueHard', 'power.voltage'."),
gte: z.number().optional(),
lte: z.number().optional(),
equals: z.union([z.boolean(), z.number(), z.string(), z.array(z.string())]).optional(),
unit: z.string().optional(),
}),
)
.max(6)
.optional()
.describe(`Typed spec filters, all of which must hold. Groups and fields — ${SPEC_HINT}.`),
inStockOnly: z.boolean().optional(),
priceMin: z.number().optional(),
priceMax: z.number().optional(),
limit: z.number().int().min(1).max(24).optional(),
lang: langArg,
cartId: cartIdArg,
}),
annotations: { readOnlyHint: true, openWorldHint: false },
_meta: { ui: { resourceUri: UI_RESOURCE_URI } },
},
async (args, tool) => {
/* resolve arguments, understand the words, search, suggest — below */
},
);
server.registerTool(
"checkout",
{
title: "Place order",
description:
"Place the basket as an order. mode: card (anyone; a guest needs email and name), invoice or quote (signed-in trade buyers). Prefer giving the user the checkoutUrl unless they explicitly ask you to order now.",
inputSchema: z.object({
cartId: z.string().uuid(),
mode: z.enum(["card", "invoice", "quote"]).optional(),
email: z.string().email().optional().describe("Guest checkout only."),
name: z.string().max(80).optional().describe("Guest checkout only."),
reference: z.string().max(80).optional().describe("Order reference / PO number."),
lang: langArg,
}),
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
},
async ({ cartId, mode, email, name, reference, lang }) => {
const ctx = await ctxFor(lang);
const r = await placeOrder(ctx, cartId, mode ?? (ctx.session?.trade ? "invoice" : "card"), {
email,
name,
reference,
});
if (!r.ok) return textResult(r.error, undefined, true); // e.g. "A guest order needs the shopper's email and name. Ask the user."
return textResult(`Order **${r.orderId}** placed: ${money(r.gross, ctx.lang)}.`, {
kind: "order",
orderId: r.orderId,
});
},
);
  • Errors are answers the model can act on, with isError: true: “Unknown brand “milwauke”. Brands: …“, “Invalid specs filter: …, valid fields: …”. Validate arguments against the vocabulary and say what is valid.
  • The tool description lists the spec fields (generated, compact: drilling: torqueHard Nm, hammerMode y/n, toolHolder [sds-plus|sds-max]), and the topic ids. The model then knows what it can ask for.
  • The vocabulary read must not take the server down. Catch it and fall back to empty lists.

Server instructions

Instructions go to the model with the tool list. The ones that changed behaviour most (from both stores):

Language and market: every tool takes lang. Pick it from the user's language or country and keep it for the whole
conversation; prices, VAT rate, product names and links follow it.
Specifications are typed numbers, yes/no and options, and search_products filters on them: write the user's words
into query as they are. Never filter or compare specs from memory; the result titles name the filters that were
applied.
Imprecise questions: search results may carry "Did you mean" suggestions. When the question was vague, matched
nothing or matched far too much, offer two to four of them as a one-line question and run the one the user picks
(the arguments are given). When the result already answers the question, just answer.
Showing products: whenever you recommend, compare or shortlist products — even ones you already have from an
earlier call — call a tool so the interactive cards render: search_products for a new query, or show_products with
the SKUs for your own picks. Never answer a product question with a prose list alone.
Presenting results: the only way to show products is a tool call. Never build /mcp/view links or product tables
yourself. Hosts that support MCP Apps draw each result as cards; your reply then adds one or two sentences — the
pick and why — and must not repeat names, prices, SKUs or stock. If a result says "cards rendered", you are on such
a host. Otherwise start your reply with the result's "See ... with pictures →" link and present each product as
**[name](url)**, SKU, price, availability and [Add to basket](buyUrl); never use markdown images.
Basket: add_to_cart returns a cartId. Pass it to later basket calls so everything lands in one basket. Give the
user the checkoutUrl to finish in the store; only call checkout when they explicitly ask you to place the order.
Sign-in: search, details and the basket work without an account. whoami, my_orders and recommendations need the
shopper to sign in (the host will prompt).

Start with one paragraph on what the store sells and to whom, and add domain rules (versions, compatibility, rentals) as the catalogue needs.

Typed specs from the shopper’s words

A free-text search for “18V 5Ah” or “125 mm angle grinder” is a fuzzy token match where “12V”, “8.0 Ah” and a 125 mm cutting disc score almost as well. Turn the words into the filters the index has, generated from the content model, not from a word list:

  1. Generate a spec model at build time: every spec field’s type, units, decimals and options, and its labels in every content language. One store generates it from its seed model, another from shared spec definitions.
  2. Numbers with units (“18V”, “5,0 Ah”, “over 60 Nm”, “under 2 kg”, “100–200 mm”, “minst 8 Ah”) go to the fields that carry the unit. When several do (mm, kg, Nm), the field-label words in the question decide (“blade diameter 190 mm”), then the spec families of the product type it names, then the shared pieces; what is still open is an OR across the candidates.
  3. A bare value is a ±3 % band (18 V is not 20 V); comparators in every language (“over”, “minst”, “meer dan”, “under”, “høyst”) make it a bound.
  4. Options and yes/no match their labels in any language (“SDS-plus”, “M class”, “brushless”, “with hammer mode”); a negation (“uten Bluetooth”, “without”) flips them.
  5. Brands, product types, platforms match the catalogue’s own translated taxonomy (Discovery facets per language).
  6. What is left goes to Discovery’s fuzzy text search, ranked with relevance plus the house and taste terms. If the filters plus leftover words find nothing, rerun without the words: the filters alone are the better answer.
  7. Offer a structured specs argument too, for models that want to be explicit; explicit arguments win.

Discovery’s filter names for typed fields, and the filter for one parsed constraint:

export const optionId = (key: string) =>
key.replace(/-([a-z0-9])/g, (_, c: string) => (/\d/.test(c) ? `_${c}` : c.toUpperCase()));
const base = (key: string) => key.replace(/\./g, "_");
/** "specs.drilling.torqueHard" → specs_drilling_torqueHard_number; option "sds-plus" → specs_drilling_toolHolder_sdsPlus */
export function filterName(field: Field, option?: string) {
if (field.type === "number") return `${base(field.key)}_number`;
if (field.type === "option") return `${base(field.key)}_${optionId(option ?? "")}`;
return base(field.key);
}
function partFilter(p: Part): Record<string, unknown> {
const f = p.field;
if (f.type === "boolean") return { [filterName(f)]: { equals: p.bool !== false } };
if (f.type === "option") {
const opts = (p.options ?? []).map((o) => ({ [filterName(f, o)]: { exists: !p.negate } }));
return opts.length === 1 ? opts[0] : p.negate ? { AND: opts } : { OR: opts };
}
return {
[filterName(f)]: { range: { ...(p.gte != null && { gte: p.gte }), ...(p.lte != null && { lte: p.lte }) } },
};
}
/** A bare number: about this value, ±3 % (at least half a step of the field's precision). */
function about(v: number, field: Field) {
const step = 10 ** -(field.decimals ?? 0);
const tol = Math.max(v * 0.03, step / 2);
return { gte: v - tol, lte: v + tol };
}
/** AND across constraints, OR across the parts of one (the same words on several fields). */
export const constraintFilters = (constraints: Constraint[]) =>
constraints.map((c) => (c.parts.length === 1 ? partFilter(c.parts[0]) : { OR: c.parts.map(partFilter) }));

Check the generated names against your tenant’s Discovery schema (ToolFilter, ProductFilter, …): they follow the component, piece and field identifiers. A field measured in several units (airflow in m³/h or l/s) can’t be range-filtered in one unit, because range filters ignore the unit: match each convertible unit and check the hits.

The search query

const ranking = term ? { ...base, terms: [{ signal: "relevance", weight: 2 }, ...base.terms] } : base;
const data = await discovery(
`query McpTools($term: String!, $filters: ToolFilter, $facets: ToolFacet, $rankBy: RankByInput, $context: ContextInput, $limit: Int!, $skip: Int!) {
browse { tool(language: ${lang}, term: $term, options: { fuzzy: { fuzziness: SINGLE } }, filters: $filters, facets: $facets,
rankBy: $rankBy, context: $context, pagination: { limit: $limit, skip: $skip }) {
summary { totalHits facets } hits { score rankScore ${CARD} } } } }`,
{
term,
filters: { AND: [...constraintFilters(constraints), ...topicFilters] },
facets: { topics: { key: "topics", limit: 200 } },
rankBy: ranking,
...(taste?.length ? { context: { userTaste: taste } } : {}), // omit, never null
limit,
skip,
},
);
// With words, a hit scoring 0 only matched through a filter: noise.
const hits = term ? data.browse.tool.hits.filter((h) => (h.score ?? 0) > 0) : data.browse.tool.hits;

rankBy, context and the taste vector are covered in [[vector-ranking]]. When the shopper is signed in, rebuild the taste from their Shop API order history per call (cached per customer), never from a stored profile.

“Did you mean”

For imprecise questions, return up to four suggestions, each with the exact search_products arguments that run it:

  • Nothing matched: a word is probably misspelt (“vinkelslipr”, “milwauke”) → the closest product type, brand or platform (edit distance against the vocabulary); or a spec was too strict → the same search without it, or “at least” instead of “about”.
  • Far too much matched (“drill”) → the facets that split the result best: product types, brands, platforms, trades.
  • Nothing in the corner the filters picked → the words across the whole store.
export type Suggestion = {
label: string;
why: "spelling" | "relax" | "narrow" | "widen";
args: Record<string, unknown>;
};
export function suggestionsMarkdown(list: Suggestion[]): string {
if (!list.length) return "";
return (
"\n\nDid you mean? Offer these to the user as a short question (if the question was imprecise), then call search_products with the chosen arguments:\n" +
list.map((s) => `- ${s.label} → \`${JSON.stringify(s.args)}\``).join("\n")
);
}

Keep the base arguments (lang, limit) in each suggestion’s args, and drop cartId. The cards widget shows the suggestions as chips.

Results the model can’t misuse

  • Every product carries its url (the storefront page in the market’s language), buyUrl (/mcp/buy?sku=…&lang=…) and, for lists, a viewUrl (/mcp/view?skus=…).
  • get_product also returns the packshot as an image content block (WebP, about 500 px, under 1.5 MB). Hosts show it inline even without MCP Apps.
  • Prices say their currency and whether they are incl. or excl. VAT.
  • Titles name the filters that were applied (“Results for impact driver · 18 V · ≥ 200 Nm”), so the model can tell the user what it searched for.

Resources and prompts

  • store://spec-fields: every filterable spec field with type, units and options (the same text as the tool description hint).
  • store://how-it-works: Markdown on typed specs, ranking and prices.
  • A prompt that guides a job to a basket (kit-out with a job argument; shop-for with a need).
  • The MCP App resource (mcp-apps.md).

Testing

Terminal window
claude mcp add --transport http my-store http://localhost:3000/api/mcp
claude -p "Find an 18V impact driver over 200 Nm from the my-store server, priced for Norway"
npx @modelcontextprotocol/inspector # against the local endpoint
  • Unit tests (node:test) on the pure modules: question → filters in every language, structured spec arguments, multi-unit checks, “Did you mean”.
  • A smoke test against a running server: discovery documents, the 401 gate, searches in each language, details, basket and hand-off, the UI resource, DCR + PKCE + consent + token + signed-in calls. Don’t place real orders from it; check that checkout asks a guest for their details.
  • Claude.ai and other hosted apps need a public URL (a deployment, or a tunnel such as cloudflared tunnel --url http://localhost:3000): add https://<host>/api/mcp as a custom connector, with “Sign in when needed”.

Shopper sign-in for an MCP server

The MCP specification makes the server an OAuth 2.1 resource server; something has to be the authorization server. For a production store that is the shop’s identity provider. The two demo stores run their own small, stateless authorization server, where “signing in” means choosing which demo customer the assistant shops as.

The Crystallize MCP server’s own OAuth tokens work only on the Core API, so they can’t identify a shopper to a store. A shop still needs its own identity provider.

The flow

Host ── tools/call whoami (no token) ──▶ /api/mcp ── 401 + WWW-Authenticate: resource_metadata=…
Host ── GET /.well-known/oauth-protected-resource/api/mcp ──▶ authorization_servers: [site]
Host ── GET /.well-known/oauth-authorization-server ──▶ authorize / token / register, PKCE S256, CIMD
Host ── POST /oauth/register (DCR) or client_id = its metadata document URL (CIMD)
Browser ─ GET /oauth/authorize?… ──▶ consent page: pick a customer ──▶ POST /oauth/approve
Browser ─ 303 → redirect_uri?code=…&state=…&iss=…
Host ── POST /oauth/token (code + code_verifier) ──▶ access_token (1 h) + refresh_token (30 d, rotating)
Host ── retries with Bearer token ──▶ personalised answer

Lazy authentication

initialize, tools/list and the public tools never need a token, so the connector works at once. Only tools that act for the shopper answer 401, and only a transport-level 401 makes a host start sign-in; a tool handler can’t produce one. So the gate runs in the route, on the parsed JSON-RPC body, before the SDK:

export const PROTECTED_TOOLS = new Set(["whoami", "my_orders", "recommendations"]);
function callsProtectedTool(body: unknown): boolean {
const messages = Array.isArray(body) ? body : [body];
return messages.some(
(m) =>
m &&
typeof m === "object" &&
(m as { method?: unknown }).method === "tools/call" &&
PROTECTED_TOOLS.has(String((m as { params?: { name?: unknown } }).params?.name)),
);
}
function challenge(req: Request, description: string, error = "invalid_token", status = 401): Response {
const metadata = `${siteUrl(req)}/.well-known/oauth-protected-resource/api/mcp`;
return withCors(
Response.json(
{ error, error_description: description },
{
status,
headers: {
"WWW-Authenticate": `Bearer error="${error}", error_description="${description}", resource_metadata="${metadata}", scope="${SCOPE}"`,
},
},
),
);
}

An invalid or expired token is refused outright with the same challenge, so the client refreshes or re-authorises. Public tools still personalise when a valid token comes along.

Discovery documents

RFC 9728 protected-resource metadata at /.well-known/oauth-protected-resource/api/mcp (and at the bare /.well-known/oauth-protected-resource), and RFC 8414 authorization-server metadata at /.well-known/oauth-authorization-server:

export function protectedResourceMetadata(req: Request) {
return {
resource: mcpUrl(req),
authorization_servers: [siteUrl(req)],
scopes_supported: [SCOPE],
bearer_methods_supported: ["header"],
resource_name: "My Store MCP",
resource_documentation: `${siteUrl(req)}/en/mcp`,
};
}
export function authorizationServerMetadata(req: Request) {
const issuer = siteUrl(req);
return {
issuer,
authorization_endpoint: `${issuer}/oauth/authorize`,
token_endpoint: `${issuer}/oauth/token`,
registration_endpoint: `${issuer}/oauth/register`,
scopes_supported: [SCOPE],
response_types_supported: ["code"],
response_modes_supported: ["query"],
grant_types_supported: ["authorization_code", "refresh_token"],
token_endpoint_auth_methods_supported: ["none"],
code_challenge_methods_supported: ["S256"],
client_id_metadata_document_supported: true,
authorization_response_iss_parameter_supported: true,
};
}

Serve both with CORS and Cache-Control: public, max-age=300. For a production store, point authorization_servers at the identity provider and drop the rest of this file.

A stateless authorization server (demo)

Every artefact (the client registration, the code, the access and refresh tokens, the basket hand-off) is a signed JWT (HS256, jose), each with its own typ, so nothing needs a database:

  • Clients. Dynamic Client Registration (RFC 7591) for public clients: the registration is the client_id. Client ID Metadata Documents: the client_id is an https URL; fetch it, check its client_id matches and the redirect URI is listed, and show the host’s name on the consent page. Claude supports both (“Register automatically” and “Use Claude’s published identity”).
  • Redirect URIs are https, or http on loopback. Loopback redirects match with the port ignored (RFC 8252 §7.3), which Claude Code needs.
  • Codes live 5 minutes, bound to client, redirect URI, PKCE challenge (S256 only) and resource.
  • Access tokens live 1 hour, with aud = the MCP URL; they are rejected anywhere else.
  • Refresh tokens live 30 days and rotate on every use (a fresh jti). They can’t be revoked individually: fine for a demo, not for production.
  • The token endpoint accepts form-encoded bodies (and JSON), verifies PKCE, checks resource matches, and for CIMD clients checks the document still exists on refresh.
export async function verifyAccessToken(token: string, issuer: string, resource: string): Promise<AuthInfo> {
try {
const { payload } = await jwtVerify(token, authSecret(), { issuer, audience: resource, typ: "at+jwt" });
return {
token,
clientId: payload.cid as string,
scopes: String(payload.scope ?? SCOPE)
.split(" ")
.filter(Boolean),
expiresAt: payload.exp,
resource: new URL(resource),
extra: { shopper: payload.sub },
};
} catch (error) {
const expired = error instanceof joseErrors.JWTExpired;
throw new OAuthError(OAuthErrorCode.InvalidToken, expired ? "Token expired" : "Invalid token");
}
}

The sub is the shopper; the tools turn it into the Shop API customer (for a trade buyer, the company), their price-list markets and their taste.

The issuer URL

The issuer, the resource identifier and every link handed to the model are built from one function, and must be stable per deployment:

export function siteUrl(req?: Request | null): string {
const explicit = process.env.MCP_SITE_URL?.replace(/\/$/, "");
if (explicit) return explicit;
if (req) {
const host = req.headers.get("x-forwarded-host") ?? req.headers.get("host");
const proto =
req.headers.get("x-forwarded-proto")?.split(",")[0] ??
(host && /^(localhost|127\.0\.0\.1|\[::1\])(:|$)/.test(host) ? "http" : "https");
if (host) return `${proto}://${host}`;
}
if (process.env.VERCEL_PROJECT_PRODUCTION_URL) return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
return SITE_URL;
}
export const mcpUrl = (req?: Request | null) => `${siteUrl(req)}/api/mcp`;

The canonical production URL (for SEO) is deliberately not first: a local or preview server would then issue tokens for production. Set MCP_SITE_URL to the tunnel’s origin when testing through a tunnel.

Environment

Variable Purpose
CRYSTALLIZE_ACCESS_TOKEN_ID / _SECRET The Shop API (baskets, orders, bookings). Discovery needs nothing when open
MCP_AUTH_SECRET Signs the OAuth artefacts and basket hand-offs. A long random string
MCP_SITE_URL The public origin for the issuer and links, when the request host isn’t it

Browser headers on the OAuth pages

An MCP client may open the consent page in a popup and read the result through window.opener after the redirect back. Cross-Origin-Opener-Policy: same-origin cuts that: exclude the OAuth routes from COOP ([[storefront]] security headers).

An on-site shopping assistant

A chat drawer in the store, answered by a streaming model loop over the store’s own tools: Discovery for the catalogue and ranking, the Shop API for the basket and order history. Results render as the store’s own product cards, ranked by the shopper’s taste. Code is trimmed from a working store (app/api/assistant/route.ts, lib/assistant/*), on the Anthropic TypeScript SDK.

The route

POST /api/assistant takes the page’s language and the conversation as plain text, and answers NDJSON: text deltas, tool status, product rails and basket updates, then done.

export const maxDuration = 60;
// A small, fast model by default; override with an environment variable to trade speed for depth.
const MODEL = process.env.ASSISTANT_MODEL || "claude-haiku-5-5";
/** Tool rounds per reply; the last one runs without tools so the model always closes with words. */
const MAX_ITERATIONS = 5;
const Body = z.object({
lang: z.enum(LANGS),
messages: z
.array(
z.object({
role: z.enum(["user", "assistant"]),
content: z.string().max(4000),
shown: z
.array(z.object({ sku: z.string(), name: z.string() }))
.max(60)
.optional(),
}),
)
.min(1)
.max(60),
});
export type AssistantEvent =
| { type: "text"; delta: string }
| { type: "tool"; name: string; status: "start" | "done" | "error" }
| ProductsEvent // a rail of cards
| CartEvent // the basket changed
| { type: "error"; code: "config" | "busy" | "network" | "api" | "internal" | "long" }
| { type: "done" };
export async function POST(req: Request) {
const body = Body.parse(await req.json());
const ctx = await assistantContext(body.lang); // session, taste, VAT mode, basket, orders, from cookies
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
const emit = (e: AssistantEvent) => controller.enqueue(encoder.encode(JSON.stringify(e) + "\n"));
try {
await converse(ctx, toMessageParams(body.messages), emit, req.signal);
} catch (error) {
emit({ type: "error", code: errorCode(error) });
} finally {
emit({ type: "done" });
controller.close();
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "application/x-ndjson; charset=utf-8",
"Cache-Control": "no-store",
"X-Accel-Buffering": "no",
},
});
}

The drawer keeps text only. Products it showed ride along with each assistant turn as a note (“Shown to the shopper as cards: Name [SKU]; …”), so “add the second one” still resolves without sending tool results back. Merge two turns of the same role in a row (an answer that failed half-way), and drop leading assistant turns.

The loop

async function converse(
ctx: AssistantContext,
messages: Anthropic.MessageParam[],
emit: (e: AssistantEvent) => void,
signal: AbortSignal,
) {
const client = new Anthropic();
const system = await systemPrompt(ctx);
let retries = 0;
for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
const finalRound = iteration === MAX_ITERATIONS - 1;
const stream = client.messages.stream(
{
model: MODEL,
max_tokens: 4000,
system,
tools: TOOLS,
...(finalRound ? { tool_choice: { type: "none" as const } } : {}), // end in words, not a rail
messages,
output_config: { effort: "low" }, // the tools do the thinking; keep the chat snappy
},
{ signal },
);
stream.on("text", (delta) => emit({ type: "text", delta }));
let message: Anthropic.Message;
try {
message = await stream.finalMessage();
retries = 0;
} catch (error) {
// With eager input streaming, a tool input that can't be parsed rejects here: re-issue the turn.
const unparseable = error instanceof SyntaxError || (error instanceof Error && /JSON/i.test(error.message));
if (!unparseable || error instanceof Anthropic.APIError || signal.aborted || retries++ >= 2) throw error;
continue;
}
if (message.stop_reason === "refusal") return;
const uses = message.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use");
if (!uses.length) return;
messages.push({ role: "assistant", content: message.content });
// Tools in one turn run together; writes (add to basket) run after the reads.
const reads = uses.filter((u) => u.name !== "add_to_basket");
const writes = uses.filter((u) => u.name === "add_to_basket");
const outcomes = new Map(
await Promise.all(reads.map(async (u) => [u.id, await runTool(ctx, u.name, u.input)] as const)),
);
for (const u of writes) outcomes.set(u.id, await runTool(ctx, u.name, u.input));
const results: Anthropic.ToolResultBlockParam[] = [];
for (const use of uses) {
const outcome = outcomes.get(use.id)!;
for (const r of outcome.rails ?? []) if (r.items.length) emit(r); // cards go to the UI, not the model
if (outcome.cart) emit(outcome.cart);
results.push({
type: "tool_result",
tool_use_id: use.id,
content: outcome.text,
...(outcome.isError ? { is_error: true } : {}),
});
}
messages.push({ role: "user", content: results });
}
}

Map SDK errors to codes the drawer can explain: authentication → config, rate limit → busy, connection → network, other API errors → api.

The system prompt: three blocks

export async function systemPrompt(ctx: AssistantContext): Promise<Anthropic.TextBlockParam[]> {
const tax = await taxonomy("en"); // keys are the same in every language: one cache entry
return [
{ type: "text", text: RULES }, // never changes
{
type: "text",
text: `Taxonomy (dimension: id (English label)).\n${taxonomyForPrompt(tax)}`,
cache_control: { type: "ephemeral" },
},
{ type: "text", text: shopperBlock(ctx) }, // who is asking, in which language, basket, taste: last
];
}

The rules and the taxonomy are cached (the breakpoint after the taxonomy); the shopper block changes per request and goes last. Rules that worked:

  • Be terse. At most one short sentence before a tool. After the cards, at most about 40 words: the pick and why, naming at most one product. The cards show name, price, specs and stock; never repeat them.
  • Show products with tools, never in prose. One tool call usually answers; two or three rails at most. Run related searches in parallel.
  • Ask at most one clarifying question, only when you can’t sensibly search without it. Otherwise assume, say so in a clause, and search.
  • Prices, specs and SKUs only from tool results. Never invent products or compatibility.
  • Add to the basket only when the shopper clearly asks, in the variant they asked for.
  • On a tool error, don’t retry in the same reply; say so in one sentence.
  • Answer in the shopper’s language, with the trade’s own terms.
  • Plain sentences; no lists, headings, tables or links.

The shopper block: language, market, currency and VAT mode; the signed-in shopper, company and price lists; their taste in words; recent orders; the basket. When the customer layer can’t be read, say so and answer as for a guest rather than failing the chat.

The tools

The assistant’s tools wrap the same functions as the MCP server and the server actions: search_products, similar_products, product_details, add_to_basket (the cookie basket), plus taste tools a store can only offer on-site: search with a composed taste vector (“shop as another trade”), “complete my kit” from what the shopper owns, explain my profile. Results come back as text for the model and as rails of cards for the UI.

Lessons from other builds

  • Small models show text written before a tool call (a larger one hid it), and sometimes write the answer both before and after the tools: dedupe in the UI. Ordering “answer text, then a closing visual tool” saves a step.
  • Cache the whole conversation, not only the system prompt, on every step, and use low effort. One build went from 13.6 s to about 9 s per answer, and first text from about 11 s to 4–6 s.
  • Grounding that is too strict makes the model refuse. Forbid unsourced numbers and claims; allow it to explain documented principles.
  • SDK history traps. With the AI SDK (v7), agent.generate().response.messages holds only the last step: use result.responseMessages, or earlier tool calls silently drop out of multi-turn history. With extended thinking, thinking blocks are bound to the conversation: don’t trim history, keep it append-only.
  • Live regions: the conversation is role="log", but don’t announce it token by token; debounce, and show “thinking” as role="status" text ([[storefront]] accessibility).
  • Render model output as elements, never innerHTML. Keep conversations in sessionStorage.

WebMCP: tools in the store’s own pages

Status: early preview. WebMCP runs in Chromium 146.0.7672+ with chrome://flags/#enable-webmcp-testing, under a draft W3C Community Group spec, and no major browser supports it natively yet. Chrome-specific parts: consequentialHint from Chrome 154; toolactivated/toolcancel dispatched on document.modelContext from Chrome 156 (on window before that). Neither Crystallize store behind this skill ships WebMCP yet: what follows is the design from a Modern Web Guidance v1.0 audit of one of them, not tested code. Follow Chrome’s MWG guides (guides/webmcp/webmcp.md, agentic-forms.md, agentic-javascript-tools.md) for the API itself.

How it relates to the MCP server

Remote MCP server (mcp-server.md) WebMCP
Agent Claude, ChatGPT and other hosts, with no browser session The agent inside the shopper’s own tab (Gemini in Chrome, extensions, DevTools)
Shopper OAuth token The page’s session: cookies, market, VAT mode, taste
Basket cartId and a hand-off link The page’s cart cookie; no cartId, no OAuth
What the shopper sees Cards in the chat The page itself updating as the agent works

Both call the same code: the storefront’s server actions (addToCart, setQuantity, the cart view, checkout, booking availability) and the same search and ranking as the MCP tools. Use the MCP server’s tool names (snake_case, the same nouns), so an agent that knows one surface knows the other.

Prerequisites

Fix these first; they are also what the tools’ schemas are built from:

  • Labelled native controls. Quantity is <input type="number" name="quantity" min="1">, not a <span> between buttons. Variant options are radio inputs in a fieldset/legend.
  • Errors in live regions, and returned to the agent as strings.
  • Security headers, at least the companion headers and a Report-Only CSP: tools act with the shopper’s session, so an XSS becomes an agent acting as the shopper ([[storefront]] security headers).

Declarative: agentic forms

Self-contained forms get toolname and tooldescription, and toolparamdescription on their fields. Browsers without WebMCP ignore the attributes, so they are safe to ship now.

Form Attributes Notes
Header search toolname="search_products", a tooldescription naming what can be searched, toolautosubmit (read-only) toolparamdescription on q with examples. Wrap the form in <search>. On agentInvoked, respondWith the results JSON instead of navigating
Add to basket toolname="add_to_cart", toolautosubmit (low-risk and reversible) Wrap the variant fieldset and the quantity input in the form. respondWith the updated basket summary
Card checkout toolname="place_order", no toolautosubmit (financial) The browser stops for the shopper to review. Style form:tool-form-active and button:tool-submit-active
Invoice, quote toolname="order_on_invoice", toolname="request_quote", no autosubmit toolparamdescription on the PO reference and project fields
<!-- Design, not tested code: attribute names from the MWG agentic-forms guide. -->
<search>
<form
action="/en/search"
method="get"
toolname="search_products"
toolautosubmit
tooldescription="Search the catalogue by words, brand or spec, and list matching products."
>
<input
name="q"
type="search"
aria-label="Search"
toolparamdescription="e.g. '18V impact driver over 200 Nm', 'Makita 40V angle grinder'"
/>
</form>
</search>

Never toolautosubmit on a form that spends money. Not declarative: facet sidebars made of links, and forms with highly dependent fields (a rental booking where depot, period and start day depend on each other and on fetched availability).

Imperative: tools registered in JavaScript

For what isn’t a form: filters, the current product, the cart. In React, register them with useWebMCP from use-webmcp-tool (the package MWG mandates for React), in one client component mounted in the layout, using enabled per route rather than conditional hooks.

Tool Route Does Hint
list_filters Category, brand pages The facet groups and values with counts on this page readOnlyHint: true
filter_products Same Navigates to the filtered URL, waits for the render, returns the active filters and the count readOnlyHint: true
get_product Product page The current product: variants (SKU, price in the active VAT mode, stock) and typed specs, in the MCP tool’s shape readOnlyHint: true
view_cart All Basket lines and totals; opens the drawer readOnlyHint: true
update_cart_line All Sets a quantity; 0 removes the line none (reversible)
Booking availability, book_… Bookable products Wrap the availability and booking actions read-only, then consequentialHint: true
checkout Cart Only if you want one tool rather than the checkout forms consequentialHint: true
  • Feature-detect ('modelContext' in document) before registering anything.
  • Validate input inside execute, pass the AbortSignal on to fetch, and return errors as values ({ error }) rather than throwing.
  • Register per page with an AbortSignal, so tools disappear when the shopper navigates away.
  • consequentialHint is not an enforcement mechanism: keep the in-page confirmation for orders.
  • Add webmcp-types to tsconfig types.

Testing

Test with the Chrome flag on, and in a Node test through getTools() / executeTool(). Your own on-site assistant can later discover the page’s tools the same way, for example to open the cart drawer.


Crystallize AI