@snowcone-app/mcp 0.9.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/index.js +913 -402
  3. package/package.json +4 -1
package/dist/index.js CHANGED
@@ -24,7 +24,9 @@ var SNOWCONE_HOSTS = {
24
24
  /** Content-addressed artwork store (ingest handles). */
25
25
  raws: "https://raws.snowcone.app",
26
26
  /** Developer docs. */
27
- docs: "https://developers.snowcone.app"
27
+ docs: "https://developers.snowcone.app",
28
+ /** The storefront site; `/api/launch` says whether orders are open yet. */
29
+ site: "https://snowcone.app"
28
30
  };
29
31
  var SNOWCONE_REALTIME_WS_URL = `${SNOWCONE_HOSTS.cdn.replace(/^http/, "ws")}/realtime`;
30
32
  var PARAMS = {
@@ -232,6 +234,7 @@ async function signDevSig(canonical, secret) {
232
234
  var API_BASE = stripSlash(process.env.SNOWCONE_API_BASE ?? SNOWCONE_HOSTS.api);
233
235
  var IMG_BASE = stripSlash(process.env.SNOWCONE_IMG_BASE ?? SNOWCONE_HOSTS.img);
234
236
  var BUY_BASE = stripSlash(process.env.SNOWCONE_BUY_BASE ?? SNOWCONE_HOSTS.buy);
237
+ var LAUNCH_URL = process.env.SNOWCONE_LAUNCH_URL ?? `${stripSlash(SNOWCONE_HOSTS.site)}/api/launch`;
235
238
  var MEILI_HOST = stripSlash(process.env.SNOWCONE_MEILI_HOST ?? SNOWCONE_HOSTS.search);
236
239
  var MEILI_KEY = process.env.SNOWCONE_MEILI_KEY ?? "73f573ead9be75531c56ee89d104caa49d79154db387f119a013d33eccfe654b";
237
240
  var MEILI_INDEX = process.env.SNOWCONE_MEILI_INDEX ?? "snowcone";
@@ -243,6 +246,368 @@ function stripSlash(s) {
243
246
  return s.replace(/\/+$/, "");
244
247
  }
245
248
 
249
+ // package.json
250
+ var package_default = {
251
+ name: "@snowcone-app/mcp",
252
+ version: "0.11.0",
253
+ mcpName: "io.github.snowcone-app/snowcone",
254
+ description: "Snowcone MCP server \u2014 the agent-native quickstart. Mint a sandbox shop, browse the catalog, and turn any image into a buyable printed-merch mockup URL, all as callable tools.",
255
+ keywords: [
256
+ "mcp",
257
+ "model-context-protocol",
258
+ "snowcone",
259
+ "print-on-demand",
260
+ "mockup",
261
+ "merch",
262
+ "agent"
263
+ ],
264
+ author: "Snowcone <dev@snowcone.app>",
265
+ license: "MIT",
266
+ repository: {
267
+ type: "git",
268
+ url: "https://github.com/snowcone-app/snowcone-monorepo.git",
269
+ directory: "packages/mcp"
270
+ },
271
+ bugs: {
272
+ url: "https://github.com/snowcone-app/snowcone-monorepo/issues"
273
+ },
274
+ homepage: "https://developers.snowcone.app",
275
+ private: false,
276
+ type: "module",
277
+ bin: {
278
+ "snowcone-mcp": "./dist/index.js"
279
+ },
280
+ main: "dist/index.js",
281
+ files: [
282
+ "dist",
283
+ "README.md",
284
+ "CHANGELOG.md"
285
+ ],
286
+ scripts: {
287
+ build: "tsup",
288
+ dev: "tsup --watch",
289
+ start: "node dist/index.js",
290
+ "worker:dev": "wrangler dev",
291
+ deploy: "wrangler deploy --env production",
292
+ clean: "rm -rf dist",
293
+ typecheck: "tsc --noEmit",
294
+ test: "vitest run",
295
+ prepack: "pnpm run build"
296
+ },
297
+ dependencies: {
298
+ "@modelcontextprotocol/sdk": "^1.32.2",
299
+ zod: "^3.23.8"
300
+ },
301
+ devDependencies: {
302
+ "@snowcone-app/mockup-url": "workspace:*",
303
+ "@types/node": "^20.11.0",
304
+ tsup: "^8.1.0",
305
+ typescript: "^5.5.4",
306
+ vitest: "^2.1.9",
307
+ wrangler: "^3.91.0"
308
+ },
309
+ publishConfig: {
310
+ access: "public"
311
+ },
312
+ engines: {
313
+ node: ">=18"
314
+ }
315
+ };
316
+
317
+ // src/version.ts
318
+ var VERSION = package_default.version ?? "0.0.0";
319
+
320
+ // src/card.ts
321
+ var CARD_URI = "ui://snowcone/mockup-card.html";
322
+ var CARD_MIME = "text/html;profile=mcp-app";
323
+ var CARD_TOOL_META = {
324
+ ui: { resourceUri: CARD_URI },
325
+ "ui/resourceUri": CARD_URI,
326
+ "openai/outputTemplate": CARD_URI,
327
+ "openai/widgetAccessible": true,
328
+ "openai/toolInvocation/invoking": "Rendering the mockup\u2026",
329
+ "openai/toolInvocation/invoked": "Mockup ready"
330
+ };
331
+ function cardResourceMeta(opts = {}) {
332
+ const domains = [new URL(IMG_BASE).origin];
333
+ if (opts.beaconUrl) domains.push(new URL(opts.beaconUrl).origin);
334
+ return {
335
+ ui: { csp: { resourceDomains: domains, connectDomains: [] }, prefersBorder: true },
336
+ "openai/widgetCSP": { resource_domains: domains, connect_domains: [] },
337
+ "openai/widgetPrefersBorder": true,
338
+ "openai/widgetDescription": "A preview of the person's design printed on the product, with its price, option choices, and a Buy button (or 'Orders open soon' before launch)."
339
+ };
340
+ }
341
+ function cardHtml(opts = {}) {
342
+ return CARD_HTML.replace("__VERSION__", VERSION).replace("__BEACON__", opts.beaconUrl ? JSON.stringify(opts.beaconUrl).slice(1, -1) : "");
343
+ }
344
+ var CARD_HTML = `<!doctype html>
345
+ <html lang="en">
346
+ <head>
347
+ <meta charset="utf-8" />
348
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
349
+ <title>Snowcone mockup</title>
350
+ <style>
351
+ :root { color-scheme: light dark; --bg:#fff; --fg:#14161a; --muted:#5d636e; --line:#e4e6ea; --well:#f4f5f7; --accent:#14161a; --accent-fg:#fff; }
352
+ :root[data-theme="dark"] { --bg:#16181c; --fg:#f2f3f5; --muted:#a2a8b3; --line:#2c3038; --well:#1f2228; --accent:#f2f3f5; --accent-fg:#14161a; }
353
+ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --bg:#16181c; --fg:#f2f3f5; --muted:#a2a8b3; --line:#2c3038; --well:#1f2228; --accent:#f2f3f5; --accent-fg:#14161a; } }
354
+ * { box-sizing: border-box; }
355
+ html, body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.4 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
356
+ .card { max-width: 560px; margin: 0 auto; padding: 12px; }
357
+ .well { position: relative; background: var(--well); border-radius: 12px; overflow: hidden; aspect-ratio: 16 / 9; display: grid; place-items: center; }
358
+ .well img { width: 100%; height: 100%; object-fit: contain; display: block; transition: opacity .2s; }
359
+ .card[data-state="loading"] .well img, .card[data-busy="true"] .well img { opacity: .45; }
360
+ .placeholder { color: var(--muted); font-size: 13px; padding: 16px; text-align: center; }
361
+ .head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin: 12px 2px 0; }
362
+ .name { font-weight: 600; font-size: 15px; }
363
+ .price { font-variant-numeric: tabular-nums; color: var(--muted); white-space: nowrap; }
364
+ .opts { margin: 10px 2px 0; display: grid; gap: 8px; }
365
+ .opt-label { font-size: 12px; color: var(--muted); margin-bottom: 4px; text-transform: capitalize; }
366
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; }
367
+ .chip { border: 1px solid var(--line); background: transparent; color: var(--fg); border-radius: 999px; padding: 4px 10px; font: inherit; font-size: 13px; cursor: pointer; }
368
+ .chip[aria-pressed="true"] { border-color: var(--fg); font-weight: 600; }
369
+ .chip:disabled { cursor: default; opacity: .6; }
370
+ .buy { margin: 12px 2px 0; }
371
+ .btn { width: 100%; border: 0; border-radius: 10px; padding: 11px 14px; font: inherit; font-weight: 600; background: var(--accent); color: var(--accent-fg); cursor: pointer; }
372
+ .btn:disabled { background: var(--well); color: var(--muted); cursor: default; }
373
+ .note { margin: 6px 2px 0; font-size: 12px; color: var(--muted); }
374
+ .error { margin: 12px 2px 0; font-size: 13px; color: #c0392b; white-space: pre-wrap; }
375
+ .foot { margin: 10px 2px 0; font-size: 11px; color: var(--muted); }
376
+ </style>
377
+ </head>
378
+ <body>
379
+ <div class="card" id="card" data-state="loading" data-orders="" data-busy="false" data-missing-option="">
380
+ <div class="well"><div class="placeholder" id="placeholder">Rendering your mockup\u2026</div><img id="img" alt="" hidden /></div>
381
+ <div class="head" id="head" hidden><div class="name" id="name"></div><div class="price" id="price"></div></div>
382
+ <div class="opts" id="opts"></div>
383
+ <div class="buy" id="buy" hidden><button class="btn" id="buyBtn" type="button"></button><div class="note" id="note"></div></div>
384
+ <div class="error" id="error" hidden></div>
385
+ <div class="foot">Printed and shipped by Snowcone</div>
386
+ </div>
387
+ <script>
388
+ (() => {
389
+ "use strict";
390
+ const $ = (id) => document.getElementById(id);
391
+ const cardEl = $("card");
392
+ let card = null;
393
+ const BEACON = "__BEACON__"; // hosted endpoint only: one 1\xD71 load per card, so we can tell where cards are viewed from
394
+ let beaconSent = false;
395
+ let bridge = false; // MCP Apps bridge is up
396
+ let nextId = 1;
397
+ const pending = new Map();
398
+
399
+ function post(msg) { window.parent.postMessage(msg, "*"); }
400
+ function request(method, params) {
401
+ return new Promise((resolve, reject) => {
402
+ const id = nextId++;
403
+ pending.set(id, { resolve, reject });
404
+ post({ jsonrpc: "2.0", id, method, params });
405
+ setTimeout(() => { if (pending.has(id)) { pending.delete(id); reject(new Error(method + " timed out")); } }, 30000);
406
+ });
407
+ }
408
+ function notify(method, params) { post({ jsonrpc: "2.0", method, params: params || {} }); }
409
+
410
+ function applyTheme(ctx) {
411
+ const theme = ctx && ctx.theme;
412
+ if (theme === "dark" || theme === "light") document.documentElement.setAttribute("data-theme", theme);
413
+ }
414
+
415
+ function money(cents) {
416
+ if (typeof cents !== "number") return "";
417
+ return "$" + (cents / 100).toFixed(2);
418
+ }
419
+
420
+ function showError(text) {
421
+ cardEl.dataset.state = "error";
422
+ $("placeholder").textContent = "This mockup didn't render.";
423
+ $("img").hidden = true;
424
+ $("placeholder").hidden = false;
425
+ const e = $("error");
426
+ e.textContent = text || "";
427
+ e.hidden = !text;
428
+ }
429
+
430
+ function render(next) {
431
+ if (!next || typeof next !== "object") return;
432
+ card = next;
433
+ cardEl.dataset.state = "ready";
434
+ cardEl.dataset.orders = card.orders && card.orders.orders === "open" ? "open" : "not-open";
435
+ $("error").hidden = true;
436
+
437
+ const img = $("img");
438
+ if (typeof card.image_url === "string" && /^https:\\/\\//.test(card.image_url)) {
439
+ img.onload = () => {
440
+ $("placeholder").hidden = true; img.hidden = false; cardEl.dataset.busy = "false"; resize();
441
+ if (BEACON && !beaconSent) { beaconSent = true; new Image().src = BEACON; }
442
+ };
443
+ img.onerror = () => { cardEl.dataset.busy = "false"; showError("The image host refused the picture."); };
444
+ img.alt = card.product ? "Mockup of " + card.product.name : "Product mockup";
445
+ if (img.src === card.image_url && img.complete) cardEl.dataset.busy = "false"; // same picture: no load event comes
446
+ else img.src = card.image_url;
447
+ } else {
448
+ cardEl.dataset.busy = "false";
449
+ }
450
+
451
+ if (card.product) {
452
+ $("name").textContent = card.product.name;
453
+ $("price").textContent = money(card.product.price_cents);
454
+ $("head").hidden = false;
455
+ } else {
456
+ $("head").hidden = true;
457
+ }
458
+
459
+ const opts = $("opts");
460
+ opts.textContent = "";
461
+ const canPick = !!card.render_args && (bridge || (window.openai && typeof window.openai.callTool === "function"));
462
+ for (const [attr, o] of Object.entries(card.options || {})) {
463
+ const row = document.createElement("div");
464
+ const label = document.createElement("div");
465
+ label.className = "opt-label";
466
+ label.textContent = attr;
467
+ const chips = document.createElement("div");
468
+ chips.className = "chips";
469
+ for (const choice of o.choices || []) {
470
+ const b = document.createElement("button");
471
+ b.type = "button";
472
+ b.className = "chip";
473
+ b.textContent = choice;
474
+ b.dataset.attr = attr;
475
+ b.dataset.choice = choice;
476
+ b.setAttribute("aria-pressed", String(o.selected === choice));
477
+ b.disabled = !canPick;
478
+ b.addEventListener("click", () => pick(attr, choice));
479
+ chips.appendChild(b);
480
+ }
481
+ row.appendChild(label);
482
+ row.appendChild(chips);
483
+ opts.appendChild(row);
484
+ }
485
+
486
+ const btn = $("buyBtn");
487
+ const note = $("note");
488
+ const missing = Object.entries(card.options || {}).find(([, o]) => !o.selected);
489
+ cardEl.dataset.missingOption = missing ? missing[0] : "";
490
+ if (card.orders && card.orders.orders === "open" && missing) {
491
+ // Never let a shopper buy a size (or colour) nobody chose.
492
+ btn.disabled = true;
493
+ btn.textContent = "Choose a " + missing[0];
494
+ note.textContent = canPick ? "Pick one above, then buy." : "Ask for the " + missing[0] + " you want.";
495
+ } else if (card.orders && card.orders.orders === "open") {
496
+ btn.disabled = false;
497
+ btn.textContent = card.product && card.product.price_cents != null ? "Buy \xB7 " + money(card.product.price_cents) : "Buy";
498
+ note.textContent = "Opens checkout in your browser.";
499
+ } else {
500
+ btn.disabled = true;
501
+ btn.textContent = "Orders open soon";
502
+ note.textContent = card.orders && card.orders.reason === "prelaunch"
503
+ ? "Snowcone hasn't launched yet. This is exactly what you'd get."
504
+ : "We couldn't confirm ordering is available right now.";
505
+ }
506
+ $("buy").hidden = false;
507
+ resize();
508
+ }
509
+
510
+ async function pick(attr, choice) {
511
+ if (!card || !card.render_args) return;
512
+ const current = {};
513
+ for (const [a, o] of Object.entries(card.options || {})) if (o.selected) current[a] = o.selected;
514
+ const args = Object.assign({}, card.render_args, { options: Object.assign(current, { [attr]: choice }) });
515
+ cardEl.dataset.busy = "true";
516
+ try {
517
+ let result;
518
+ if (bridge) result = await request("tools/call", { name: "snowcone_render_mockup", arguments: args });
519
+ else result = await window.openai.callTool("snowcone_render_mockup", args);
520
+ const sc = result && (result.structuredContent || (result.result && result.result.structuredContent));
521
+ if (result && result.isError) {
522
+ cardEl.dataset.busy = "false";
523
+ showError(textOf(result));
524
+ } else if (sc && sc.card) render(sc.card);
525
+ else cardEl.dataset.busy = "false";
526
+ } catch (err) {
527
+ cardEl.dataset.busy = "false";
528
+ showError(String(err && err.message || err));
529
+ }
530
+ }
531
+
532
+ function textOf(result) {
533
+ const c = (result && result.content) || [];
534
+ return c.filter((x) => x && x.type === "text").map((x) => x.text).join("\\n");
535
+ }
536
+
537
+ $("buyBtn").addEventListener("click", async () => {
538
+ if (!card || !card.orders || card.orders.orders !== "open" || cardEl.dataset.missingOption) return;
539
+ const url = card.buy_url;
540
+ if (!/^https:\\/\\//.test(url)) return;
541
+ try {
542
+ if (bridge) { await request("ui/open-link", { url }); return; }
543
+ if (window.openai && typeof window.openai.openExternal === "function") { window.openai.openExternal({ href: url }); return; }
544
+ } catch (_) { /* fall through to a plain new tab */ }
545
+ window.open(url, "_blank", "noopener");
546
+ });
547
+
548
+ let lastH = 0;
549
+ function resize() {
550
+ const h = Math.ceil(document.documentElement.getBoundingClientRect().height);
551
+ if (bridge && h !== lastH) { lastH = h; notify("ui/notifications/size-changed", { height: h }); }
552
+ }
553
+ if (typeof ResizeObserver === "function") new ResizeObserver(resize).observe(document.body);
554
+
555
+ function onToolResult(result) {
556
+ if (!result) return;
557
+ if (result.isError) { showError(textOf(result)); return; }
558
+ const sc = result.structuredContent;
559
+ if (sc && sc.card) render(sc.card);
560
+ }
561
+
562
+ window.addEventListener("message", (event) => {
563
+ if (event.source !== window.parent) return;
564
+ const m = event.data;
565
+ if (!m || m.jsonrpc !== "2.0") return;
566
+ if (m.method === undefined && m.id !== undefined && pending.has(m.id)) {
567
+ const p = pending.get(m.id);
568
+ pending.delete(m.id);
569
+ if (m.error) p.reject(new Error(m.error.message || "host error"));
570
+ else p.resolve(m.result);
571
+ return;
572
+ }
573
+ switch (m.method) {
574
+ case "ui/notifications/tool-result": onToolResult(m.params); break;
575
+ case "ui/notifications/tool-cancelled": showError("The render was cancelled."); break;
576
+ case "ui/notifications/host-context-changed": applyTheme(m.params); break;
577
+ default:
578
+ // Answer any host request we don't handle (e.g. ui/resource-teardown) so the host never hangs.
579
+ if (m.id !== undefined && m.method) post({ jsonrpc: "2.0", id: m.id, result: {} });
580
+ }
581
+ });
582
+
583
+ // OpenAI Apps SDK globals, where a host injects them.
584
+ function fromOpenAi() {
585
+ const o = window.openai;
586
+ if (!o) return;
587
+ applyTheme({ theme: o.theme });
588
+ if (o.toolOutput && o.toolOutput.card) render(o.toolOutput.card);
589
+ }
590
+ window.addEventListener("openai:set_globals", fromOpenAi);
591
+ fromOpenAi();
592
+
593
+ // MCP Apps handshake.
594
+ request("ui/initialize", {
595
+ appInfo: { name: "snowcone-mockup-card", version: "__VERSION__" },
596
+ appCapabilities: {},
597
+ protocolVersion: "2026-01-26",
598
+ }).then((r) => {
599
+ bridge = true;
600
+ applyTheme(r && r.hostContext);
601
+ notify("ui/notifications/initialized", {});
602
+ if (card) render(card); // re-enable the picker now that tools/call is available
603
+ resize();
604
+ }).catch(() => { /* no MCP Apps host: the openai globals (if any) drive the card */ });
605
+ })();
606
+ </script>
607
+ </body>
608
+ </html>
609
+ `;
610
+
246
611
  // src/http.ts
247
612
  function ok(structured, text) {
248
613
  return {
@@ -481,6 +846,78 @@ async function searchDesigns(query, limit, offset, filter, semanticRatio) {
481
846
  return { hits: body.hits ?? [], estimatedTotalHits: body.estimatedTotalHits ?? body.hits?.length ?? 0 };
482
847
  }
483
848
 
849
+ // src/drafts.ts
850
+ var KNOWN = ["ok", "blocked", "limited", "budget-exhausted", "no-product", "unavailable"];
851
+ async function searchDrafts(query, forwardedFor) {
852
+ const none = (status, detail) => ({ status, detail, drafts: [], cached: false, subject: "", product_terms: "" });
853
+ try {
854
+ const r = await httpJson(`${API_BASE}/agent-drafts/search`, {
855
+ method: "POST",
856
+ body: { query },
857
+ ...forwardedFor ? { headers: { "X-Forwarded-For": forwardedFor } } : {}
858
+ });
859
+ const status = KNOWN.find((s) => s === r.status);
860
+ if (!status) return none("unreachable", `Draft designs answered with an unknown status (${String(r.status).slice(0, 40)}).`);
861
+ return {
862
+ status,
863
+ detail: typeof r.detail === "string" ? r.detail : "",
864
+ // Only what passed moderation is ever shown, whatever the wire says.
865
+ drafts: Array.isArray(r.drafts) ? r.drafts.filter((d) => d && d.moderated === true && typeof d.mockup_url === "string") : [],
866
+ cached: r.cached === true,
867
+ subject: typeof r.subject === "string" ? r.subject : "",
868
+ product_terms: typeof r.product_terms === "string" ? r.product_terms : ""
869
+ };
870
+ } catch (err) {
871
+ const why = err instanceof HttpError ? `HTTP ${err.status}` : err instanceof Error ? err.message : String(err);
872
+ return none("unreachable", `Draft designs could not be reached (${why.slice(0, 120)}). The catalog results are unaffected.`);
873
+ }
874
+ }
875
+ var money = (cents) => `$${(cents / 100).toFixed(2)}`;
876
+ function draftsText(query, a) {
877
+ if (a.status === "ok" && a.drafts.length > 0) {
878
+ const lines = a.drafts.flatMap(
879
+ (d, i) => d.mockups.map((m) => `- Draft ${i + 1} on ${m.product_name} (${money(m.price_cents)}): ${m.mockup_url}`).concat(` Draft ${i + 1} design: ${d.image_url}`)
880
+ );
881
+ return `Fresh draft designs for "${query}" (made just now, low-res, labelled drafts):
882
+ ${lines.join("\n")}
883
+ ${a.detail}`;
884
+ }
885
+ if (a.status === "unavailable" || a.status === "unreachable") return `No fresh drafts this time: ${a.detail}`;
886
+ return a.detail ? `No fresh drafts: ${a.detail}` : "";
887
+ }
888
+
889
+ // src/launch.ts
890
+ var launchFetch = (url, init) => fetch(url, init);
891
+ var TTL_MS = 6e4;
892
+ var cached = null;
893
+ async function readOrdersState(now = Date.now()) {
894
+ if (cached && now - cached.at < TTL_MS) return cached.state;
895
+ const state = await fetchState();
896
+ if (!(state.orders === "not-open" && state.reason === "unreadable")) cached = { at: now, state };
897
+ return state;
898
+ }
899
+ async function fetchState() {
900
+ try {
901
+ const res = await launchFetch(LAUNCH_URL, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(3e3) });
902
+ if (!res.ok) return unreadable(`HTTP ${res.status} from ${LAUNCH_URL}`);
903
+ const body = await res.json();
904
+ if (body.orders === "open") return { orders: "open" };
905
+ if (body.orders === "not-open" && body.reason === "prelaunch") return { orders: "not-open", reason: "prelaunch" };
906
+ return unreadable(`unexpected answer from ${LAUNCH_URL}: ${JSON.stringify(body).slice(0, 200)}`);
907
+ } catch (err) {
908
+ return unreadable(`${LAUNCH_URL}: ${err instanceof Error ? err.message : String(err)}`);
909
+ }
910
+ }
911
+ function unreadable(detail) {
912
+ return { orders: "not-open", reason: "unreadable", detail };
913
+ }
914
+ function ordersLine(s) {
915
+ if (s.orders === "open") return "Orders are open: the buy link takes the person to checkout.";
916
+ if (s.reason === "prelaunch")
917
+ return "Orders open soon: Snowcone hasn't launched yet. Show the person the mockup, but don't offer the buy link as a way to order today.";
918
+ return "Couldn't confirm that orders are open right now, so don't offer the buy link yet; the mockup is fine to show.";
919
+ }
920
+
484
921
  // src/orders.ts
485
922
  async function getQuote(input) {
486
923
  const q = new URLSearchParams({ quote: "1" });
@@ -519,17 +956,6 @@ function orderStatusText(r) {
519
956
  ].join("\n");
520
957
  }
521
958
 
522
- // src/version.ts
523
- import { createRequire } from "module";
524
- var VERSION = (() => {
525
- try {
526
- const pkg = createRequire(import.meta.url)("../package.json");
527
- return pkg.version ?? "0.0.0";
528
- } catch {
529
- return "0.0.0";
530
- }
531
- })();
532
-
533
959
  // src/quickstart.ts
534
960
  var QUICKSTART = `# Snowcone in one screen (for agents)
535
961
 
@@ -633,6 +1059,7 @@ Until you lock the shop, treat any artwork you render on it as effectively publi
633
1059
  function mintShop(input) {
634
1060
  return httpJson(`${API_BASE}/shops/sandbox`, {
635
1061
  method: "POST",
1062
+ ...input.forwardedFor ? { headers: { "X-Forwarded-For": input.forwardedFor } } : {},
636
1063
  body: {
637
1064
  ...input.name ? { name: input.name } : {},
638
1065
  ...input.claim_pin ? { claim_pin: input.claim_pin } : {},
@@ -691,7 +1118,12 @@ var renderUrl = (input) => buildUrl(input, IMG_BASE);
691
1118
  var buyUrl = (input) => buildUrl(input, BUY_BASE);
692
1119
 
693
1120
  // src/server.ts
694
- var server = new McpServer({ name: "snowcone-mcp-server", version: VERSION });
1121
+ function createServer(ctx = {}) {
1122
+ const server2 = new McpServer({ name: "snowcone-mcp-server", version: VERSION });
1123
+ registerCard(server2, ctx);
1124
+ registerTools(server2, ctx);
1125
+ return server2;
1126
+ }
695
1127
  var fillSchema = z.union([
696
1128
  z.string().describe("A public image URL for this placement."),
697
1129
  z.object({
@@ -739,170 +1171,6 @@ function toUrlInput(a) {
739
1171
  ...a.shop_secret !== void 0 ? { shopSecret: a.shop_secret } : {}
740
1172
  };
741
1173
  }
742
- server.registerTool(
743
- "snowcone_quickstart",
744
- {
745
- title: "Snowcone Quickstart",
746
- description: "Make custom printed products from any photo, design or text \u2014 t-shirts, mugs, hoodies, totes, posters \u2014 with a photoreal preview and a link to buy, printed and shipped for the user. Return the entire Snowcone model and the recommended tool order in one screen. Call this FIRST when you're new to Snowcone \u2014 it explains how to mint a shop, render a mockup, and sell it, plus the silent-failure gotchas.",
747
- inputSchema: {},
748
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }
749
- },
750
- async () => ({ content: [{ type: "text", text: QUICKSTART }] })
751
- );
752
- server.registerTool(
753
- "snowcone_mint_shop",
754
- {
755
- title: "Mint a sandbox Shop",
756
- description: "Start a print-on-demand merch store for a creator, podcast or brand in one call \u2014 no account, no inventory; every order is printed and shipped. Mint your OWN sandbox Shop ID \u2014 no account or human needed. Returns { shop_id, shop_secret, api_key, api_key_scopes, store_url, lineup, claim }. When store_url is set, the shop is already a live store at that link \u2014 show it to the person you're helping. Pass image_url (the person's art, logo or photo) and the store opens stocked with best-sellers wearing that image \u2014 real listings at catalog prices, with mockups and checkout \u2014 listed in lineup. IMPORTANT: mint ONCE and reuse the shop_id for all render/buy calls \u2014 minting is rate-limited (60/hour, 200 unclaimed per IP \u2192 HTTP 429). shop_id is public (use it as 'shop'); shop_secret and api_key are secret (server-side only). To get paid, hand claim.verification_uri_complete to your human and poll snowcone_claim_status.",
757
- inputSchema: {
758
- name: z.string().optional().describe("Optional shop name (e.g. 'Jess Prints'); it also names the store's web address. Defaults to 'Sandbox <id>'."),
759
- claim_pin: z.string().optional().describe("Optional out-of-band PIN your human must enter to claim (deliver it separately from the link)."),
760
- require_signature: z.boolean().optional().describe(
761
- "Lock the shop down: require SIGNED mockup URLs (L3). Default false \u2014 the shop is open and any unsigned URL renders (simplest to start). Set true to harden against Shop-ID theft: then every render/buy URL must be signed with the returned shop_secret (pass it as shop_secret to snowcone_render_mockup / buy URLs). Unsigned URLs will 403."
762
- ),
763
- mockup_bg_color: z.string().optional().describe(
764
- "Default background painted behind every mockup render (6-hex, '#' optional, e.g. 'f5f0ea'). Visible only where the mockup scene is transparent (studio-cutout shots). Omit for transparent (the default). Change it later with snowcone_set_mockup_background; a per-render bg overrides it."
765
- ),
766
- image_url: z.string().url().optional().describe(
767
- "Optional art for the store to open with: an https URL of a public PNG, JPEG, WebP or AVIF image (at most 10 MB). The store then opens stocked with best-sellers wearing that image, ready to sell. A bad image fails the mint with a typed E_MINT_IMAGE_* error and creates nothing. Omit for an empty store that shows what it will sell once art is added."
768
- )
769
- },
770
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true }
771
- },
772
- async (args) => {
773
- try {
774
- const r = await mintShop({
775
- ...args.name !== void 0 ? { name: args.name } : {},
776
- ...args.claim_pin !== void 0 ? { claim_pin: args.claim_pin } : {},
777
- ...args.require_signature ? { require_signed_urls: true } : {},
778
- ...args.mockup_bg_color !== void 0 ? { mockup_bg_color: args.mockup_bg_color } : {},
779
- ...args.image_url !== void 0 ? { image_url: args.image_url } : {}
780
- });
781
- const sigLine = r.require_signed_urls ? `This shop REQUIRES signed URLs: pass shop_secret=${r.shop_secret} as shop_secret on every render/buy call, or the edge 403s.
782
- ` : `This shop is OPEN (unsigned URLs render). To lock it later, your human can toggle "Require signed URLs" on /studio/api-keys.
783
- `;
784
- const storeLine = r.store_url ? `Your store is live at ${r.store_url} \u2014 show this link to the person you're helping.
785
- ` : "";
786
- const lineupLine = r.lineup?.listings.length ? `It opened stocked with ${r.lineup.listings.length} best-sellers wearing your image:
787
- ` + r.lineup.listings.map((l) => `- ${l.product_name} \u2014 $${(l.price_cents / 100).toFixed(2)}${l.url ? ` \u2014 ${l.url}` : ""} (mockup: ${l.mockup_url})`).join("\n") + "\n" : "";
788
- const text = storeLine + lineupLine + `Minted shop_id=${r.shop_id} (REUSE this \u2014 don't mint again).
789
- shop_secret=${r.shop_secret} (secret)
790
- api_key=${r.api_key} (secret; scopes: ${r.api_key_scopes.join(", ")})
791
- ` + sigLine + `To get paid, send your human: ${r.claim.verification_uri_complete}
792
- claim_token=${r.claim.claim_token} (secret)
793
- Poll claim with that claim_token via snowcone_claim_status. Expires in ${r.claim.expires_in}s.
794
- Note: the shop takes ~1-3s to propagate to the render edge \u2014 a render right after minting can 404 "Unknown shop"; wait a second and retry.`;
795
- return ok(r, text);
796
- } catch (err) {
797
- return fail(formatError(err));
798
- }
799
- }
800
- );
801
- server.registerTool(
802
- "snowcone_claim_status",
803
- {
804
- title: "Poll Shop claim status",
805
- description: "Check whether your human has claimed the shop yet. Pass the claim_token from snowcone_mint_shop. Returns status: 'pending' | 'claimed' | 'expired'. Once 'claimed', sales route to your human's account.",
806
- inputSchema: {
807
- claim_token: z.string().min(1).describe("The claim_token returned by snowcone_mint_shop (ct_\u2026).")
808
- },
809
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
810
- },
811
- async (args) => {
812
- try {
813
- return ok(await claimStatus(args.claim_token));
814
- } catch (err) {
815
- return fail(formatError(err));
816
- }
817
- }
818
- );
819
- server.registerTool(
820
- "snowcone_release_shop",
821
- {
822
- title: "Release a sandbox Shop",
823
- description: "Delete an UNCLAIMED sandbox shop you minted, freeing your per-IP mint budget. Authenticated by the shop_secret. Refused if the shop has already been claimed. Use this when you're done iterating. What survives: already-produced mockup IMAGE URLs keep rendering (they're public marketing imagery). What dies: buy/checkout URLs, the shop's credentials (shop_secret, api_key), and the claim link. Irreversible.",
824
- inputSchema: {
825
- shop_id: z.string().min(1).describe("The sandbox shop_id to release."),
826
- shop_secret: z.string().min(1).describe("The shop_secret from snowcone_mint_shop (scsec_\u2026).")
827
- },
828
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
829
- },
830
- async (args) => {
831
- try {
832
- const r = await releaseShop(args.shop_id, args.shop_secret);
833
- return ok(
834
- r,
835
- `Released shop_id=${r.shop_id}. Already-produced mockup IMAGE URLs keep rendering (public marketing imagery survives release). Buy/checkout URLs, the shop_secret, the api_key, and the claim link are now dead. Your per-IP mint budget is freed.`
836
- );
837
- } catch (err) {
838
- return fail(formatError(err));
839
- }
840
- }
841
- );
842
- server.registerTool(
843
- "snowcone_set_mockup_background",
844
- {
845
- title: "Set the shop's default mockup background",
846
- description: "Set (or clear) the shop's DEFAULT background color for mockup renders \u2014 painted behind every render where the mockup scene is transparent (studio-cutout shots). Applies to all renders for the shop that don't pass an explicit bg; a per-render bg on snowcone_render_mockup overrides it. Sandbox shops only (authenticated by shop_secret); once claimed, your human manages this in shop settings \u2192 Branding. Takes effect on new renders within a few seconds (already-cached mockup URLs keep their old background).",
847
- inputSchema: {
848
- shop_id: z.string().min(1).describe("The sandbox shop_id to update."),
849
- shop_secret: z.string().min(1).describe("The shop_secret from snowcone_mint_shop (scsec_\u2026)."),
850
- color: z.string().nullable().describe("6-hex color ('#' optional, e.g. 'f5f0ea' or '#F5F0EA'), or null to clear back to transparent.")
851
- },
852
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true }
853
- },
854
- async (args) => {
855
- try {
856
- const r = await setMockupBackground(args.shop_id, args.shop_secret, args.color);
857
- const stated = r.mockup_bg_color === null ? "transparent (cleared)" : `#${r.mockup_bg_color}`;
858
- return ok(
859
- r,
860
- `Default mockup background for shop_id=${r.shop_id} is now ${stated}. New renders pick it up within a few seconds; pass bg on snowcone_render_mockup to override per render.`
861
- );
862
- } catch (err) {
863
- return fail(formatError(err));
864
- }
865
- }
866
- );
867
- server.registerTool(
868
- "snowcone_search_catalog",
869
- {
870
- title: "Search the product catalog",
871
- description: "Find products to put a photo or design on \u2014 t-shirts, hoodies, mugs, totes, posters and more \u2014 with their suggested retail prices. Full-text search the public Snowcone catalog (t-shirts, hoodies, mugs, \u2026). Returns matching products with their code (id), name, price_cents (suggested retail, USD cents), and placement/mockup counts. Use snowcone_get_product for the full placement/mockup/option detail needed to render.",
872
- inputSchema: {
873
- query: z.string().default("").describe("Search text. Empty string lists popular products."),
874
- limit: z.number().int().min(1).max(50).default(10).describe("Max results (1-50)."),
875
- offset: z.number().int().min(0).default(0).describe("Pagination offset.")
876
- },
877
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
878
- },
879
- async (args) => {
880
- try {
881
- const { hits, estimatedTotalHits } = await searchCatalog(args.query, args.limit, args.offset);
882
- const items = hits.map((h) => ({
883
- id: h.id,
884
- name: h.name,
885
- price_cents: h.basePrice ?? h.price,
886
- placements: h.placements?.length ?? 0,
887
- mockups: h.mockups?.length ?? 0
888
- }));
889
- const out = {
890
- total: estimatedTotalHits,
891
- count: items.length,
892
- offset: args.offset,
893
- items,
894
- has_more: estimatedTotalHits > args.offset + items.length
895
- };
896
- let text = JSON.stringify(out, null, 2);
897
- if (text.length > CHARACTER_LIMIT) {
898
- text = JSON.stringify({ ...out, items: items.slice(0, 5), truncated: true }, null, 2);
899
- }
900
- return { content: [{ type: "text", text }], structuredContent: out };
901
- } catch (err) {
902
- return fail(formatError(err));
903
- }
904
- }
905
- );
906
1174
  async function summarizeDesign(d, shop, shopSecret) {
907
1175
  const base = {
908
1176
  pairing_id: d.pairingId ?? d.id,
@@ -926,256 +1194,499 @@ async function summarizeDesign(d, shop, shopSecret) {
926
1194
  const url = await renderUrl(input);
927
1195
  return shop ? { ...base, mockup_url: url } : { ...base, mockup_url_template: url };
928
1196
  }
929
- server.registerTool(
930
- "snowcone_search_designs",
931
- {
932
- title: "Search the pre-made designs catalog",
933
- description: "Search the public catalog of remixable published designs \u2014 hybrid semantic + keyword over each design's AI visual caption, so descriptive queries like 'pink cowgirl boots on the moon' work (e.g. holiday cards, tees, posters; filter curated = true for first-party-curated picks) so an integration never starts from a blank canvas. Filterable facets: tags, occasion, style, productId, minPriceCents, curated. Each result includes the design's product, license, and a ready-to-render mockup_url (a design=<pairingId> reference URL) when you pass your 'shop'. Catalog design renders are FREE \u2014 they don't count against the shop's usage budget. Without 'shop' you get a mockup_url_template containing YOUR_SHOP_ID to substitute.",
934
- inputSchema: {
935
- query: z.string().default("").describe("Search text, e.g. 'christmas card'. Empty string lists curated designs."),
936
- limit: z.number().int().min(1).max(50).default(10).describe("Max results (1-50)."),
937
- offset: z.number().int().min(0).default(0).describe("Pagination offset."),
938
- filter: z.string().optional().describe(`Meilisearch filter expression, e.g. "occasion = 'christmas' AND style = 'watercolor'".`),
939
- semantic_ratio: z.number().min(0).max(1).default(0.5).describe("Semantic vs keyword blend (0 = keyword-only, 1 = fully semantic). Default 0.5."),
940
- shop: z.string().optional().describe("Your public Shop ID \u2014 when set, each result includes a ready-to-render mockup_url."),
941
- shop_secret: z.string().optional().describe("Per-shop secret (scsec_\u2026). With 'shop', URLs are L3-signed (server-side only \u2014 never expose it).")
1197
+ function registerCard(server2, ctx) {
1198
+ const opts = ctx.cardBeaconUrl ? { beaconUrl: ctx.cardBeaconUrl } : {};
1199
+ server2.registerResource(
1200
+ "Snowcone mockup card",
1201
+ CARD_URI,
1202
+ {
1203
+ title: "Snowcone mockup card",
1204
+ description: "The person's design on the product, with price, option choices and Buy.",
1205
+ mimeType: CARD_MIME,
1206
+ _meta: cardResourceMeta(opts)
942
1207
  },
943
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
944
- },
945
- async (args) => {
946
- try {
947
- const { hits, estimatedTotalHits } = await searchDesigns(args.query, args.limit, args.offset, args.filter, args.semantic_ratio);
948
- const items = await Promise.all(hits.map((h) => summarizeDesign(h, args.shop, args.shop_secret)));
949
- const out = {
950
- total: estimatedTotalHits,
951
- count: items.length,
952
- offset: args.offset,
953
- items,
954
- has_more: estimatedTotalHits > args.offset + items.length
955
- };
956
- let text = JSON.stringify(out, null, 2);
957
- if (text.length > CHARACTER_LIMIT) {
958
- text = JSON.stringify({ ...out, items: items.slice(0, 5), truncated: true }, null, 2);
1208
+ async () => ({
1209
+ contents: [{ uri: CARD_URI, mimeType: CARD_MIME, text: cardHtml(opts), _meta: cardResourceMeta(opts) }]
1210
+ })
1211
+ );
1212
+ }
1213
+ function pickableOptions(p, chosen) {
1214
+ const attrs = p?.options?.attributes;
1215
+ const out = {};
1216
+ for (const [attr, meta] of Object.entries(attrs ?? {})) {
1217
+ const choices = (meta.choices ?? []).map((c) => c.label).filter((l) => typeof l === "string" && l.length > 0);
1218
+ if (choices.length < 2) continue;
1219
+ const picked = chosen?.[attr];
1220
+ out[attr] = { choices, selected: picked !== void 0 && choices.includes(picked) ? picked : null };
1221
+ }
1222
+ return out;
1223
+ }
1224
+ async function buildCard(args, imageUrl, orders, product) {
1225
+ const { shop_secret, verify: _verify, ...rest } = args;
1226
+ return {
1227
+ image_url: imageUrl,
1228
+ product: product ? {
1229
+ id: product.id,
1230
+ name: product.name ?? product.id,
1231
+ price_cents: typeof (product.basePrice ?? product.price) === "number" ? product.basePrice ?? product.price : null
1232
+ } : null,
1233
+ options: pickableOptions(product, args.options),
1234
+ buy_url: await buyUrl(toUrlInput(args)),
1235
+ orders,
1236
+ // A signed shop's secret never goes into the card, so its picker can't re-sign: no picker there.
1237
+ render_args: shop_secret ? null : rest
1238
+ };
1239
+ }
1240
+ function registerTools(server2, ctx) {
1241
+ server2.registerTool(
1242
+ "snowcone_quickstart",
1243
+ {
1244
+ title: "Snowcone Quickstart",
1245
+ description: "Make custom printed products from any photo, design or text \u2014 t-shirts, mugs, hoodies, totes, posters \u2014 with a photoreal preview and a link to buy, printed and shipped for the user. Return the entire Snowcone model and the recommended tool order in one screen. Call this FIRST when you're new to Snowcone \u2014 it explains how to mint a shop, render a mockup, and sell it, plus the silent-failure gotchas.",
1246
+ inputSchema: {},
1247
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }
1248
+ },
1249
+ async () => ({ content: [{ type: "text", text: QUICKSTART }] })
1250
+ );
1251
+ server2.registerTool(
1252
+ "snowcone_mint_shop",
1253
+ {
1254
+ title: "Mint a sandbox Shop",
1255
+ description: "Start a print-on-demand merch store for a creator, podcast or brand in one call \u2014 no account, no inventory; every order is printed and shipped. Mint your OWN sandbox Shop ID \u2014 no account or human needed. Returns { shop_id, shop_secret, api_key, api_key_scopes, store_url, lineup, claim }. When store_url is set, the shop is already a live store at that link \u2014 show it to the person you're helping. Pass image_url (the person's art, logo or photo) and the store opens stocked with best-sellers wearing that image \u2014 real listings at catalog prices, with mockups and checkout \u2014 listed in lineup. IMPORTANT: mint ONCE and reuse the shop_id for all render/buy calls \u2014 minting is rate-limited (60/hour, 200 unclaimed per IP \u2192 HTTP 429). shop_id is public (use it as 'shop'); shop_secret and api_key are secret (server-side only). To get paid, hand claim.verification_uri_complete to your human and poll snowcone_claim_status.",
1256
+ inputSchema: {
1257
+ name: z.string().optional().describe("Optional shop name (e.g. 'Jess Prints'); it also names the store's web address. Defaults to 'Sandbox <id>'."),
1258
+ claim_pin: z.string().optional().describe("Optional out-of-band PIN your human must enter to claim (deliver it separately from the link)."),
1259
+ require_signature: z.boolean().optional().describe(
1260
+ "Lock the shop down: require SIGNED mockup URLs (L3). Default false \u2014 the shop is open and any unsigned URL renders (simplest to start). Set true to harden against Shop-ID theft: then every render/buy URL must be signed with the returned shop_secret (pass it as shop_secret to snowcone_render_mockup / buy URLs). Unsigned URLs will 403."
1261
+ ),
1262
+ mockup_bg_color: z.string().optional().describe(
1263
+ "Default background painted behind every mockup render (6-hex, '#' optional, e.g. 'f5f0ea'). Visible only where the mockup scene is transparent (studio-cutout shots). Omit for transparent (the default). Change it later with snowcone_set_mockup_background; a per-render bg overrides it."
1264
+ ),
1265
+ image_url: z.string().url().optional().describe(
1266
+ "Optional art for the store to open with: an https URL of a public PNG, JPEG, WebP or AVIF image (at most 10 MB). The store then opens stocked with best-sellers wearing that image, ready to sell. A bad image fails the mint with a typed E_MINT_IMAGE_* error and creates nothing. Omit for an empty store that shows what it will sell once art is added."
1267
+ )
1268
+ },
1269
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true }
1270
+ },
1271
+ async (args) => {
1272
+ try {
1273
+ const r = await mintShop({
1274
+ ...ctx.forwardedFor ? { forwardedFor: ctx.forwardedFor } : {},
1275
+ ...args.name !== void 0 ? { name: args.name } : {},
1276
+ ...args.claim_pin !== void 0 ? { claim_pin: args.claim_pin } : {},
1277
+ ...args.require_signature ? { require_signed_urls: true } : {},
1278
+ ...args.mockup_bg_color !== void 0 ? { mockup_bg_color: args.mockup_bg_color } : {},
1279
+ ...args.image_url !== void 0 ? { image_url: args.image_url } : {}
1280
+ });
1281
+ const sigLine = r.require_signed_urls ? `This shop REQUIRES signed URLs: pass shop_secret=${r.shop_secret} as shop_secret on every render/buy call, or the edge 403s.
1282
+ ` : `This shop is OPEN (unsigned URLs render). To lock it later, your human can toggle "Require signed URLs" on /studio/api-keys.
1283
+ `;
1284
+ const storeLine = r.store_url ? `Your store is live at ${r.store_url} \u2014 show this link to the person you're helping.
1285
+ ` : "";
1286
+ const lineupLine = r.lineup?.listings.length ? `It opened stocked with ${r.lineup.listings.length} best-sellers wearing your image:
1287
+ ` + r.lineup.listings.map((l) => `- ${l.product_name} \u2014 $${(l.price_cents / 100).toFixed(2)}${l.url ? ` \u2014 ${l.url}` : ""} (mockup: ${l.mockup_url})`).join("\n") + "\n" : "";
1288
+ const text = storeLine + lineupLine + `Minted shop_id=${r.shop_id} (REUSE this \u2014 don't mint again).
1289
+ shop_secret=${r.shop_secret} (secret)
1290
+ api_key=${r.api_key} (secret; scopes: ${r.api_key_scopes.join(", ")})
1291
+ ` + sigLine + `To get paid, send your human: ${r.claim.verification_uri_complete}
1292
+ claim_token=${r.claim.claim_token} (secret)
1293
+ Poll claim with that claim_token via snowcone_claim_status. Expires in ${r.claim.expires_in}s.
1294
+ Note: the shop takes ~1-3s to propagate to the render edge \u2014 a render right after minting can 404 "Unknown shop"; wait a second and retry.`;
1295
+ return ok(r, text);
1296
+ } catch (err) {
1297
+ return fail(formatError(err));
959
1298
  }
960
- return { content: [{ type: "text", text }], structuredContent: out };
961
- } catch (err) {
962
- return fail(formatError(err));
963
1299
  }
964
- }
965
- );
966
- server.registerTool(
967
- "snowcone_get_product",
968
- {
969
- title: "Get a product",
970
- description: "Fetch one product by its code (id) or slug. Returns placements (where art goes), mockups (scene ids for the 'view' param), and variant options \u2014 everything you need to build a render URL. Returns an error if the code doesn't exist (it would render blank).",
971
- inputSchema: {
972
- // eng/0049 F1 (growth/0013 cold-agent run): every sibling tool takes
973
- // `product`, and the prose says "product code" — the one tool that
974
- // spelled it `id_or_slug` cost every cold agent a guaranteed failed
975
- // round-trip. `product` is the canonical name; `id_or_slug` stays as a
976
- // silent alias so agents that learned the old name keep working.
977
- product: z.string().min(1).optional().describe("Product code (the catalog document id) or slug, e.g. 'BC43BE'. Same name as every other tool."),
978
- id_or_slug: z.string().min(1).optional().describe("Deprecated alias of 'product' \u2014 accepted for back-compat; prefer 'product'.")
1300
+ );
1301
+ server2.registerTool(
1302
+ "snowcone_claim_status",
1303
+ {
1304
+ title: "Poll Shop claim status",
1305
+ description: "Check whether your human has claimed the shop yet. Pass the claim_token from snowcone_mint_shop. Returns status: 'pending' | 'claimed' | 'expired'. Once 'claimed', sales route to your human's account.",
1306
+ inputSchema: {
1307
+ claim_token: z.string().min(1).describe("The claim_token returned by snowcone_mint_shop (ct_\u2026).")
1308
+ },
1309
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
979
1310
  },
980
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
981
- },
982
- async (args) => {
983
- try {
984
- const code = args.product ?? args.id_or_slug;
985
- if (!code) {
986
- return fail(
987
- "E_MISSING_PRODUCT: pass product (the product code or slug, e.g. { product: 'BC43BE' }) \u2014 the same 'product' argument snowcone_render_mockup and snowcone_buy_url take."
1311
+ async (args) => {
1312
+ try {
1313
+ return ok(await claimStatus(args.claim_token));
1314
+ } catch (err) {
1315
+ return fail(formatError(err));
1316
+ }
1317
+ }
1318
+ );
1319
+ server2.registerTool(
1320
+ "snowcone_release_shop",
1321
+ {
1322
+ title: "Release a sandbox Shop",
1323
+ description: "Delete an UNCLAIMED sandbox shop you minted, freeing your per-IP mint budget. Authenticated by the shop_secret. Refused if the shop has already been claimed. Use this when you're done iterating. What survives: already-produced mockup IMAGE URLs keep rendering (they're public marketing imagery). What dies: buy/checkout URLs, the shop's credentials (shop_secret, api_key), and the claim link. Irreversible.",
1324
+ inputSchema: {
1325
+ shop_id: z.string().min(1).describe("The sandbox shop_id to release."),
1326
+ shop_secret: z.string().min(1).describe("The shop_secret from snowcone_mint_shop (scsec_\u2026).")
1327
+ },
1328
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
1329
+ },
1330
+ async (args) => {
1331
+ try {
1332
+ const r = await releaseShop(args.shop_id, args.shop_secret);
1333
+ return ok(
1334
+ r,
1335
+ `Released shop_id=${r.shop_id}. Already-produced mockup IMAGE URLs keep rendering (public marketing imagery survives release). Buy/checkout URLs, the shop_secret, the api_key, and the claim link are now dead. Your per-IP mint budget is freed.`
988
1336
  );
1337
+ } catch (err) {
1338
+ return fail(formatError(err));
989
1339
  }
990
- const p = await getProduct(code);
991
- if (!p) return fail(`Error: no product found for '${code}'. It would render blank \u2014 pick one from snowcone_search_catalog.`);
992
- return ok(summarizeProduct(p));
993
- } catch (err) {
994
- return fail(formatError(err));
995
1340
  }
996
- }
997
- );
998
- server.registerTool(
999
- "snowcone_render_mockup",
1000
- {
1001
- title: "Render a mockup URL",
1002
- description: "Show the user their photo, design or text on a real product (t-shirt, mug, hoodie, tote, poster\u2026) as a photoreal preview image. Build a public mockup IMAGE url for a product + your artwork + your shop. The result is an <img>-ready URL \u2014 no API call, no upload. Provide 'asset' (one image) OR 'design' (per-placement map). The asset must be a publicly-fetchable raster image (PNG/JPEG/WebP/AVIF; not SVG), and the product code must exist in the catalog. Pass shop_secret to get an L3-signed URL. By DEFAULT the server fetches the built URL and confirms it actually renders, so a bad product code, wrong placement key, or unusable asset comes back as a clear error instead of a confident-but-broken URL. Pass verify=false to skip that check and just get the URL string instantly.",
1003
- inputSchema: {
1004
- ...urlShape,
1005
- verify: z.boolean().optional().describe(
1006
- "Fetch the built URL and confirm it returns a real image before reporting success (DEFAULT true). Turns silent failures into a clear, actionable error and retries once on a not-yet-propagated shop. Set false to skip the network round-trip and return the URL string unchecked."
1007
- )
1341
+ );
1342
+ server2.registerTool(
1343
+ "snowcone_set_mockup_background",
1344
+ {
1345
+ title: "Set the shop's default mockup background",
1346
+ description: "Set (or clear) the shop's DEFAULT background color for mockup renders \u2014 painted behind every render where the mockup scene is transparent (studio-cutout shots). Applies to all renders for the shop that don't pass an explicit bg; a per-render bg on snowcone_render_mockup overrides it. Sandbox shops only (authenticated by shop_secret); once claimed, your human manages this in shop settings \u2192 Branding. Takes effect on new renders within a few seconds (already-cached mockup URLs keep their old background).",
1347
+ inputSchema: {
1348
+ shop_id: z.string().min(1).describe("The sandbox shop_id to update."),
1349
+ shop_secret: z.string().min(1).describe("The shop_secret from snowcone_mint_shop (scsec_\u2026)."),
1350
+ color: z.string().nullable().describe("6-hex color ('#' optional, e.g. 'f5f0ea' or '#F5F0EA'), or null to clear back to transparent.")
1351
+ },
1352
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1008
1353
  },
1009
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1010
- },
1011
- async (args) => {
1012
- try {
1013
- const url = await renderUrl(toUrlInput(args));
1014
- const img_html = `<img src="${url}" style="object-fit:cover" alt="mockup" />`;
1015
- if (args.verify === false) {
1354
+ async (args) => {
1355
+ try {
1356
+ const r = await setMockupBackground(args.shop_id, args.shop_secret, args.color);
1357
+ const stated = r.mockup_bg_color === null ? "transparent (cleared)" : `#${r.mockup_bg_color}`;
1016
1358
  return ok(
1017
- {
1018
- url,
1019
- img_html,
1020
- notes: "Unverified (verify=false). Display with object-fit:cover and request ~2\xD7 the displayed size. The asset URL must be a publicly-fetchable raster image."
1021
- },
1022
- url
1359
+ r,
1360
+ `Default mockup background for shop_id=${r.shop_id} is now ${stated}. New renders pick it up within a few seconds; pass bg on snowcone_render_mockup to override per render.`
1023
1361
  );
1362
+ } catch (err) {
1363
+ return fail(formatError(err));
1364
+ }
1365
+ }
1366
+ );
1367
+ server2.registerTool(
1368
+ "snowcone_search_catalog",
1369
+ {
1370
+ title: "Search the product catalog",
1371
+ description: "Find products to put a photo or design on \u2014 t-shirts, hoodies, mugs, totes, posters and more \u2014 with their suggested retail prices. Full-text search the public Snowcone catalog (t-shirts, hoodies, mugs, \u2026). Returns matching products with their code (id), name, price_cents (suggested retail, USD cents), and placement/mockup counts. Use snowcone_get_product for the full placement/mockup/option detail needed to render.",
1372
+ inputSchema: {
1373
+ query: z.string().default("").describe("Search text. Empty string lists popular products."),
1374
+ limit: z.number().int().min(1).max(50).default(10).describe("Max results (1-50)."),
1375
+ offset: z.number().int().min(0).default(0).describe("Pagination offset.")
1376
+ },
1377
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1378
+ },
1379
+ async (args) => {
1380
+ try {
1381
+ const { hits, estimatedTotalHits } = await searchCatalog(args.query, args.limit, args.offset);
1382
+ const items = hits.map((h) => ({
1383
+ id: h.id,
1384
+ name: h.name,
1385
+ price_cents: h.basePrice ?? h.price,
1386
+ placements: h.placements?.length ?? 0,
1387
+ mockups: h.mockups?.length ?? 0
1388
+ }));
1389
+ const out = {
1390
+ total: estimatedTotalHits,
1391
+ count: items.length,
1392
+ offset: args.offset,
1393
+ items,
1394
+ has_more: estimatedTotalHits > args.offset + items.length
1395
+ };
1396
+ let text = JSON.stringify(out, null, 2);
1397
+ if (text.length > CHARACTER_LIMIT) {
1398
+ text = JSON.stringify({ ...out, items: items.slice(0, 5), truncated: true }, null, 2);
1399
+ }
1400
+ return { content: [{ type: "text", text }], structuredContent: out };
1401
+ } catch (err) {
1402
+ return fail(formatError(err));
1024
1403
  }
1025
- let v = await verifyImageUrl(url);
1026
- if (!v.ok && /unknown shop/i.test(v.error ?? "")) {
1027
- await new Promise((r) => setTimeout(r, 2e3));
1028
- v = await verifyImageUrl(url);
1404
+ }
1405
+ );
1406
+ server2.registerTool(
1407
+ "snowcone_search_designs",
1408
+ {
1409
+ title: "Search the pre-made designs catalog",
1410
+ description: "Search the public catalog of remixable published designs \u2014 hybrid semantic + keyword over each design's AI visual caption, so descriptive queries like 'pink cowgirl boots on the moon' work (e.g. holiday cards, tees, posters; filter curated = true for first-party-curated picks) so an integration never starts from a blank canvas. Filterable facets: tags, occasion, style, productId, minPriceCents, curated. Each result includes the design's product, license, and a ready-to-render mockup_url (a design=<pairingId> reference URL) when you pass your 'shop'. Catalog design renders are FREE \u2014 they don't count against the shop's usage budget. Without 'shop' you get a mockup_url_template containing YOUR_SHOP_ID to substitute. A search with words in it also returns 'drafts': a couple of fresh low-res draft designs made for exactly that search (e.g. 'corgi astronaut phone case'), each already shown on matching products as a ready mockup_url, no shop needed. Show the person those mockups. Drafts are labelled drafts, not finished designs; 'drafts_status' says why when there are none.",
1411
+ inputSchema: {
1412
+ query: z.string().default("").describe("Search text, e.g. 'christmas card'. Empty string lists curated designs."),
1413
+ limit: z.number().int().min(1).max(50).default(10).describe("Max results (1-50)."),
1414
+ offset: z.number().int().min(0).default(0).describe("Pagination offset."),
1415
+ filter: z.string().optional().describe(`Meilisearch filter expression, e.g. "occasion = 'christmas' AND style = 'watercolor'".`),
1416
+ semantic_ratio: z.number().min(0).max(1).default(0.5).describe("Semantic vs keyword blend (0 = keyword-only, 1 = fully semantic). Default 0.5."),
1417
+ shop: z.string().optional().describe("Your public Shop ID \u2014 when set, each result includes a ready-to-render mockup_url."),
1418
+ shop_secret: z.string().optional().describe("Per-shop secret (scsec_\u2026). With 'shop', URLs are L3-signed (server-side only \u2014 never expose it)."),
1419
+ drafts: z.boolean().optional().describe("Also make fresh draft designs for this search (DEFAULT true; first page of a worded, unfiltered search only). Set false for catalog results alone.")
1420
+ },
1421
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1422
+ },
1423
+ async (args) => {
1424
+ try {
1425
+ const wantsDrafts = args.drafts !== false && args.query.trim().length > 0 && args.offset === 0 && !args.filter;
1426
+ const [{ hits, estimatedTotalHits }, drafted] = await Promise.all([
1427
+ searchDesigns(args.query, args.limit, args.offset, args.filter, args.semantic_ratio),
1428
+ wantsDrafts ? searchDrafts(args.query.trim(), ctx.forwardedFor) : Promise.resolve(null)
1429
+ ]);
1430
+ const items = await Promise.all(hits.map((h) => summarizeDesign(h, args.shop, args.shop_secret)));
1431
+ const out = {
1432
+ total: estimatedTotalHits,
1433
+ count: items.length,
1434
+ offset: args.offset,
1435
+ items,
1436
+ has_more: estimatedTotalHits > args.offset + items.length,
1437
+ ...drafted ? { drafts: drafted.drafts, drafts_status: drafted.status, drafts_detail: drafted.detail } : {}
1438
+ };
1439
+ const catalog = { total: out.total, count: out.count, offset: out.offset, items, has_more: out.has_more };
1440
+ let text = JSON.stringify(catalog, null, 2);
1441
+ if (text.length > CHARACTER_LIMIT) {
1442
+ text = JSON.stringify({ ...catalog, items: items.slice(0, 5), truncated: true }, null, 2);
1443
+ }
1444
+ const draftLines = drafted ? draftsText(args.query.trim(), drafted) : "";
1445
+ if (draftLines) text = `${draftLines}
1446
+
1447
+ Catalog designs for this search:
1448
+ ${text}`;
1449
+ return { content: [{ type: "text", text }], structuredContent: out };
1450
+ } catch (err) {
1451
+ return fail(formatError(err));
1029
1452
  }
1030
- if (!v.ok) {
1031
- const hint = renderFixHint(v.error);
1032
- const reason = (v.error ?? "render failed").replace(/\.*$/, "");
1033
- return fail(`Built ${url} but it does NOT render: ${reason}.${hint ? " " + hint : ""}`);
1453
+ }
1454
+ );
1455
+ server2.registerTool(
1456
+ "snowcone_get_product",
1457
+ {
1458
+ title: "Get a product",
1459
+ description: "Fetch one product by its code (id) or slug. Returns placements (where art goes), mockups (scene ids for the 'view' param), and variant options \u2014 everything you need to build a render URL. Returns an error if the code doesn't exist (it would render blank).",
1460
+ inputSchema: {
1461
+ // eng/0049 F1 (growth/0013 cold-agent run): every sibling tool takes
1462
+ // `product`, and the prose says "product code" — the one tool that
1463
+ // spelled it `id_or_slug` cost every cold agent a guaranteed failed
1464
+ // round-trip. `product` is the canonical name; `id_or_slug` stays as a
1465
+ // silent alias so agents that learned the old name keep working.
1466
+ product: z.string().min(1).optional().describe("Product code (the catalog document id) or slug, e.g. 'BC43BE'. Same name as every other tool."),
1467
+ id_or_slug: z.string().min(1).optional().describe("Deprecated alias of 'product' \u2014 accepted for back-compat; prefer 'product'.")
1468
+ },
1469
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1470
+ },
1471
+ async (args) => {
1472
+ try {
1473
+ const code = args.product ?? args.id_or_slug;
1474
+ if (!code) {
1475
+ return fail(
1476
+ "E_MISSING_PRODUCT: pass product (the product code or slug, e.g. { product: 'BC43BE' }) \u2014 the same 'product' argument snowcone_render_mockup and snowcone_buy_url take."
1477
+ );
1478
+ }
1479
+ const p = await getProduct(code);
1480
+ if (!p) return fail(`Error: no product found for '${code}'. It would render blank \u2014 pick one from snowcone_search_catalog.`);
1481
+ return ok(summarizeProduct(p));
1482
+ } catch (err) {
1483
+ return fail(formatError(err));
1034
1484
  }
1035
- const designKeys = args.design ? Object.keys(args.design) : [];
1036
- const verifiedView = args.view ? `view '${args.view}'` : "the default view";
1037
- const scopeNote = designKeys.length > 1 ? `verify confirmed ${verifiedView} only \u2014 placements not visible in it (design keys: ${designKeys.join(", ")}) are built into the URL but NOT independently confirmed. Render each placement's own view to confirm it.` : void 0;
1038
- return ok(
1039
- {
1040
- url,
1041
- img_html,
1042
- verified: true,
1043
- kind: v.kind,
1044
- bytes: v.bytes,
1045
- ...scopeNote ? { verified_scope: scopeNote } : {}
1046
- },
1047
- `\u2713 verified \u2014 renders ${v.kind} (${v.bytes} bytes): ${url}${scopeNote ? `
1048
- \u26A0\uFE0F ${scopeNote}` : ""}`
1049
- );
1050
- } catch (err) {
1051
- return fail(formatError(err));
1052
1485
  }
1053
- }
1054
- );
1055
- server.registerTool(
1056
- "snowcone_buy_url",
1057
- {
1058
- title: "Build a checkout URL",
1059
- description: "Give the user a link to buy the printed product they just previewed \u2014 it's printed and shipped to them. Build the buyable checkout url for the same product + artwork + shop you'd render. Same inputs as snowcone_render_mockup. Send a customer here to purchase the printed item. Sales route to Snowcone until your human claims the shop. By DEFAULT the server follows the URL and confirms it resolves to a live checkout (the Stripe session actually builds) AND that the matching mockup image renders \u2014 so a bad product code, shop, option combo, or unusable asset comes back as a clear error instead of a confident-but-broken link. 'verified' means the same thing here as in snowcone_render_mockup. This does NOT charge anything; it only builds the session. Pass verify=false to skip the check and get the URL string instantly.",
1060
- inputSchema: {
1061
- ...urlShape,
1062
- verify: z.boolean().optional().describe(
1063
- "Follow the built URL and confirm it resolves to a live checkout, and fetch the matching mockup to confirm the product image renders, before reporting success (DEFAULT true). Set false to skip the network round-trip and return the URL string unchecked."
1064
- )
1486
+ );
1487
+ server2.registerTool(
1488
+ "snowcone_render_mockup",
1489
+ {
1490
+ title: "Render a mockup URL",
1491
+ description: "Show the user their photo, design or text on a real product (t-shirt, mug, hoodie, tote, poster\u2026) as a photoreal preview image. Build a public mockup IMAGE url for a product + your artwork + your shop. The result is an <img>-ready URL \u2014 no API call, no upload. Provide 'asset' (one image) OR 'design' (per-placement map). The asset must be a publicly-fetchable raster image (PNG/JPEG/WebP/AVIF; not SVG), and the product code must exist in the catalog. Pass shop_secret to get an L3-signed URL. By DEFAULT the server fetches the built URL and confirms it actually renders, so a bad product code, wrong placement key, or unusable asset comes back as a clear error instead of a confident-but-broken URL. Pass verify=false to skip that check and just get the URL string instantly. In ChatGPT, Claude and other MCP Apps hosts the result shows as a card: the mockup, name, price, option choices and Buy. The result's 'orders' says whether Snowcone is taking orders yet; when it is 'not-open', show the mockup but don't offer the buy link as a way to order.",
1492
+ _meta: CARD_TOOL_META,
1493
+ inputSchema: {
1494
+ ...urlShape,
1495
+ verify: z.boolean().optional().describe(
1496
+ "Fetch the built URL and confirm it returns a real image before reporting success (DEFAULT true). Turns silent failures into a clear, actionable error and retries once on a not-yet-propagated shop. Set false to skip the network round-trip and return the URL string unchecked."
1497
+ )
1498
+ },
1499
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1065
1500
  },
1066
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1067
- },
1068
- async (args) => {
1069
- try {
1070
- const url = await buyUrl(toUrlInput(args));
1071
- if (args.verify === false) {
1501
+ async (args) => {
1502
+ try {
1503
+ const url = await renderUrl(toUrlInput(args));
1504
+ const img_html = `<img src="${url}" style="object-fit:cover" alt="mockup" />`;
1505
+ if (args.verify === false) {
1506
+ const orders2 = await readOrdersState();
1507
+ const card2 = await buildCard(args, url, orders2, null);
1508
+ return ok(
1509
+ {
1510
+ url,
1511
+ img_html,
1512
+ buy_url: card2.buy_url,
1513
+ orders: orders2,
1514
+ card: card2,
1515
+ notes: "Unverified (verify=false). Display with object-fit:cover and request ~2\xD7 the displayed size. The asset URL must be a publicly-fetchable raster image."
1516
+ },
1517
+ `${url}
1518
+ ${ordersLine(orders2)}`
1519
+ );
1520
+ }
1521
+ const productP = getProduct(args.product).catch(() => null);
1522
+ const ordersP = readOrdersState();
1523
+ let v = await verifyImageUrl(url);
1524
+ if (!v.ok && /unknown shop/i.test(v.error ?? "")) {
1525
+ await new Promise((r) => setTimeout(r, 2e3));
1526
+ v = await verifyImageUrl(url);
1527
+ }
1528
+ if (!v.ok) {
1529
+ const hint = renderFixHint(v.error);
1530
+ const reason = (v.error ?? "render failed").replace(/\.*$/, "");
1531
+ return fail(`Built ${url} but it does NOT render: ${reason}.${hint ? " " + hint : ""}`);
1532
+ }
1533
+ const designKeys = args.design ? Object.keys(args.design) : [];
1534
+ const verifiedView = args.view ? `view '${args.view}'` : "the default view";
1535
+ const scopeNote = designKeys.length > 1 ? `verify confirmed ${verifiedView} only \u2014 placements not visible in it (design keys: ${designKeys.join(", ")}) are built into the URL but NOT independently confirmed. Render each placement's own view to confirm it.` : void 0;
1536
+ const [product, orders] = await Promise.all([productP, ordersP]);
1537
+ const card = await buildCard(args, url, orders, product);
1072
1538
  return ok(
1073
- { url, notes: "Unverified (verify=false). Send a customer here to purchase the printed item." },
1074
- url
1539
+ {
1540
+ url,
1541
+ img_html,
1542
+ verified: true,
1543
+ kind: v.kind,
1544
+ bytes: v.bytes,
1545
+ ...scopeNote ? { verified_scope: scopeNote } : {},
1546
+ buy_url: card.buy_url,
1547
+ orders,
1548
+ card
1549
+ },
1550
+ `\u2713 verified \u2014 renders ${v.kind} (${v.bytes} bytes): ${url}${scopeNote ? `
1551
+ \u26A0\uFE0F ${scopeNote}` : ""}
1552
+ ${ordersLine(orders)}`
1075
1553
  );
1554
+ } catch (err) {
1555
+ return fail(formatError(err));
1076
1556
  }
1077
- const [v, img] = await Promise.all([verifyCheckoutUrl(url), verifyImageUrl(await renderUrl(toUrlInput(args)))]);
1078
- if (!v.ok) {
1079
- const reason = (v.error ?? "checkout failed").replace(/\.*$/, "");
1080
- return fail(`Built ${url} but it does NOT resolve to a live checkout: ${reason}.`);
1081
- }
1082
- if (!img.ok) {
1083
- const hint = renderFixHint(img.error);
1084
- const reason = (img.error ?? "render failed").replace(/\.*$/, "");
1085
- return fail(
1086
- `Built ${url} \u2014 the checkout is live, but the product image for these inputs does NOT render, so a customer would buy a broken mockup: ${reason}.${hint ? " " + hint : ""} Fix the inputs (same as snowcone_render_mockup) and call again.`
1557
+ }
1558
+ );
1559
+ server2.registerTool(
1560
+ "snowcone_buy_url",
1561
+ {
1562
+ title: "Build a checkout URL",
1563
+ description: "Give the user a link to buy the printed product they just previewed \u2014 it's printed and shipped to them. Build the buyable checkout url for the same product + artwork + shop you'd render. Same inputs as snowcone_render_mockup. Send a customer here to purchase the printed item. Sales route to Snowcone until your human claims the shop. By DEFAULT the server follows the URL and confirms it resolves to a live checkout (the Stripe session actually builds) AND that the matching mockup image renders \u2014 so a bad product code, shop, option combo, or unusable asset comes back as a clear error instead of a confident-but-broken link. 'verified' means the same thing here as in snowcone_render_mockup. This does NOT charge anything; it only builds the session. Pass verify=false to skip the check and get the URL string instantly. The result's 'orders' says whether Snowcone is taking orders yet: while it is 'not-open', don't offer this link to the person as a way to order.",
1564
+ inputSchema: {
1565
+ ...urlShape,
1566
+ verify: z.boolean().optional().describe(
1567
+ "Follow the built URL and confirm it resolves to a live checkout, and fetch the matching mockup to confirm the product image renders, before reporting success (DEFAULT true). Set false to skip the network round-trip and return the URL string unchecked."
1568
+ )
1569
+ },
1570
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1571
+ },
1572
+ async (args) => {
1573
+ try {
1574
+ const url = await buyUrl(toUrlInput(args));
1575
+ const ordersP = readOrdersState();
1576
+ if (args.verify === false) {
1577
+ const orders2 = await ordersP;
1578
+ return ok(
1579
+ { url, orders: orders2, notes: "Unverified (verify=false). Send a customer here to purchase the printed item." },
1580
+ `${url}
1581
+ ${ordersLine(orders2)}`
1582
+ );
1583
+ }
1584
+ const [v, img] = await Promise.all([verifyCheckoutUrl(url), verifyImageUrl(await renderUrl(toUrlInput(args)))]);
1585
+ if (!v.ok) {
1586
+ const reason = (v.error ?? "checkout failed").replace(/\.*$/, "");
1587
+ return fail(`Built ${url} but it does NOT resolve to a live checkout: ${reason}.`);
1588
+ }
1589
+ if (!img.ok) {
1590
+ const hint = renderFixHint(img.error);
1591
+ const reason = (img.error ?? "render failed").replace(/\.*$/, "");
1592
+ return fail(
1593
+ `Built ${url} \u2014 the checkout is live, but the product image for these inputs does NOT render, so a customer would buy a broken mockup: ${reason}.${hint ? " " + hint : ""} Fix the inputs (same as snowcone_render_mockup) and call again.`
1594
+ );
1595
+ }
1596
+ const orders = await ordersP;
1597
+ return ok(
1598
+ { url, verified: true, checkout_url: v.checkout_url, render_verified: true, render_kind: img.kind, orders },
1599
+ `\u2713 verified \u2014 resolves to a live checkout AND the product image renders (${img.kind}): ${url}
1600
+ ${ordersLine(orders)}`
1087
1601
  );
1602
+ } catch (err) {
1603
+ return fail(formatError(err));
1088
1604
  }
1089
- return ok(
1090
- { url, verified: true, checkout_url: v.checkout_url, render_verified: true, render_kind: img.kind },
1091
- `\u2713 verified \u2014 resolves to a live checkout AND the product image renders (${img.kind}): ${url}`
1092
- );
1093
- } catch (err) {
1094
- return fail(formatError(err));
1095
1605
  }
1096
- }
1097
- );
1098
- server.registerTool(
1099
- "snowcone_get_quote",
1100
- {
1101
- title: "Get the price, shipping and delivery",
1102
- description: "Tell the user what a printed product costs and when it would arrive, before they buy. Returns the price the buy link will charge (before tax), and each shipping option with its cost and delivery estimate for where it's going. Takes the same product and options as snowcone_buy_url; no artwork or shop needed. Nothing is created or charged. Only promise what comes back: an option with no estimated_delivery means we have no date for it yet.",
1103
- inputSchema: {
1104
- product: z.string().min(1).describe("Product code (the catalog document id), e.g. 'BC43BE'."),
1105
- options: z.record(z.string()).optional().describe("Variant option picks: attribute \u2192 choice, e.g. { size: 'M', color: 'black' }. The price depends on these."),
1106
- quantity: z.number().int().min(1).max(100).optional().describe("How many (1 to 100). Default 1."),
1107
- ship_to: z.string().length(2).optional().describe("2-letter destination country, e.g. 'US'. Default US. A country we can't ship to returns an error listing the ones we can.")
1606
+ );
1607
+ server2.registerTool(
1608
+ "snowcone_get_quote",
1609
+ {
1610
+ title: "Get the price, shipping and delivery",
1611
+ description: "Tell the user what a printed product costs and when it would arrive, before they buy. Returns the price the buy link will charge (before tax), and each shipping option with its cost and delivery estimate for where it's going. Takes the same product and options as snowcone_buy_url; no artwork or shop needed. Nothing is created or charged. Only promise what comes back: an option with no estimated_delivery means we have no date for it yet.",
1612
+ inputSchema: {
1613
+ product: z.string().min(1).describe("Product code (the catalog document id), e.g. 'BC43BE'."),
1614
+ options: z.record(z.string()).optional().describe("Variant option picks: attribute \u2192 choice, e.g. { size: 'M', color: 'black' }. The price depends on these."),
1615
+ quantity: z.number().int().min(1).max(100).optional().describe("How many (1 to 100). Default 1."),
1616
+ ship_to: z.string().length(2).optional().describe("2-letter destination country, e.g. 'US'. Default US. A country we can't ship to returns an error listing the ones we can.")
1617
+ },
1618
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1108
1619
  },
1109
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1110
- },
1111
- async (args) => {
1112
- try {
1113
- const q = await getQuote({
1114
- product: args.product,
1115
- ...args.options ? { options: args.options } : {},
1116
- ...args.quantity !== void 0 ? { quantity: args.quantity } : {},
1117
- ...args.ship_to !== void 0 ? { shipTo: args.ship_to } : {}
1118
- });
1119
- return ok(
1120
- {
1121
- product: q.product,
1122
- variant_id: q.variantId,
1123
- variant_label: q.variantLabel,
1124
- quantity: q.quantity,
1125
- currency: q.currency,
1126
- unit_price_cents: q.unitPriceCents,
1127
- items_total_cents: q.itemsTotalCents,
1128
- tax_included: q.taxIncluded,
1129
- ship_to: q.shipTo,
1130
- shipping: q.shipping.map((s) => ({
1131
- speed: s.speed,
1132
- price_cents: s.priceCents,
1133
- ...s.minTransitDays !== void 0 ? { min_transit_days: s.minTransitDays } : {},
1134
- ...s.maxTransitDays !== void 0 ? { max_transit_days: s.maxTransitDays } : {},
1135
- ...s.estimatedDelivery ? { estimated_delivery: s.estimatedDelivery } : {}
1136
- })),
1137
- quoted_at: q.quotedAt
1138
- },
1139
- quoteText(q)
1140
- );
1141
- } catch (err) {
1142
- return fail(formatError(err));
1620
+ async (args) => {
1621
+ try {
1622
+ const q = await getQuote({
1623
+ product: args.product,
1624
+ ...args.options ? { options: args.options } : {},
1625
+ ...args.quantity !== void 0 ? { quantity: args.quantity } : {},
1626
+ ...args.ship_to !== void 0 ? { shipTo: args.ship_to } : {}
1627
+ });
1628
+ return ok(
1629
+ {
1630
+ product: q.product,
1631
+ variant_id: q.variantId,
1632
+ variant_label: q.variantLabel,
1633
+ quantity: q.quantity,
1634
+ currency: q.currency,
1635
+ unit_price_cents: q.unitPriceCents,
1636
+ items_total_cents: q.itemsTotalCents,
1637
+ tax_included: q.taxIncluded,
1638
+ ship_to: q.shipTo,
1639
+ shipping: q.shipping.map((s) => ({
1640
+ speed: s.speed,
1641
+ price_cents: s.priceCents,
1642
+ ...s.minTransitDays !== void 0 ? { min_transit_days: s.minTransitDays } : {},
1643
+ ...s.maxTransitDays !== void 0 ? { max_transit_days: s.maxTransitDays } : {},
1644
+ ...s.estimatedDelivery ? { estimated_delivery: s.estimatedDelivery } : {}
1645
+ })),
1646
+ quoted_at: q.quotedAt
1647
+ },
1648
+ quoteText(q)
1649
+ );
1650
+ } catch (err) {
1651
+ return fail(formatError(err));
1652
+ }
1143
1653
  }
1144
- }
1145
- );
1146
- server.registerTool(
1147
- "snowcone_get_order_status",
1148
- {
1149
- title: "Find out where an order is",
1150
- description: "Tell the user where their order is: whether it's being made or on its way, the carrier and tracking number, and the latest scan. Ask them for the order number and the email from their order confirmation. Read-only. If nothing matches, the error doesn't say which of the two was wrong, and repeated tries are limited, so check both with the person before retrying.",
1151
- inputSchema: {
1152
- order_number: z.string().min(1).describe("The order number from the confirmation email, e.g. '8532-5134'."),
1153
- email: z.string().min(3).describe("The email the order was placed with.")
1654
+ );
1655
+ server2.registerTool(
1656
+ "snowcone_get_order_status",
1657
+ {
1658
+ title: "Find out where an order is",
1659
+ description: "Tell the user where their order is: whether it's being made or on its way, the carrier and tracking number, and the latest scan. Ask them for the order number and the email from their order confirmation. Read-only. If nothing matches, the error doesn't say which of the two was wrong, and repeated tries are limited, so check both with the person before retrying.",
1660
+ inputSchema: {
1661
+ order_number: z.string().min(1).describe("The order number from the confirmation email, e.g. '8532-5134'."),
1662
+ email: z.string().min(3).describe("The email the order was placed with.")
1663
+ },
1664
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1154
1665
  },
1155
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
1156
- },
1157
- async (args) => {
1158
- try {
1159
- const r = await getOrderStatus({ orderNumber: args.order_number, email: args.email });
1160
- return ok(
1161
- {
1162
- order_number: r.order.order.number,
1163
- placed_at: r.order.order.placedAt,
1164
- status: r.order.status,
1165
- headline: r.order.headline,
1166
- stages: r.order.stages,
1167
- packages: r.order.packages,
1168
- events: r.order.events,
1169
- items: r.order.items,
1170
- status_url: r.statusUrl
1171
- },
1172
- orderStatusText(r)
1173
- );
1174
- } catch (err) {
1175
- return fail(formatError(err));
1666
+ async (args) => {
1667
+ try {
1668
+ const r = await getOrderStatus({ orderNumber: args.order_number, email: args.email });
1669
+ return ok(
1670
+ {
1671
+ order_number: r.order.order.number,
1672
+ placed_at: r.order.order.placedAt,
1673
+ status: r.order.status,
1674
+ headline: r.order.headline,
1675
+ stages: r.order.stages,
1676
+ packages: r.order.packages,
1677
+ events: r.order.events,
1678
+ items: r.order.items,
1679
+ status_url: r.statusUrl
1680
+ },
1681
+ orderStatusText(r)
1682
+ );
1683
+ } catch (err) {
1684
+ return fail(formatError(err));
1685
+ }
1176
1686
  }
1177
- }
1178
- );
1687
+ );
1688
+ }
1689
+ var server = createServer();
1179
1690
 
1180
1691
  // src/index.ts
1181
1692
  async function main() {