z-zero-mcp-server 1.6.1 → 1.8.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.
package/dist/index.js CHANGED
@@ -46,17 +46,18 @@ const version_js_2 = require("./version.js");
46
46
  const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
47
47
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
48
48
  const zod_1 = require("zod");
49
- // ── WDK Non-Custodial Backend (single backend, no custodial fallback) ─────────
50
- const activeBackend = __importStar(require("./wdk_backend.js"));
49
+ // ── Base backend (single backend, no custodial fallback) ─────────────────────
50
+ const activeBackend = __importStar(require("./base_backend.js"));
51
51
  const issueTokenRemote = activeBackend.issueTokenRemote;
52
52
  const resolveTokenRemote = activeBackend.resolveTokenRemote;
53
53
  const burnTokenRemote = activeBackend.burnTokenRemote;
54
54
  const cancelTokenRemote = activeBackend.cancelTokenRemote;
55
55
  const refundUnderspendRemote = activeBackend.refundUnderspendRemote;
56
+ const postReceiptRemote = activeBackend.postReceiptRemote;
56
57
  const getBalanceRemote = activeBackend.getBalanceRemote;
57
58
  const listCardsRemote = activeBackend.listCardsRemote;
58
59
  const getDepositAddressesRemote = activeBackend.getDepositAddressesRemote;
59
- console.error(`[Z-ZERO MCP] 🚀 Pure WDK Non-Custodial Mode`);
60
+ console.error(`[Z-ZERO MCP] 🚀 Base + USDC (non-custodial, gasless)`);
60
61
  // ────────────────────────────────────────────────────────────────────────────
61
62
  const playwright_bridge_js_1 = require("./playwright_bridge.js");
62
63
  const web3_detector_js_1 = require("./lib/web3-detector.js");
@@ -64,6 +65,8 @@ const extract_total_price_js_1 = require("./lib/extract-total-price.js");
64
65
  const playwright_1 = require("playwright");
65
66
  const key_store_js_1 = require("./lib/key-store.js"); // ✅ Hot-Swap + rotate-on-connect
66
67
  const url_guard_js_1 = require("./lib/url-guard.js");
68
+ const api_base_js_1 = require("./lib/api-base.js");
69
+ const failure_taxonomy_js_1 = require("./failure_taxonomy.js");
67
70
  /** Masked, non-reconstructable hint for a secret key (for debug output only). */
68
71
  function maskKey(key) {
69
72
  if (!key)
@@ -73,6 +76,35 @@ function maskKey(key) {
73
76
  return `${key.slice(0, 4)}…${key.slice(-2)}`;
74
77
  }
75
78
  // ============================================================
79
+ // Structured checkout-event emitter (Primitive 2 — labeling)
80
+ // Fire-and-forget: NEVER blocks or fails the payment flow.
81
+ // Auto-called on every non-confirmed outcome so traffic becomes
82
+ // labeled data even when the agent never calls report_checkout_fail.
83
+ // ============================================================
84
+ function emitCheckoutEvent(evt) {
85
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
86
+ const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
87
+ const body = {
88
+ ...evt,
89
+ // 🔴 redact at capture — the event must never carry PAN/CVV
90
+ error_message: evt.error_message ? (0, failure_taxonomy_js_1.redactCardData)(evt.error_message).slice(0, 500) : undefined,
91
+ taxonomy_version: failure_taxonomy_js_1.TAXONOMY_VERSION,
92
+ mcp_version: version_js_2.CURRENT_MCP_VERSION,
93
+ // Legacy field so an older backend still logs something meaningful
94
+ error_type: evt.raw_error_type || evt.failure_class,
95
+ };
96
+ fetch(`${ZZERO_API}/api/checkout-hints`, {
97
+ method: "POST",
98
+ headers: {
99
+ "Content-Type": "application/json",
100
+ "Authorization": `Bearer ${(0, key_store_js_1.getPassportKey)()}`,
101
+ ...(INTERNAL_SECRET ? { "x-internal-secret": INTERNAL_SECRET } : {}),
102
+ "x-mcp-version": version_js_2.CURRENT_MCP_VERSION,
103
+ },
104
+ body: JSON.stringify(body),
105
+ }).catch(() => { });
106
+ }
107
+ // ============================================================
76
108
  // CREATE MCP SERVER
77
109
  // ============================================================
78
110
  const server = new mcp_js_1.McpServer({
@@ -80,26 +112,40 @@ const server = new mcp_js_1.McpServer({
80
112
  version: version_js_2.CURRENT_MCP_VERSION,
81
113
  });
82
114
  // ============================================================
115
+ // SHARED: the one AUTH_REQUIRED reply
116
+ // ============================================================
117
+ // A 401 can mean the key is missing, mistyped, revoked, or already rotated onto
118
+ // another machine — the server cannot tell us which, so the message must not
119
+ // claim one of them. It also must not send the reader to a restart: set_api_key
120
+ // activates a new key in place (since 1.5.0).
121
+ function authRequiredResult(detail) {
122
+ return {
123
+ content: [{
124
+ type: "text",
125
+ text: "❌ AUTHENTICATION REQUIRED: Z-ZERO rejected your Passport Key — it is missing, invalid, or has been revoked.\n" +
126
+ (detail ? `Server said: ${detail}\n` : "") +
127
+ "\n👉 Get a fresh key: https://z-zero.xyz/dashboard/agents\n" +
128
+ "👉 Then call set_api_key with it — no restart needed. (Or set Z_ZERO_API_KEY in your MCP config and restart.)\n" +
129
+ "Note: one key belongs to one machine — it rotates on first connect, so a key already used elsewhere will not work here."
130
+ }],
131
+ isError: true,
132
+ };
133
+ }
134
+ // ============================================================
83
135
  // TOOL 1: List available cards (safe - no sensitive data)
84
136
  // ============================================================
85
137
  server.tool("list_cards", "List all available virtual card aliases and their balances. No sensitive data is returned.", {}, async () => {
86
138
  const data = await listCardsRemote();
87
- if (data?.error === "AUTH_REQUIRED") {
88
- return {
89
- content: [{
90
- type: "text",
91
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
92
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents\n" +
93
- "👉 Then SET it as the 'Z_ZERO_API_KEY' environment variable in your AI tool (Claude Desktop/Cursor) and RESTART the tool."
94
- }],
95
- isError: true
96
- };
97
- }
139
+ if (data?.error === "AUTH_REQUIRED")
140
+ return authRequiredResult(data.message);
98
141
  if (data?.error) {
99
142
  return {
100
143
  content: [{
101
144
  type: "text",
102
- text: `❌ API ERROR: ${data.message || data.error}\n\nCould not fetch cards. Please verify your Passport Key is correct.`
145
+ // Don't blame the key here — AUTH_REQUIRED was already handled
146
+ // above, so whatever reaches this branch is something else
147
+ // (redirected base URL, deactivated agent, server error).
148
+ text: `❌ API ERROR: ${data.message || data.error}\n\nCould not fetch cards.`
103
149
  }],
104
150
  isError: true
105
151
  };
@@ -130,23 +176,18 @@ server.tool("check_balance", "Check spendable USD balance for a card alias. For
130
176
  .describe("The alias of the card to check, e.g. 'Card_01'"),
131
177
  }, async ({ card_alias }) => {
132
178
  const data = await getBalanceRemote(card_alias);
133
- if (data?.error === "AUTH_REQUIRED") {
134
- return {
135
- content: [{
136
- type: "text",
137
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
138
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents\n" +
139
- "👉 Then SET it as the 'Z_ZERO_API_KEY' environment variable and RESTART."
140
- }],
141
- isError: true
142
- };
143
- }
179
+ if (data?.error === "AUTH_REQUIRED")
180
+ return authRequiredResult(data.message);
144
181
  if (!data || data.error) {
182
+ // Pass the backend's own reason through — "card not found" was being
183
+ // printed over real causes (no wallet, network down, server error).
184
+ const reason = data?.message
185
+ || `Card "${card_alias}" not found. Use list_cards to see available cards.`;
145
186
  return {
146
187
  content: [
147
188
  {
148
189
  type: "text",
149
- text: `Card "${card_alias}" not found or API issue. Use list_cards to see available cards.`,
190
+ text: reason,
150
191
  },
151
192
  ],
152
193
  isError: true,
@@ -166,21 +207,12 @@ server.tool("check_balance", "Check spendable USD balance for a card alias. For
166
207
  // ============================================================
167
208
  server.tool("get_deposit_addresses", "Get your Base deposit address to top up your wallet with USDC (or any supported stablecoin on Base).", {}, async () => {
168
209
  const data = await getDepositAddressesRemote();
169
- if (data?.error === "AUTH_REQUIRED") {
170
- return {
171
- content: [{
172
- type: "text",
173
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
174
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents\n" +
175
- "👉 Then SET it as the 'Z_ZERO_API_KEY' environment variable and RESTART."
176
- }],
177
- isError: true
178
- };
179
- }
210
+ if (data?.error === "AUTH_REQUIRED")
211
+ return authRequiredResult(data.message);
180
212
  // ── Base smart-account wallet ─────────────────────────────────────────
181
- if (data?.wdk_wallet?.address) {
182
- const walletAddr = data.wdk_wallet.address;
183
- const balance = data.wdk_wallet.balance_usdt ?? 0;
213
+ if (data?.base_wallet?.address) {
214
+ const walletAddr = data.base_wallet.address;
215
+ const balance = data.base_wallet.balance_usdt ?? 0;
184
216
  return {
185
217
  content: [{
186
218
  type: "text",
@@ -196,11 +228,14 @@ server.tool("get_deposit_addresses", "Get your Base deposit address to top up yo
196
228
  }],
197
229
  };
198
230
  }
199
- // No Base wallet connected
231
+ // Anything else: say what actually went wrong. Only a real NO_WALLET
232
+ // sends the reader to the wallet page — a network or server failure that
233
+ // pointed there would have them building a wallet they already have.
200
234
  return {
201
235
  content: [{
202
236
  type: "text",
203
- text: "No Base wallet found. Please create one at https://z-zero.xyz/dashboard/agent-wallet",
237
+ text: data?.message
238
+ || "No Base wallet found. Please create one at https://z-zero.xyz/dashboard/agent-wallet",
204
239
  }],
205
240
  isError: true,
206
241
  };
@@ -208,7 +243,8 @@ server.tool("get_deposit_addresses", "Get your Base deposit address to top up yo
208
243
  // ============================================================
209
244
  // TOOL 3: Request a temporary payment token (issues secure JIT card)
210
245
  // ============================================================
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.", {
246
+ 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. " +
247
+ "BEFORE requesting: look at the checkout page one more time and compare it against what the user actually asked for — same items, same quantity, same variant, same destination? If anything differs, do NOT request a token; fix the cart or check with the user first. A mismatch you catch here costs nothing; after this point it costs a card. If you pass `cart`, the server signs your declared intent and binds the card to it — the user gets cryptographic proof of what this card was authorized for.", {
212
248
  card_alias: zod_1.z
213
249
  .string()
214
250
  .describe("Which card to charge, e.g. 'Card_01'"),
@@ -220,18 +256,33 @@ server.tool("request_payment_token", "Request a single-use JIT virtual card ($1
220
256
  merchant: zod_1.z
221
257
  .string()
222
258
  .describe("Name or URL of the merchant/service being purchased"),
223
- }, async ({ card_alias, amount, merchant }) => {
224
- const token = await issueTokenRemote(card_alias, amount, merchant);
225
- if (token?.error === "AUTH_REQUIRED") {
226
- return {
227
- content: [{
228
- type: "text",
229
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
230
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents"
231
- }],
232
- isError: true
233
- };
234
- }
259
+ cart: zod_1.z
260
+ .array(zod_1.z.object({
261
+ title: zod_1.z.string().describe("Item name as shown on the checkout page"),
262
+ qty: zod_1.z.number().describe("Quantity"),
263
+ unit_price: zod_1.z.number().optional().describe("Unit price if visible"),
264
+ url: zod_1.z.string().optional().describe("Product URL if known"),
265
+ }))
266
+ .max(50)
267
+ .optional()
268
+ .describe("RECOMMENDED: the items you are buying, as the USER agreed to them. This becomes a signed intent bound to the card — proof of what was authorized."),
269
+ ship_to: zod_1.z
270
+ .string()
271
+ .optional()
272
+ .describe("Shipping destination as a single string (only a hash is stored, never the raw address)."),
273
+ }, async ({ card_alias, amount, merchant, cart, ship_to }) => {
274
+ const intentInput = (cart && cart.length) || ship_to
275
+ ? {
276
+ cart,
277
+ subtotal: cart?.every(i => typeof i.unit_price === "number")
278
+ ? Math.round(cart.reduce((s, i) => s + i.unit_price * i.qty, 0) * 100) / 100
279
+ : undefined,
280
+ ship_to,
281
+ }
282
+ : undefined;
283
+ const token = await issueTokenRemote(card_alias, amount, merchant, intentInput);
284
+ if (token?.error === "AUTH_REQUIRED")
285
+ return authRequiredResult(token.message);
235
286
  if (!token || token.error) {
236
287
  // Show actual API error if available (e.g. 429 max cards, 402 insufficient)
237
288
  if (token?.message) {
@@ -244,7 +295,11 @@ server.tool("request_payment_token", "Request a single-use JIT virtual card ($1
244
295
  };
245
296
  }
246
297
  const balanceData = await getBalanceRemote(card_alias);
247
- const balance = balanceData?.balance;
298
+ // getBalanceRemote returns `wallet_balance` — reading `balance` here
299
+ // always came back undefined, so this fell through to the vague
300
+ // "not found / key invalid / limit exceeded" line even when the real
301
+ // reason was simply an empty wallet.
302
+ const balance = balanceData?.error ? undefined : balanceData?.wallet_balance;
248
303
  return {
249
304
  content: [
250
305
  {
@@ -269,6 +324,14 @@ server.tool("request_payment_token", "Request a single-use JIT virtual card ($1
269
324
  merchant: token.merchant,
270
325
  expires_at: expiresAt,
271
326
  card_issued: true,
327
+ ...(token.intent ? {
328
+ intent: {
329
+ intent_id: token.intent.intent_id,
330
+ intent_hash: token.intent.intent_hash,
331
+ signer_address: token.intent.signer_address,
332
+ note: "Card is bound to this signed intent. The receipt after purchase will be diffed against it.",
333
+ },
334
+ } : {}),
272
335
  instructions: "Use this token with execute_payment within 1 hour. IMPORTANT: If the actual checkout price is HIGHER than the token amount, do NOT proceed — call cancel_payment_token first and request a new token with the correct amount.",
273
336
  ...(token.mcp_warning ? { _mcp_warning: token.mcp_warning } : {}),
274
337
  }, null, 2),
@@ -286,7 +349,7 @@ server.tool("get_merchant_hints", "Get merchant navigation flow for a domain or
286
349
  .string()
287
350
  .describe("The main domain of the checkout page, e.g. 'amazon.com' or 'shopify.com'. Strip 'www.' prefix."),
288
351
  }, async ({ domain }) => {
289
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
352
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
290
353
  const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
291
354
  try {
292
355
  const resp = await fetch(`${ZZERO_API}/api/checkout-hints?domain=${encodeURIComponent(domain)}&fields=merchant`, {
@@ -362,16 +425,8 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
362
425
  }
363
426
  // Step 1: Resolve token → card data (RAM only)
364
427
  const cardData = await resolveTokenRemote(token);
365
- if (cardData?.error === "AUTH_REQUIRED") {
366
- return {
367
- content: [{
368
- type: "text",
369
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
370
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents"
371
- }],
372
- isError: true
373
- };
374
- }
428
+ if (cardData?.error === "AUTH_REQUIRED")
429
+ return authRequiredResult(cardData.message);
375
430
  if (!cardData || cardData.error) {
376
431
  return {
377
432
  content: [
@@ -393,6 +448,17 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
393
448
  if (actual_amount > tokenAmount * TOLERANCE) {
394
449
  // Auto-cancel the token to free up funds
395
450
  await cancelTokenRemote(token);
451
+ // 📊 Labeled event: price moved between authorization and checkout
452
+ emitCheckoutEvent({
453
+ url: checkout_url,
454
+ failure_class: "price_changed",
455
+ step: "preflight",
456
+ raw_error_type: "PRICE_MISMATCH",
457
+ error_message: `Checkout total $${actual_amount} exceeds authorized $${tokenAmount} (+5% tolerance)`,
458
+ outcome: "aborted",
459
+ labeled_by: "auto",
460
+ card_bin: (0, failure_taxonomy_js_1.extractBin)(cardData.number),
461
+ });
396
462
  return {
397
463
  content: [{
398
464
  type: "text",
@@ -414,10 +480,29 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
414
480
  // Step 3: Burn the token ONLY on a CONFIRMED payment (result.success === status 'confirmed').
415
481
  // Every other outcome (declined / unconfirmed / not_submitted / no_fields / error) leaves the
416
482
  // token UNBURNED so the funds stay recoverable. "Filled a field" is NOT a payment.
417
- if (!result.success) {
483
+ // ONE gate for the irreversible step. `success` is a boolean the bridge sets;
484
+ // `status` is the outcome it observed. Burning a token cannot be undone, so it
485
+ // requires both to say the merchant confirmed the order (backtest E07).
486
+ const isConfirmed = result.success && result.status === 'confirmed';
487
+ if (!isConfirmed) {
418
488
  // `declined` = merchant rejected → webhook refund flow handles it.
419
489
  // Everything else = we couldn't prove a charge happened → funds stay locked, recoverable.
420
490
  const isDeclined = result.status === 'declined';
491
+ // 📊 Auto-label every non-confirmed run — this is the corpus (Primitive 2)
492
+ const label = (0, failure_taxonomy_js_1.classifyBridgeResult)(result.status, result.message);
493
+ if (label) {
494
+ emitCheckoutEvent({
495
+ url: checkout_url,
496
+ failure_class: label.failure_class,
497
+ step: label.step,
498
+ raw_error_type: result.status,
499
+ error_message: result.message,
500
+ outcome: "failed",
501
+ labeled_by: "auto",
502
+ card_bin: (0, failure_taxonomy_js_1.extractBin)(cardData.number),
503
+ intent_id: cardData.intent_id,
504
+ });
505
+ }
421
506
  return {
422
507
  content: [
423
508
  {
@@ -436,12 +521,23 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
436
521
  isError: true,
437
522
  };
438
523
  }
439
- // Confirmed — burn the token, passing the REAL receipt id if one was scraped.
524
+ // Past the gate above, so status === 'confirmed'. Burn, passing the REAL
525
+ // receipt id if one was scraped.
440
526
  await burnTokenRemote(token, result.receipt_id);
441
527
  // Step 4: Refund underspend if actual amount was less than token amount
442
528
  if (actual_amount !== undefined) {
443
529
  await refundUnderspendRemote(token, actual_amount);
444
530
  }
531
+ // Step 4.5: Signed receipt (Primitive 3) — proof of what actually settled,
532
+ // diffed server-side against the intent this token was bound to.
533
+ // Never blocks the result: payment is already confirmed at this point.
534
+ const signedReceipt = await postReceiptRemote({
535
+ token,
536
+ checkout_url,
537
+ merchant_order_id: result.receipt_id || null,
538
+ amount_captured: actual_amount,
539
+ card_last4: cardData.number ? cardData.number.replace(/\D/g, "").slice(-4) : undefined,
540
+ }).catch(() => null);
445
541
  // Step 5: Return result (NEVER includes card numbers)
446
542
  return {
447
543
  content: [
@@ -453,6 +549,16 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
453
549
  message: result.message,
454
550
  receipt_id: result.receipt_id || null,
455
551
  token_status: "BURNED",
552
+ ...(signedReceipt ? {
553
+ signed_receipt: {
554
+ receipt_id: signedReceipt.receipt?.receipt_id,
555
+ receipt_hash: signedReceipt.receipt_hash,
556
+ match: signedReceipt.receipt?.match,
557
+ diff: signedReceipt.receipt?.diff,
558
+ verify_url: signedReceipt.verify_url || null,
559
+ note: "Cryptographically signed proof of this purchase. Share verify_url with the user — anyone can check it.",
560
+ },
561
+ } : {}),
456
562
  note: "Token has been permanently invalidated after this confirmed transaction.",
457
563
  }, null, 2),
458
564
  },
@@ -471,16 +577,8 @@ server.tool("cancel_payment_token", "Cancel unused token and refund instantly. U
471
577
  .describe("Reason for cancellation, e.g. 'Price mismatch: checkout shows $20 but token is $15'"),
472
578
  }, async ({ token, reason }) => {
473
579
  const result = await cancelTokenRemote(token);
474
- if (result?.error === "AUTH_REQUIRED") {
475
- return {
476
- content: [{
477
- type: "text",
478
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
479
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents"
480
- }],
481
- isError: true
482
- };
483
- }
580
+ if (result?.error === "AUTH_REQUIRED")
581
+ return authRequiredResult(result.message);
484
582
  if (!result || !result.success) {
485
583
  return {
486
584
  content: [
@@ -566,9 +664,9 @@ server.tool("set_api_key", "Activate a new Passport Key instantly, no restart ne
566
664
  };
567
665
  }
568
666
  // Step 2: Validate new key against Dashboard API before swapping
569
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
667
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
570
668
  try {
571
- const resp = await fetch(`${ZZERO_API}/api/wdk/balance`, {
669
+ const resp = await fetch(`${ZZERO_API}/api/wallet/balance`, {
572
670
  headers: {
573
671
  "Authorization": `Bearer ${trimmed}`,
574
672
  "x-mcp-version": version_js_2.CURRENT_MCP_VERSION,
@@ -683,7 +781,7 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
683
781
  .string()
684
782
  .describe("Card alias to charge for JIT Fiat fallback, e.g. 'Card_01'."),
685
783
  }, async ({ checkout_url, card_alias }) => {
686
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
784
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
687
785
  const API_KEY = (0, key_store_js_1.getPassportKey)(); // ✅ FIX: use hot-swap key store, not process.env
688
786
  // Spend guard for the autonomous path. auto_pay derives the amount itself
689
787
  // (scraped fiat total OR on-chain amount from an EIP-681 link / calldata), so there is
@@ -736,7 +834,7 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
736
834
  isError: true,
737
835
  };
738
836
  }
739
- const resp = await fetch(`${ZZERO_API}/api/wdk/transfer`, {
837
+ const resp = await fetch(`${ZZERO_API}/api/wallet/transfer`, {
740
838
  method: "POST",
741
839
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` },
742
840
  body: JSON.stringify({ to, amount, card_alias }),
@@ -763,6 +861,16 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
763
861
  console.error(`[SMART ROUTE] No Web3. Extracting price...`);
764
862
  const totalPrice = await (0, extract_total_price_js_1.extractTotalPrice)(page);
765
863
  if (!totalPrice) {
864
+ // 📊 Price extraction failed = DOM we don't understand → form_changed
865
+ emitCheckoutEvent({
866
+ url: checkout_url,
867
+ failure_class: "form_changed",
868
+ step: "navigate",
869
+ raw_error_type: "PRICE_NOT_FOUND",
870
+ error_message: "Could not extract total price from checkout page",
871
+ outcome: "aborted",
872
+ labeled_by: "auto",
873
+ });
766
874
  return {
767
875
  content: [{ type: "text", text: JSON.stringify({
768
876
  route: "FIAT", status: "PRICE_NOT_FOUND",
@@ -802,14 +910,39 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
802
910
  const fillResult = await (0, playwright_bridge_js_1.fillCheckoutForm)(checkout_url, cardData, page);
803
911
  // Burn ONLY on a confirmed charge. Any other outcome leaves the JIT token unburned
804
912
  // so the locked funds are recoverable (cancel/expire/decline-webhook).
805
- if (fillResult.success) {
913
+ let autoReceipt = null;
914
+ // Same rule as execute_payment: burning needs both the flag and the
915
+ // observed status to say confirmed (backtest E07).
916
+ if (fillResult.success && fillResult.status === 'confirmed') {
806
917
  const burnOk = await burnTokenRemote(token.token, fillResult.receipt_id);
807
918
  if (!burnOk)
808
919
  console.error(`[WARN] Token burn failed for ${token.token} — manual check needed`);
920
+ // Signed receipt (Primitive 3) — never blocks the confirmed result
921
+ autoReceipt = await postReceiptRemote({
922
+ token: token.token,
923
+ checkout_url,
924
+ merchant_order_id: fillResult.receipt_id || null,
925
+ amount_captured: totalPrice,
926
+ card_last4: cardData.number ? cardData.number.replace(/\D/g, "").slice(-4) : undefined,
927
+ }).catch(() => null);
809
928
  }
810
929
  else {
811
930
  // Release the freshly-issued JIT token so the price funds don't sit locked on a non-payment.
812
931
  await cancelTokenRemote(token.token).catch(() => { });
932
+ // 📊 Auto-label the failed run (Primitive 2 corpus)
933
+ const label = (0, failure_taxonomy_js_1.classifyBridgeResult)(fillResult.status, fillResult.message);
934
+ if (label) {
935
+ emitCheckoutEvent({
936
+ url: checkout_url,
937
+ failure_class: label.failure_class,
938
+ step: label.step,
939
+ raw_error_type: fillResult.status,
940
+ error_message: fillResult.message,
941
+ outcome: "failed",
942
+ labeled_by: "auto",
943
+ card_bin: (0, failure_taxonomy_js_1.extractBin)(cardData.number),
944
+ });
945
+ }
813
946
  }
814
947
  return {
815
948
  content: [{ type: "text", text: JSON.stringify({
@@ -824,6 +957,14 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
824
957
  ? `✅ Confirmed: JIT card issued (limit $${issueAmount}) and order confirmed by merchant for ~$${totalPrice}.`
825
958
  : `❌ Not confirmed (${fillResult.status}): ${fillResult.message} Token released.`,
826
959
  receipt_id: fillResult.receipt_id || null,
960
+ ...(autoReceipt ? {
961
+ signed_receipt: {
962
+ receipt_id: autoReceipt.receipt?.receipt_id,
963
+ receipt_hash: autoReceipt.receipt_hash,
964
+ match: autoReceipt.receipt?.match,
965
+ verify_url: autoReceipt.verify_url || null,
966
+ },
967
+ } : {}),
827
968
  }, null, 2) }],
828
969
  isError: !fillResult.success,
829
970
  };
@@ -831,6 +972,19 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
831
972
  catch (err) {
832
973
  // ✅ FIX 8: Sanitize error message before returning to agent — avoid leaking internal paths
833
974
  const safeMsg = (err?.message || String(err)).replace(/\/.*(src|dist)\/.*\.ts/g, '[internal]').slice(0, 200);
975
+ // 📊 Label the exception path too (timeout vs unknown)
976
+ const label = (0, failure_taxonomy_js_1.classifyBridgeResult)("error", safeMsg);
977
+ if (label) {
978
+ emitCheckoutEvent({
979
+ url: checkout_url,
980
+ failure_class: label.failure_class,
981
+ step: label.step,
982
+ raw_error_type: "EXCEPTION",
983
+ error_message: safeMsg,
984
+ outcome: "failed",
985
+ labeled_by: "auto",
986
+ });
987
+ }
834
988
  return {
835
989
  content: [{ type: "text", text: JSON.stringify({
836
990
  status: "ERROR", message: safeMsg,
@@ -848,46 +1002,79 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
848
1002
  // Triggers: stuck mid pre_steps, bot blocked, selector not found, etc.
849
1003
  // Does NOT apply to: user cancelled, insufficient balance, price mismatch.
850
1004
  // ============================================================
851
- server.tool("report_checkout_fail", "Report a checkout URL that you could not complete. Call this when you failed to finish a purchase — for any reason (field not found, bot blocked, timeout, unknown form). The URL will be logged for admin review to improve future checkout success rates. This is part of Z-ZERO's self-healing loop.", {
1005
+ server.tool("report_checkout_fail", "Report a checkout you could not complete. Pick the failure_class that best matches what you saw — this feeds Z-ZERO's self-healing loop (labeled failures become better merchant hints for the next run). If nothing fits, use 'unknown' and describe what happened in error_message.", {
852
1006
  url: zod_1.z
853
1007
  .string()
854
1008
  .url()
855
1009
  .describe("The checkout/payment page URL where the purchase failed."),
856
- error_type: zod_1.z
857
- .string()
858
- .describe("Short error category: 'field_not_found', 'timeout', 'bot_blocked', 'unknown_form', 'price_mismatch', or 'other'."),
1010
+ failure_class: zod_1.z
1011
+ .enum(failure_taxonomy_js_1.FAILURE_CLASSES)
1012
+ .describe("Fixed failure class: 'card_declined_issuer' (card rejected by bank), 'card_declined_bin_block' (merchant refuses prepaid/virtual cards), 'avs_mismatch' (billing address rejected), '3ds_required' (extra verification/SCA screen appeared), 'bot_detected' (CAPTCHA/Cloudflare/'unusual activity'), 'form_changed' (expected field or button not found), 'price_changed' (total differs from expected), 'out_of_stock', 'shipping_unsupported' (cannot ship to address), 'login_required' (checkout demands an account), 'timeout', 'outcome_unconfirmed' (submitted but no confirmation seen), or 'unknown'."),
1013
+ step: zod_1.z
1014
+ .enum(failure_taxonomy_js_1.CHECKOUT_STEPS)
1015
+ .optional()
1016
+ .describe("Where it failed: 'navigate' (page load), 'pre_steps' (shipping/navigation steps), 'fill_form' (card fields), 'submit' (Pay button), 'confirm' (after submitting)."),
859
1017
  error_message: zod_1.z
860
1018
  .string()
861
1019
  .optional()
862
- .describe("Brief description of what went wrong, e.g. 'Could not find card number field' or 'Page redirected to CAPTCHA'."),
863
- }, async ({ url, error_type, error_message }) => {
864
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
865
- const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
866
- try {
867
- await fetch(`${ZZERO_API}/api/checkout-hints`, {
868
- method: "POST",
869
- headers: {
870
- "Content-Type": "application/json",
871
- "Authorization": `Bearer ${(0, key_store_js_1.getPassportKey)()}`,
872
- ...(INTERNAL_SECRET ? { "x-internal-secret": INTERNAL_SECRET } : {}),
873
- "x-mcp-version": version_js_2.CURRENT_MCP_VERSION,
874
- },
875
- body: JSON.stringify({ url, error_type, error_message, mcp_version: version_js_2.CURRENT_MCP_VERSION }),
876
- });
877
- }
878
- catch {
879
- // Fire-and-forget — never block the agent on a logging call
880
- }
1020
+ .describe("Brief description of what you saw, e.g. 'Card number field is inside a new iframe' or 'Page redirected to CAPTCHA'. NEVER include card numbers."),
1021
+ remediation_tried: zod_1.z
1022
+ .string()
1023
+ .optional()
1024
+ .describe("What you already tried before giving up, e.g. 'retried with submit_selector from hints'."),
1025
+ }, async ({ url, failure_class, step, error_message, remediation_tried }) => {
1026
+ emitCheckoutEvent({
1027
+ url,
1028
+ failure_class,
1029
+ step,
1030
+ error_message,
1031
+ remediation_tried,
1032
+ outcome: "failed",
1033
+ labeled_by: "agent",
1034
+ });
881
1035
  return {
882
1036
  content: [{ type: "text", text: JSON.stringify({
883
1037
  logged: true,
884
1038
  url,
885
- error_type,
886
- message: "Checkout failure logged. Admin will review and improve hints for this domain.",
1039
+ failure_class,
1040
+ message: "Checkout failure recorded with a structured label. This improves merchant hints for future runs.",
887
1041
  }, null, 2) }],
888
1042
  };
889
1043
  });
890
1044
  // ============================================================
1045
+ // TOOL: Verify a signed receipt (Primitive 3)
1046
+ // Lets the agent PROVE a purchase happened instead of claiming it.
1047
+ // Public endpoint — anyone with the receipt_id can verify.
1048
+ // ============================================================
1049
+ server.tool("verify_receipt", "Check where an order ENDED UP, and prove it. Returns TWO separate axes: " +
1050
+ "`order_status` — 'completed' (bought, issuer not reported yet) · 'settled' (issuer confirmed) · 'reversed' (auth voided before clearing — the order does NOT stand) · 'partially_refunded' / 'refunded' (merchant returned money AFTER settlement — the order still happened) — " +
1051
+ "and `funds_status` — 'no_payout_due' · 'payout_pending' (money owed back but not yet confirmed on-chain) · 'returned' (confirmed on-chain). " +
1052
+ "Read BOTH before speaking: 'reversed' or 'refunded' with funds 'payout_pending' means the buyer has NOT got the money back yet — never say they have. If you told the user a purchase was done and a later check returns 'reversed', tell them unprompted.", {
1053
+ receipt_id: zod_1.z
1054
+ .string()
1055
+ .describe("The receipt_id returned by execute_payment / auto_pay_checkout (signed_receipt.receipt_id)."),
1056
+ }, async ({ receipt_id }) => {
1057
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
1058
+ try {
1059
+ const resp = await fetch(`${ZZERO_API}/api/receipts/${encodeURIComponent(receipt_id)}`, {
1060
+ headers: { "x-mcp-version": version_js_2.CURRENT_MCP_VERSION },
1061
+ });
1062
+ const data = await resp.json();
1063
+ return {
1064
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1065
+ };
1066
+ }
1067
+ catch (err) {
1068
+ return {
1069
+ content: [{ type: "text", text: JSON.stringify({
1070
+ found: false,
1071
+ message: `Could not reach receipts API: ${err?.message || "unknown error"}. The receipt may still be valid — try the public verify page.`,
1072
+ }, null, 2) }],
1073
+ isError: true,
1074
+ };
1075
+ }
1076
+ });
1077
+ // ============================================================
891
1078
  // RESOURCE: Z-ZERO Autonomous Payment SOP
892
1079
  // ============================================================
893
1080
  server.resource("Standard Operating Procedure (SOP) for Autonomous Payments", "mcp://resources/sop", {
@@ -942,8 +1129,29 @@ Tools: \`get_merchant_hints\`, \`request_payment_token\`, \`execute_payment\`, \
942
1129
  2. Follow \`pre_steps\` in YOUR browser: navigate, add to cart, submit shipping (ask the user via
943
1130
  \`request_human_approval\` if shipping info is unknown).
944
1131
  3. Wait until the card section is visible AND the FINAL total (incl. shipping + tax) is shown.
945
- 4. \`request_payment_token(card_alias, amount = exact final total, merchant)\` → one-time token, valid 1h.
946
- 5. \`execute_payment(token, checkout_url, actual_amount = final total)\`. ALWAYS pass actual_amount.
1132
+ 4. **INTENT CHECK (do this yourself — it is free):** look at the checkout page one more time and compare
1133
+ it with what the user actually asked for: same items, same quantity, same variant/size/color, same
1134
+ destination. If ANYTHING differs → do NOT request a token. Fix the cart or ask the user. A mismatch
1135
+ caught now costs nothing; after the token it costs a card. If you give up on the mismatch, call
1136
+ \`report_checkout_fail\` with failure_class \`intent_mismatch\`.
1137
+ 5. \`request_payment_token(card_alias, amount = exact final total, merchant, cart = items as the user
1138
+ agreed to them, ship_to = destination)\` → one-time token, valid 1h. Passing \`cart\` makes Z-Zero SIGN
1139
+ your declared intent and bind the card to it — the user gets cryptographic proof of what was authorized.
1140
+ 6. \`execute_payment(token, checkout_url, actual_amount = final total)\`. ALWAYS pass actual_amount.
1141
+ On success you get \`signed_receipt\` (+ verify_url): a signed statement of what actually settled,
1142
+ diffed against the intent. Share verify_url with the user — prove the purchase, don't claim it.
1143
+
1144
+ 7. **After a confirmed purchase, say it is bought — then watch what the issuer says.**
1145
+ \`status: confirmed\` means the order was really placed, so tell the user it is done; do not
1146
+ hedge. The card issuer reports minutes later. When you check back — or the user asks — call
1147
+ \`verify_receipt(receipt_id)\` and read BOTH axes:
1148
+ · \`order_status\`: 'completed' → 'settled' (confirmed) · 'reversed' (auth voided — the order
1149
+ does NOT stand) · 'partially_refunded'/'refunded' (merchant returned money; the order
1150
+ itself still happened).
1151
+ · \`funds_status\`: 'payout_pending' means money is owed back but NOT yet confirmed on-chain —
1152
+ never tell the user their money is back until it says 'returned'.
1153
+ If order_status comes back 'reversed' after you already said it was bought, correct
1154
+ yourself immediately and unprompted.
947
1155
 
948
1156
  ⛔ Never call \`request_payment_token\` before BOTH: shipping submitted AND card fields + final total visible.
949
1157
 
@@ -994,7 +1202,8 @@ After \`confirmed\`/\`unconfirmed\`, prefer to visually confirm the order page w
994
1202
 
995
1203
  If you began PATH B (called \`get_merchant_hints\` + followed \`pre_steps\`) but cannot finish for a
996
1204
  TECHNICAL reason (field not found, bot-blocked, timeout, unknown form):
997
- → Call \`report_checkout_fail(url, error_type, error_message)\` before giving up (url = the page you got stuck on).
1205
+ → Call \`report_checkout_fail(url, failure_class, step, error_message)\` before giving up (url = the page you got stuck on;
1206
+ pick the closest \`failure_class\` from the tool's enum — use 'unknown' only as last resort).
998
1207
  → Do NOT call it for user-cancelled or insufficient-balance — those are not technical failures.
999
1208
 
1000
1209
  ### Known limitations
@@ -1060,6 +1269,6 @@ async function main() {
1060
1269
  await server.connect(transport);
1061
1270
  console.error(`🔐 Z-Zero MCP Server v${version_js_2.CURRENT_MCP_VERSION} running (Base + USDC, gasless via Coinbase Paymaster)...`);
1062
1271
  console.error("Status: Secure & Connected to Z-ZERO Gateway");
1063
- 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");
1272
+ 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, verify_receipt, set_api_key, show_api_key_status");
1064
1273
  }
1065
1274
  main().catch(console.error);