z-zero-mcp-server 1.2.3 → 1.3.2

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.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
- // OpenClaw MCP Server (z-zero-mcp-server) v1.1.0
3
+ // Z-Zero MCP Server (z-zero-mcp-server) — version from package.json (see CURRENT_MCP_VERSION)
4
4
  // Exposes secure JIT payment tools to AI Agents via Model Context Protocol
5
- // Status: Connected to Z-ZERO Gateway — produces secure JIT virtual cards
5
+ // Status: Connected to Z-ZERO Gateway — JIT virtual cards + gasless USDC on Base
6
6
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
7
  if (k2 === undefined) k2 = k;
8
8
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -63,6 +63,15 @@ const web3_detector_js_1 = require("./lib/web3-detector.js");
63
63
  const extract_total_price_js_1 = require("./lib/extract-total-price.js");
64
64
  const playwright_1 = require("playwright");
65
65
  const key_store_js_1 = require("./lib/key-store.js"); // ✅ Hot-Swap support
66
+ const url_guard_js_1 = require("./lib/url-guard.js");
67
+ /** Masked, non-reconstructable hint for a secret key (for debug output only). */
68
+ function maskKey(key) {
69
+ if (!key)
70
+ return "";
71
+ if (key.length <= 8)
72
+ return "••••";
73
+ return `${key.slice(0, 4)}…${key.slice(-2)}`;
74
+ }
66
75
  // ============================================================
67
76
  // CREATE MCP SERVER
68
77
  // ============================================================
@@ -155,7 +164,7 @@ server.tool("check_balance", "Check spendable USD balance for a card alias. For
155
164
  // ============================================================
156
165
  // TOOL 2.5: Get deposit addresses (Phase 14 feature)
157
166
  // ============================================================
158
- server.tool("get_deposit_addresses", "Get crypto deposit addresses (EVM + Tron) to top up wallet balance.", {}, async () => {
167
+ server.tool("get_deposit_addresses", "Get your Base deposit address to top up your wallet with USDC (or any supported stablecoin on Base).", {}, async () => {
159
168
  const data = await getDepositAddressesRemote();
160
169
  if (data?.error === "AUTH_REQUIRED") {
161
170
  return {
@@ -168,32 +177,30 @@ server.tool("get_deposit_addresses", "Get crypto deposit addresses (EVM + Tron)
168
177
  isError: true
169
178
  };
170
179
  }
171
- // ── WDK Non-Custodial Mode ────────────────────────────────────────────
180
+ // ── Base smart-account wallet ─────────────────────────────────────────
172
181
  if (data?.wdk_wallet?.address) {
173
- const wdkAddr = data.wdk_wallet.address;
182
+ const walletAddr = data.wdk_wallet.address;
174
183
  const balance = data.wdk_wallet.balance_usdt ?? 0;
175
- const tronAddr = data.wdk_wallet.tron_address;
176
184
  return {
177
185
  content: [{
178
186
  type: "text",
179
187
  text: JSON.stringify({
180
- wallet_type: "non-custodial (WDK)",
181
- balance_usdt: balance,
188
+ wallet_type: "Base smart account",
189
+ balance_usdc: balance,
182
190
  supported_chains: [
183
- { chain: "Ethereum", token: "USDT", address: wdkAddr },
184
- ...(tronAddr ? [{ chain: "Tron", token: "USDT", address: tronAddr }] : []),
191
+ { chain: "Base", token: "USDC", address: walletAddr },
185
192
  ],
186
- instructions: `Send USDT (Ethereum ERC-20) to: ${wdkAddr}${tronAddr ? `\nSend USDT (Tron TRC-20) to: ${tronAddr}` : ''}`,
187
- note: "Gasless payments via ERC-4337 Paymaster (Ethereum) / GasFree (Tron)."
193
+ instructions: `Send USDC (or any supported stablecoin) on Base to: ${walletAddr}`,
194
+ note: "Gasless spending via the Coinbase Paymaster on Base."
188
195
  }, null, 2),
189
196
  }],
190
197
  };
191
198
  }
192
- // No WDK wallet connected
199
+ // No Base wallet connected
193
200
  return {
194
201
  content: [{
195
202
  type: "text",
196
- text: "No WDK wallet found. Please create one at https://www.clawcard.store/dashboard/agent-wallet",
203
+ text: "No Base wallet found. Please create one at https://www.clawcard.store/dashboard/agent-wallet",
197
204
  }],
198
205
  isError: true,
199
206
  };
@@ -201,7 +208,7 @@ server.tool("get_deposit_addresses", "Get crypto deposit addresses (EVM + Tron)
201
208
  // ============================================================
202
209
  // TOOL 3: Request a temporary payment token (issues secure JIT card)
203
210
  // ============================================================
204
- server.tool("request_payment_token", "⚠️ MANDATORY: Read mcp://resources/sop first. Collect shipping info and check get_merchant_hints before calling. Request a JIT virtual card ($1-$100).", {
211
+ server.tool("request_payment_token", "Request a single-use JIT virtual card ($1–$100) locked to one amount + merchant. ⚠️ Read mcp://resources/sop first. Only call once the FINAL total is visible — for physical goods that is AFTER shipping is submitted (use get_merchant_hints to navigate there). For digital goods with the price already visible, prefer auto_pay_checkout instead.", {
205
212
  card_alias: zod_1.z
206
213
  .string()
207
214
  .describe("Which card to charge, e.g. 'Card_01'"),
@@ -279,7 +286,7 @@ server.tool("get_merchant_hints", "Get merchant navigation flow for a domain or
279
286
  .string()
280
287
  .describe("The main domain of the checkout page, e.g. 'amazon.com' or 'shopify.com'. Strip 'www.' prefix."),
281
288
  }, async ({ domain }) => {
282
- const ZZERO_API = process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
289
+ const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
283
290
  const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
284
291
  try {
285
292
  const resp = await fetch(`${ZZERO_API}/api/checkout-hints?domain=${encodeURIComponent(domain)}&fields=merchant`, {
@@ -306,7 +313,7 @@ server.tool("get_merchant_hints", "Get merchant navigation flow for a domain or
306
313
  // ============================================================
307
314
  // TOOL 4b: Execute payment (The "Invisible Hand")
308
315
  // ============================================================
309
- server.tool("execute_payment", "Execute a payment using a temporary token. This tool will securely fill the checkout form on the target website. You will NEVER see the real card number - it is handled securely in the background.", {
316
+ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero opens a headless browser, injects the card (you NEVER see the PAN), clicks Pay, then watches for a REAL confirmation before reporting success. Returns a `status`: `confirmed` (order placed → token burned, receipt_id may hold a real order #), `declined` (merchant rejected → token kept for refund), `unconfirmed` (submitted but no confirmation seen → do NOT retry blindly, verify first), `not_submitted` (no Pay button → supply a submit_selector hint), or `no_fields`. ALWAYS pass actual_amount so overcharges are blocked and underspend refunded.", {
310
317
  token: zod_1.z
311
318
  .string()
312
319
  .describe("The temporary payment token from request_payment_token"),
@@ -317,7 +324,7 @@ server.tool("execute_payment", "Execute a payment using a temporary token. This
317
324
  actual_amount: zod_1.z
318
325
  .number()
319
326
  .optional()
320
- .describe("The actual final amount on the checkout page. If different from token amount, system will auto-refund the difference."),
327
+ .describe("STRONGLY RECOMMENDED. The final total shown on the checkout page (incl. shipping + tax). Enables the overcharge block and the underspend refund — omit only if it is genuinely unreadable."),
321
328
  hints: zod_1.z
322
329
  .object({
323
330
  pre_steps: zod_1.z.array(zod_1.z.string()).optional(),
@@ -332,6 +339,23 @@ server.tool("execute_payment", "Execute a payment using a temporary token. This
332
339
  .optional()
333
340
  .describe("Optional hints from get_merchant_hints — selectors and pre-steps to guide Playwright. Use when default selectors fail or for complex multi-step checkouts."),
334
341
  }, async ({ token, checkout_url, actual_amount, hints }) => {
342
+ // Step 0: SSRF / scheme guard BEFORE we drive a browser to this URL and inject a real PAN/CVV.
343
+ try {
344
+ (0, url_guard_js_1.assertSafeCheckoutUrl)(checkout_url);
345
+ }
346
+ catch (e) {
347
+ return {
348
+ content: [{
349
+ type: "text",
350
+ text: JSON.stringify({
351
+ success: false,
352
+ status: "blocked",
353
+ message: `🚨 Refused to open checkout_url: ${e instanceof Error ? e.message : String(e)}`,
354
+ }, null, 2),
355
+ }],
356
+ isError: true,
357
+ };
358
+ }
335
359
  // Step 1: Resolve token → card data (RAM only)
336
360
  const cardData = await resolveTokenRemote(token);
337
361
  if (cardData?.error === "AUTH_REQUIRED") {
@@ -383,31 +407,35 @@ server.tool("execute_payment", "Execute a payment using a temporary token. This
383
407
  }
384
408
  // Step 2: Use Playwright to inject card into checkout form (with optional agent hints)
385
409
  const result = await (0, playwright_bridge_js_1.fillCheckoutForm)(checkout_url, cardData, undefined, hints);
386
- // Step 3: Burn the token ONLY if payment succeeded
387
- // If merchant declines → keep token ACTIVE so webhook decline flow can refund correctly
388
- if (result.success) {
389
- await burnTokenRemote(token);
390
- }
391
- else {
392
- // Payment failed — do NOT burn token
393
- // Partner card issuer will fire a 'card.authorization.declined' webhook → refund handled there
410
+ // Step 3: Burn the token ONLY on a CONFIRMED payment (result.success === status 'confirmed').
411
+ // Every other outcome (declined / unconfirmed / not_submitted / no_fields / error) leaves the
412
+ // token UNBURNED so the funds stay recoverable. "Filled a field" is NOT a payment.
413
+ if (!result.success) {
414
+ // `declined` = merchant rejected → webhook refund flow handles it.
415
+ // Everything else = we couldn't prove a charge happened → funds stay locked, recoverable.
416
+ const isDeclined = result.status === 'declined';
394
417
  return {
395
418
  content: [
396
419
  {
397
420
  type: "text",
398
421
  text: JSON.stringify({
399
422
  success: false,
400
- message: result.message || "Payment was declined by merchant.",
423
+ status: result.status,
424
+ message: result.message || "Payment was not confirmed.",
401
425
  token_status: "ACTIVE",
402
- note: "Token NOT burned. Funds will be refunded automatically via webhook within minutes.",
426
+ note: isDeclined
427
+ ? "Token NOT burned. Funds will be refunded automatically via the decline webhook within minutes."
428
+ : "Token NOT burned — no confirmed charge. If you are unsure whether the order went through, do NOT retry blindly (double-charge risk); verify the merchant, or call cancel_payment_token to release the funds.",
403
429
  }, null, 2),
404
430
  },
405
431
  ],
406
432
  isError: true,
407
433
  };
408
434
  }
435
+ // Confirmed — burn the token, passing the REAL receipt id if one was scraped.
436
+ await burnTokenRemote(token, result.receipt_id);
409
437
  // Step 4: Refund underspend if actual amount was less than token amount
410
- if (actual_amount !== undefined && result.success) {
438
+ if (actual_amount !== undefined) {
411
439
  await refundUnderspendRemote(token, actual_amount);
412
440
  }
413
441
  // Step 5: Return result (NEVER includes card numbers)
@@ -416,11 +444,12 @@ server.tool("execute_payment", "Execute a payment using a temporary token. This
416
444
  {
417
445
  type: "text",
418
446
  text: JSON.stringify({
419
- success: result.success,
447
+ success: true,
448
+ status: "confirmed",
420
449
  message: result.message,
421
450
  receipt_id: result.receipt_id || null,
422
451
  token_status: "BURNED",
423
- note: "Token has been permanently invalidated after this transaction.",
452
+ note: "Token has been permanently invalidated after this confirmed transaction.",
424
453
  }, null, 2),
425
454
  },
426
455
  ],
@@ -533,7 +562,7 @@ server.tool("set_api_key", "Activate a new Passport Key instantly, no restart ne
533
562
  };
534
563
  }
535
564
  // Step 2: Validate new key against Dashboard API before swapping
536
- const ZZERO_API = process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
565
+ const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
537
566
  try {
538
567
  const resp = await fetch(`${ZZERO_API}/api/wdk/balance`, {
539
568
  headers: {
@@ -576,7 +605,8 @@ server.tool("set_api_key", "Activate a new Passport Key instantly, no restart ne
576
605
  text: JSON.stringify({
577
606
  status: "SUCCESS",
578
607
  message: `✅ ${result.message}`,
579
- active_key_prefix: trimmed.slice(0, 12) + "...",
608
+ // Masked hint only — never echo a usable portion of the secret to the chat/model context.
609
+ active_key_hint: maskKey(trimmed),
580
610
  note: "All subsequent API calls will use this key. Previous key removed from this session (soft revoke).",
581
611
  }, null, 2),
582
612
  }],
@@ -593,7 +623,7 @@ server.tool("show_api_key_status", "Check if Passport Key is configured. Shows p
593
623
  type: "text",
594
624
  text: JSON.stringify({
595
625
  configured: hasKey,
596
- key_prefix: hasKey ? key.slice(0, 12) + "..." : null,
626
+ key_hint: hasKey ? maskKey(key) : null,
597
627
  note: hasKey
598
628
  ? "Key is active. Call set_api_key to update it."
599
629
  : "No key configured. Call set_api_key with your Passport Key from https://www.clawcard.store/dashboard/agents",
@@ -610,8 +640,14 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
610
640
  .string()
611
641
  .describe("Card alias to charge for JIT Fiat fallback, e.g. 'Card_01'."),
612
642
  }, async ({ checkout_url, card_alias }) => {
613
- const ZZERO_API = process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
643
+ const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
614
644
  const API_KEY = (0, key_store_js_1.getPassportKey)(); // ✅ FIX: use hot-swap key store, not process.env
645
+ // Spend guard for the autonomous path. auto_pay derives the amount itself
646
+ // (scraped fiat total OR on-chain amount from an EIP-681 link / calldata), so there is
647
+ // no human-authorized token to cross-check against — this range IS the only amount guard.
648
+ // It bounds the blast radius if price extraction or a payment link is wrong/malicious.
649
+ const AUTO_PAY_MIN_USD = 1;
650
+ const AUTO_PAY_MAX_USD = 100;
615
651
  if (!API_KEY) {
616
652
  return {
617
653
  content: [{ type: "text", text: JSON.stringify({
@@ -621,31 +657,8 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
621
657
  isError: true,
622
658
  };
623
659
  }
624
- // ── SSRF guard ───────────────────────────────────────────────
625
- (() => {
626
- let url;
627
- try {
628
- url = new URL(checkout_url);
629
- }
630
- catch {
631
- throw new Error(`Invalid checkout_url: ${checkout_url}`);
632
- }
633
- const isDev = process.env.NODE_ENV !== "production";
634
- const hostname = url.hostname;
635
- if (!(isDev && (hostname === "localhost" || hostname === "127.0.0.1"))) {
636
- if (url.protocol !== "https:") {
637
- throw new Error(`checkout_url must use HTTPS.`);
638
- }
639
- const privatePatterns = [
640
- /^localhost$/i, /^127\./, /^10\./,
641
- /^172\.(1[6-9]|2\d|3[01])\./, /^192\.168\./,
642
- /^169\.254\./, /^\[::1\]$/, /^0\.0\.0\.0$/,
643
- ];
644
- if (privatePatterns.some(p => p.test(hostname))) {
645
- throw new Error(`SSRF blocked host: ${hostname}`);
646
- }
647
- }
648
- })();
660
+ // ── SSRF guard (shared helper) ───────────────────────────────
661
+ (0, url_guard_js_1.assertSafeCheckoutUrl)(checkout_url);
649
662
  // ── Single Browser Instance for efficiency ──────────────────
650
663
  const browser = await playwright_1.chromium.launch({ headless: true });
651
664
  const context = await browser.newContext();
@@ -669,9 +682,20 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
669
682
  }, null, 2) }],
670
683
  };
671
684
  }
685
+ // Same spend guard as the fiat route — the on-chain amount comes from an
686
+ // untrusted EIP-681 link / calldata, so cap it before sending USDC.
687
+ if (amount < AUTO_PAY_MIN_USD || amount > AUTO_PAY_MAX_USD) {
688
+ return {
689
+ content: [{ type: "text", text: JSON.stringify({
690
+ route: "WEB3", status: "AMOUNT_OUT_OF_RANGE", recipient: to, detected_amount: amount,
691
+ message: `🚨 BLOCKED: Web3 amount $${amount} is outside the allowed $${AUTO_PAY_MIN_USD}–$${AUTO_PAY_MAX_USD} range. No funds were sent.`,
692
+ }, null, 2) }],
693
+ isError: true,
694
+ };
695
+ }
672
696
  const resp = await fetch(`${ZZERO_API}/api/wdk/transfer`, {
673
697
  method: "POST",
674
- headers: { "Content-Type": "application/json", "x-passport-key": API_KEY },
698
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` },
675
699
  body: JSON.stringify({ to, amount, card_alias }),
676
700
  });
677
701
  const txResult = await resp.json();
@@ -686,9 +710,9 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
686
710
  return {
687
711
  content: [{ type: "text", text: JSON.stringify({
688
712
  route: "WEB3", method: web3Result.method, status: "SUCCESS",
689
- recipient: to, amount_usdt: amount, tx_hash: txResult.txHash,
690
- message: `✅ Web3 payment sent on-chain! ${amount} USDT → ${to}.`,
691
- gas_savings: "~$0.001 (ERC-4337 Paymaster, gasless for user)",
713
+ recipient: to, amount_usdc: amount, tx_hash: txResult.txHash,
714
+ message: `✅ Web3 payment sent on-chain! ${amount} USDC → ${to}.`,
715
+ gas_savings: "~$0.001 (Coinbase Paymaster on Base, gasless for user)",
692
716
  }, null, 2) }],
693
717
  };
694
718
  }
@@ -703,16 +727,28 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
703
727
  isError: true,
704
728
  };
705
729
  }
706
- if (totalPrice < 1 || totalPrice > 100) {
730
+ if (totalPrice < AUTO_PAY_MIN_USD || totalPrice > AUTO_PAY_MAX_USD) {
707
731
  return {
708
732
  content: [{ type: "text", text: JSON.stringify({
709
733
  route: "FIAT", status: "AMOUNT_OUT_OF_RANGE", detected_price: totalPrice,
734
+ message: `Detected total $${totalPrice} is outside the allowed $${AUTO_PAY_MIN_USD}–$${AUTO_PAY_MAX_USD} range.`,
710
735
  }, null, 2) }],
711
736
  isError: true,
712
737
  };
713
738
  }
714
- // Issue Token
715
- const token = await issueTokenRemote(card_alias, totalPrice, checkout_url);
739
+ // FX buffer: over-provision the JIT card limit so a non-USD checkout
740
+ // (FX-converted + fee on our USD card) doesn't drift over the limit and
741
+ // get declined. USD totals are final → tiny rounding buffer only. Any
742
+ // unspent buffer is auto-refunded on-chain when the charge settles.
743
+ const currency = await (0, extract_total_price_js_1.detectCheckoutCurrency)(page);
744
+ const bufferPct = currency === 'NON_USD' ? 0.05 : 0.02;
745
+ let issueAmount = Math.round(totalPrice * (1 + bufferPct) * 100) / 100;
746
+ // Never exceed the per-tx cap; merchant charges <= totalPrice <= cap anyway.
747
+ if (issueAmount > AUTO_PAY_MAX_USD)
748
+ issueAmount = AUTO_PAY_MAX_USD;
749
+ console.error(`[SMART ROUTE] FX buffer: ${currency}, limit $${totalPrice} → $${issueAmount} (+${Math.round(bufferPct * 100)}%)`);
750
+ // Issue Token (card limit = buffered amount)
751
+ const token = await issueTokenRemote(card_alias, issueAmount, checkout_url);
716
752
  if (!token || token.error)
717
753
  throw new Error(token?.message || "Token issue failed");
718
754
  // Resolve Card Data
@@ -721,18 +757,29 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
721
757
  throw new Error("Card resolve failed");
722
758
  // Fill Form (Reusing the same page!)
723
759
  const fillResult = await (0, playwright_bridge_js_1.fillCheckoutForm)(checkout_url, cardData, page);
760
+ // Burn ONLY on a confirmed charge. Any other outcome leaves the JIT token unburned
761
+ // so the locked funds are recoverable (cancel/expire/decline-webhook).
724
762
  if (fillResult.success) {
725
- const burnOk = await burnTokenRemote(token.token);
763
+ const burnOk = await burnTokenRemote(token.token, fillResult.receipt_id);
726
764
  if (!burnOk)
727
765
  console.error(`[WARN] Token burn failed for ${token.token} — manual check needed`);
728
766
  }
767
+ else {
768
+ // Release the freshly-issued JIT token so the price funds don't sit locked on a non-payment.
769
+ await cancelTokenRemote(token.token).catch(() => { });
770
+ }
729
771
  return {
730
772
  content: [{ type: "text", text: JSON.stringify({
731
- route: "FIAT", status: fillResult.success ? "SUCCESS" : "FILL_FAILED",
773
+ route: "FIAT",
774
+ status: fillResult.success ? "SUCCESS" : (fillResult.status || "FILL_FAILED").toUpperCase(),
732
775
  detected_price: totalPrice,
776
+ authorized_amount: issueAmount,
777
+ fx_buffer: issueAmount > totalPrice
778
+ ? `Locked $${issueAmount} = $${totalPrice} + ${Math.round(bufferPct * 100)}% ${currency === 'NON_USD' ? 'FX' : 'rounding'} buffer; unspent buffer auto-refunds after the charge settles.`
779
+ : undefined,
733
780
  message: fillResult.success
734
- ? `✅ JIT card issued for $${totalPrice} and checkout filled.`
735
- : `❌ Fill failed: ${fillResult.message}`,
781
+ ? `✅ Confirmed: JIT card issued (limit $${issueAmount}) and order confirmed by merchant for ~$${totalPrice}.`
782
+ : `❌ Not confirmed (${fillResult.status}): ${fillResult.message} Token released.`,
736
783
  receipt_id: fillResult.receipt_id || null,
737
784
  }, null, 2) }],
738
785
  isError: !fillResult.success,
@@ -771,7 +818,7 @@ server.tool("report_checkout_fail", "Report a checkout URL that you could not co
771
818
  .optional()
772
819
  .describe("Brief description of what went wrong, e.g. 'Could not find card number field' or 'Page redirected to CAPTCHA'."),
773
820
  }, async ({ url, error_type, error_message }) => {
774
- const ZZERO_API = process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
821
+ const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
775
822
  const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
776
823
  try {
777
824
  await fetch(`${ZZERO_API}/api/checkout-hints`, {
@@ -803,93 +850,115 @@ server.resource("Standard Operating Procedure (SOP) for Autonomous Payments", "m
803
850
  description: "A comprehensive guide on how AI agents should use the Z-ZERO tools to execute secure, zero-trust payments."
804
851
  }, async (uri) => {
805
852
  const sopContent = `
806
- # Z-ZERO Autonomous Payment Skill SOP (v2.0.0)
853
+ # Z-ZERO Autonomous Payment SOP (v2.1.0 — matches MCP ≥ 1.3.0)
854
+
855
+ How an AI Agent uses Z-ZERO to buy goods for the user WITHOUT ever handling raw card data.
856
+ Mental model: you only ever hold a one-time **token** + a **URL**. Z-ZERO does the privileged
857
+ card injection in the background. "Filling a form" is NOT "paying" — always read the result \`status\`.
858
+
859
+ ---
860
+
861
+ ## STEP 0 — Route the request (decide FIRST)
862
+
863
+ One question: **is the final price visible now, or only after shipping?**
864
+ - **Digital / SaaS / API / on-chain** (price visible now) → **PATH A** (one call).
865
+ - **Physical goods** (Shopify, Etsy, WooCommerce — price appears only AFTER shipping) → **PATH B**.
807
866
 
808
- This SOP tells the AI Agent how to use Z-ZERO tools to autonomously purchase goods on behalf of the user — without ever handling raw credit card data.
867
+ Always do WALLET & SAFETY first.
809
868
 
810
869
  ---
811
870
 
812
- ## Group 1: Wallet Config (READ FIRST)
871
+ ## WALLET & SAFETY (do first, every time)
813
872
 
814
873
  Tools: \`check_balance\`, \`list_cards\`, \`get_deposit_addresses\`, \`set_api_key\`, \`show_api_key_status\`
815
874
 
816
- Before ANY purchase:
817
- 1. Confirm exactly what the user wants to buy and the expected price (in USD).
818
- 2. Call \`check_balance\` using your default \`card_alias\` to verify sufficient funds.
819
- - If balance is insufficient → STOP. Ask the human to deposit USDT to their wallet.
820
- 3. Use \`list_cards\` to see available card aliases, NOT to check spendable balance.
821
- 4. Never ask for the API key proactively — only call \`set_api_key\` when the user explicitly gives you one.
875
+ 1. Confirm exactly what the user wants and the expected USD price.
876
+ 2. \`check_balance\` on the default \`card_alias\` → if insufficient, STOP and ask the user to deposit
877
+ USDC on Base (\`get_deposit_addresses\`).
878
+ 3. \`list_cards\` = see aliases + active tokens, NOT spendable balance.
879
+ 4. Never ask for the API key proactively; only \`set_api_key\` when the user explicitly hands you one.
822
880
 
823
881
  ---
824
882
 
825
- ## Group 2: Manual 4-Step Payment (Core Flow)
883
+ ## PATH A — Digital goods / SaaS / API (price already visible)
826
884
 
827
- Tools: \`request_payment_token\`, \`execute_payment\`, \`cancel_payment_token\`, \`request_human_approval\`
885
+ Call \`auto_pay_checkout(checkout_url, card_alias)\` — one call:
886
+ - Auto-detects on-chain (sends USDC on Base, gasless via Coinbase Paymaster) vs fiat (issues a JIT
887
+ card + fills the form).
888
+ - Amount is read from the page and capped to $1–$100.
889
+ - Read the returned \`status\` → see **PAYMENT OUTCOMES** below.
828
890
 
829
- Execute in this exact order:
891
+ ---
830
892
 
831
- ### Step 1 — Verify
832
- Confirm item, price, and check balance (see Group 1).
893
+ ## PATH B — Physical goods (price only after shipping)
833
894
 
834
- ### Step 2 — Navigate to Payment Page
835
- Use browser tools to navigate to the final payment page where card fields are visible and the FINAL total (including shipping + tax) is displayed.
836
- - ⛔ DO NOT call \`request_payment_token\` until BOTH conditions are true:
837
- 1. Shipping/personal info submitted successfully
838
- 2. Card input fields are visible on screen
895
+ Tools: \`get_merchant_hints\`, \`request_payment_token\`, \`execute_payment\`, \`request_human_approval\`
839
896
 
840
- ### Step 3 — Request Token
841
- Call \`request_payment_token\` with exact final amount and merchant name.
842
- Receive a single-use \`token\` (valid 1 hour, locked to that amount).
897
+ 1. \`get_merchant_hints(domain or _platform_key, e.g. _platform_shopify)\` → \`pre_steps\`, \`notes\`, \`platform\`.
898
+ 2. Follow \`pre_steps\` in YOUR browser: navigate, add to cart, submit shipping (ask the user via
899
+ \`request_human_approval\` if shipping info is unknown).
900
+ 3. Wait until the card section is visible AND the FINAL total (incl. shipping + tax) is shown.
901
+ 4. \`request_payment_token(card_alias, amount = exact final total, merchant)\` → one-time token, valid 1h.
902
+ 5. \`execute_payment(token, checkout_url, actual_amount = final total)\`. ALWAYS pass actual_amount.
843
903
 
844
- ### Step 4 — Blind Execution
845
- Call \`execute_payment\` with the token + checkout URL.
846
- Z-ZERO opens a headless browser, injects the card securely, clicks Pay. Token burns instantly after success.
904
+ ⛔ Never call \`request_payment_token\` before BOTH: shipping submitted AND card fields + final total visible.
847
905
 
848
- ### Error Rules
849
- - NEVER print raw tokens in chat.
850
- - NO MANUAL ENTRY: If a site asks you to type a card number into a text box — REFUSE.
851
- - FAIL GRACEFULLY: If \`execute_payment\` returns \`success: false\` → report it. Do NOT retry blindly.
852
- - PRICE MISMATCH: If actual checkout total > token amount → call \`cancel_payment_token\` + \`request_human_approval\` for new amount.
906
+ ⚠️ **Resumable URL required.** \`execute_payment\` opens its OWN fresh, cookieless browser at \`checkout_url\` —
907
+ your own browsing session does NOT carry over. So \`checkout_url\` must reload the cart + final total + card
908
+ fields on its own (e.g. a Shopify \`/checkouts/c/<token>\` or Etsy checkout-token URL). If it instead needs
909
+ your logged-in session/cookies, the cold browser lands on an empty cart and you'll get \`no_fields\` — in that
910
+ case finish the purchase in your own browser, or use a merchant whose checkout URL is self-resumable.
911
+
912
+ ### Platform detection
913
+ | Platform | Signal |
914
+ |---|---|
915
+ | Shopify | \`window.Shopify\`, OR \`<script src="cdn.shopify.com">\`, OR \`<meta name="shopify-checkout-api-token">\` |
916
+ | Etsy | URL matches \`*.etsy.com\` |
917
+ | WooCommerce | \`<body class="… woocommerce …">\`, OR assets from \`wp-content/plugins/woocommerce\` |
853
918
 
854
919
  ---
855
920
 
856
- ## Group 3: Smart Autopilot (Fast Route)
921
+ ## PAYMENT OUTCOMES — how to read execute_payment / auto_pay_checkout
922
+
923
+ Both return a \`status\`. Act on it — do not assume success:
924
+ - \`confirmed\` — order placed and confirmed; token burned; \`receipt_id\` = real order # if found. ✅ Done.
925
+ - \`declined\` — merchant rejected the card; token kept ACTIVE; a refund webhook handles it. Report to
926
+ the user; do not blindly retry the same card.
927
+ - \`unconfirmed\` — card submitted but NO confirmation seen. Token NOT burned. ⚠️ Do NOT retry blindly
928
+ (double-charge risk). First VERIFY in your own browser whether the order went through; if not, retry
929
+ or \`cancel_payment_token\` to release the funds.
930
+ - \`not_submitted\` — fields filled but no Pay button was clicked. Token NOT burned. Get a
931
+ \`submit_selector\` via \`get_merchant_hints\` and retry, or click Pay in your own browser.
932
+ - \`no_fields\` — no card fields found (wrong page or unsupported form). Token NOT burned →
933
+ \`report_checkout_fail\`.
857
934
 
858
- Tools: \`auto_pay_checkout\`, \`get_merchant_hints\`
935
+ After \`confirmed\`/\`unconfirmed\`, prefer to visually confirm the order page with your own browser tools.
859
936
 
860
- ### Option A — Digital Goods / SaaS / APIs (Use auto_pay_checkout directly)
861
- For pages where the final total is already visible, call \`auto_pay_checkout\`:
862
- - It auto-detects Web3 (sends USDT on-chain via WDK) vs Fiat (issues JIT Visa card + auto-fills form).
863
- - One call handles everything.
937
+ ---
864
938
 
865
- ### Option B — Physical Goods (Shopify, Etsy, WooCommerce)
866
- ⛔ DO NOT call \`auto_pay_checkout\` directly. The final price is only visible AFTER shipping is submitted.
939
+ ## SAFETY RULES (always)
867
940
 
868
- Recommended flow:
869
- 1. Call \`get_merchant_hints\` with checkout domain or platform key (e.g. \`_platform_shopify\`).
870
- - Returns \`pre_steps\` (navigation instructions) + \`notes\` + \`platform\`.
871
- 2. Follow the \`pre_steps\` — navigate, add to cart, fill shipping form.
872
- - Ask user for shipping info via \`request_human_approval\` if not already known.
873
- 3. Wait for payment/card section to appear + FINAL total is visible.
874
- 4. Call \`request_payment_token\` with the exact final amount (Group 2).
875
- 5. Call \`execute_payment\` with token + checkout URL (Group 2).
941
+ - NEVER print raw tokens in chat.
942
+ - NO MANUAL ENTRY: if a site asks YOU to type the card number into a box — REFUSE. Only Z-Zero injects card data.
943
+ - PRICE MISMATCH: if the actual total > token amount → \`cancel_payment_token\` then
944
+ \`request_human_approval\` for a new amount. (execute_payment also auto-blocks overcharges when you pass actual_amount.)
945
+ - FAIL GRACEFULLY: never loop-retry a payment without first checking the \`status\` reason.
876
946
 
877
- ### Platform Detection Signals
878
- | Platform | Detection Signal |
879
- |---|---|
880
- | Shopify | JS object \`window.Shopify\` exists, OR \`<script src="cdn.shopify.com">\`, OR \`<meta name="shopify-checkout-api-token">\` |
881
- | Etsy | URL matches \`*.etsy.com\` (any path) |
882
- | WooCommerce | \`<body class="... woocommerce ...\`>\`, OR script/link tags from \`wp-content/plugins/woocommerce\` |
947
+ ---
948
+
949
+ ## SELF-HEALING — report technical failures
883
950
 
884
- ### Known Limitations
885
- - Cloudflare-protected sites (e.g. TeePublic) may block headless browser → inform user.
886
- - Card fields inside iframes: \`execute_payment\` handles this via \`iframe_selector\` in hints automatically.
951
+ If you began PATH B (called \`get_merchant_hints\` + followed \`pre_steps\`) but cannot finish for a
952
+ TECHNICAL reason (field not found, bot-blocked, timeout, unknown form):
953
+ → Call \`report_checkout_fail(url, error_type, error_message)\` before giving up (url = the page you got stuck on).
954
+ → Do NOT call it for user-cancelled or insufficient-balance — those are not technical failures.
887
955
 
888
- ### Failure Reporting (Self-Healing Loop)
889
- If you started Group 3 (called \`get_merchant_hints\` and began following \`pre_steps\`) but CANNOT complete the checkout due to a technical reason:
890
- → Call \`report_checkout_fail(url, error_type, error_message)\` before giving up.
891
- → Use \`url\` = the page you were on when stuck.
892
- → Do NOT call this if user cancelled or balance was insufficient — those are not technical failures.
956
+ ### Known limitations
957
+ - Cloudflare-protected sites (e.g. TeePublic) may block the headless browser → inform the user.
958
+ - Card fields inside iframes: handled automatically via \`iframe_selector\` in hints.
959
+ - Cold browser: \`execute_payment\`/\`auto_pay_checkout\` run in a fresh cookieless browser, so the
960
+ checkout URL must be self-resumable (see "Resumable URL required" under PATH B). Cookie/session-bound
961
+ carts will return \`no_fields\`.
893
962
  `;
894
963
  return {
895
964
  contents: [
@@ -907,8 +976,8 @@ If you started Group 3 (called \`get_merchant_hints\` and began following \`pre_
907
976
  async function main() {
908
977
  const transport = new stdio_js_1.StdioServerTransport();
909
978
  await server.connect(transport);
910
- console.error(`🔐 OpenClaw MCP Server v${version_js_2.CURRENT_MCP_VERSION} running (Phase 2: Smart Routing enabled)...`);
979
+ console.error(`🔐 Z-Zero MCP Server v${version_js_2.CURRENT_MCP_VERSION} running (Base + USDC, gasless via Coinbase Paymaster)...`);
911
980
  console.error("Status: Secure & Connected to Z-ZERO Gateway");
912
- console.error("Tools: list_cards, check_balance, request_payment_token, execute_payment, cancel_payment_token, request_human_approval, auto_pay_checkout, report_checkout_fail");
981
+ console.error("Tools: list_cards, check_balance, get_deposit_addresses, request_payment_token, get_merchant_hints, execute_payment, auto_pay_checkout, cancel_payment_token, request_human_approval, report_checkout_fail, set_api_key, show_api_key_status");
913
982
  }
914
983
  main().catch(console.error);
@@ -7,3 +7,16 @@ import type { Page } from "playwright";
7
7
  * 3. Text heuristic: find largest $ amount near keywords "total", "amount due"
8
8
  */
9
9
  export declare function extractTotalPrice(page: Page): Promise<number | null>;
10
+ /**
11
+ * Detect whether the checkout charges in USD or a non-USD currency.
12
+ * Purpose: size the FX buffer on the JIT card. A USD checkout total is final —
13
+ * our USD card pays it 1:1, no conversion. A non-USD total gets FX-converted +
14
+ * a conversion fee on our USD card and can drift OVER the authorized limit →
15
+ * issuer decline. So non-USD orders need a slightly larger card limit.
16
+ *
17
+ * Conservative by design: defaults to 'USD' unless a CLEAR non-USD signal is
18
+ * present. Both error directions are non-catastrophic (over-buffer → refunded
19
+ * at settlement; under-buffer → a decline the agent can retry), so we avoid
20
+ * false positives from random uppercase text via a currency-code whitelist.
21
+ */
22
+ export declare function detectCheckoutCurrency(page: Page): Promise<'USD' | 'NON_USD'>;