z-zero-mcp-server 1.6.0 → 1.7.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.
@@ -0,0 +1,42 @@
1
+ export declare const TAXONOMY_VERSION = 1;
2
+ /**
3
+ * Fixed failure classes. Each has a detector (how it is recognized) and a
4
+ * remediation (what the loop should try next time). Do NOT free-text new
5
+ * classes — extend the enum and bump TAXONOMY_VERSION instead.
6
+ */
7
+ export declare const FAILURE_CLASSES: readonly ["card_declined_issuer", "card_declined_bin_block", "avs_mismatch", "3ds_required", "bot_detected", "form_changed", "price_changed", "out_of_stock", "shipping_unsupported", "login_required", "timeout", "outcome_unconfirmed", "intent_mismatch", "unknown"];
8
+ export type FailureClass = (typeof FAILURE_CLASSES)[number];
9
+ /** Where in the checkout flow the failure happened. */
10
+ export declare const CHECKOUT_STEPS: readonly ["preflight", "navigate", "pre_steps", "fill_form", "submit", "confirm"];
11
+ export type CheckoutStep = (typeof CHECKOUT_STEPS)[number];
12
+ /** Structured checkout event — one row per failed (or notable) run. */
13
+ export interface CheckoutEvent {
14
+ url: string;
15
+ failure_class: FailureClass;
16
+ step?: CheckoutStep;
17
+ raw_error_type?: string;
18
+ error_message?: string;
19
+ remediation_tried?: string;
20
+ outcome?: "failed" | "recovered" | "aborted";
21
+ labeled_by: "auto" | "agent" | "human";
22
+ card_bin?: string;
23
+ intent_id?: string;
24
+ evidence_ref?: string;
25
+ }
26
+ /** Mask any 12–19 digit sequence (with optional space/dash separators) and CVV-looking patterns. */
27
+ export declare function redactCardData(text: string): string;
28
+ /** First 6 digits of a PAN — safe to log (BIN is not cardholder data). */
29
+ export declare function extractBin(cardNumber: string | undefined): string | undefined;
30
+ /**
31
+ * Map a bridge PaymentOutcome (+ message) to a failure_class + step.
32
+ * Returns null for 'confirmed' (nothing to record as a failure).
33
+ */
34
+ export declare function classifyBridgeResult(status: string, message?: string): {
35
+ failure_class: FailureClass;
36
+ step: CheckoutStep;
37
+ } | null;
38
+ /**
39
+ * Legacy string → enum map. Old published MCP versions (and old SOP text)
40
+ * send free-text error_type; the backend uses this same map server-side.
41
+ */
42
+ export declare const LEGACY_ERROR_TYPE_MAP: Record<string, FailureClass>;
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // Z-ZERO Failure Taxonomy — single source of truth (v1)
4
+ //
5
+ // Every checkout failure MUST map to exactly one failure_class below.
6
+ // This enum is the schema for the labeled-event corpus (Primitive 2,
7
+ // docs/zzero_agent_primitives_30_07_26.md): labels cannot be assigned
8
+ // retroactively, so this file exists BEFORE the self-healing loop does.
9
+ //
10
+ // ⚠️ KEEP IN SYNC with z-zero-dashboard/src/lib/failure-taxonomy.ts
11
+ // (two repos, no shared package — bump TAXONOMY_VERSION together).
12
+ // ============================================================
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.LEGACY_ERROR_TYPE_MAP = exports.CHECKOUT_STEPS = exports.FAILURE_CLASSES = exports.TAXONOMY_VERSION = void 0;
15
+ exports.redactCardData = redactCardData;
16
+ exports.extractBin = extractBin;
17
+ exports.classifyBridgeResult = classifyBridgeResult;
18
+ exports.TAXONOMY_VERSION = 1;
19
+ /**
20
+ * Fixed failure classes. Each has a detector (how it is recognized) and a
21
+ * remediation (what the loop should try next time). Do NOT free-text new
22
+ * classes — extend the enum and bump TAXONOMY_VERSION instead.
23
+ */
24
+ exports.FAILURE_CLASSES = [
25
+ "card_declined_issuer", // issuer/webhook decline → check velocity/MCC/funds
26
+ "card_declined_bin_block", // merchant rejects prepaid/virtual BIN → try different BIN
27
+ "avs_mismatch", // address verification failed → use real billing address
28
+ "3ds_required", // SCA challenge appeared → escalate request_human_approval
29
+ "bot_detected", // captcha / Cloudflare / "unusual activity" → new session, slow down
30
+ "form_changed", // selector not found / DOM changed → re-probe, update hints
31
+ "price_changed", // total differs from what was authorized → request new token/intent
32
+ "out_of_stock", // item unavailable at checkout → back to agent for new intent
33
+ "shipping_unsupported", // merchant can't ship to address → fail early, don't issue card
34
+ "login_required", // checkout requires an account → out of scope, report clearly
35
+ "timeout", // page/flow timed out → check hints whether retry is safe
36
+ "outcome_unconfirmed", // submitted but no confirmation signal → verify before any retry
37
+ "intent_mismatch", // reserved for Primitive 1 (checkout page ≠ signed intent)
38
+ "unknown", // catch-all — target of the weekly human-labeling pass
39
+ ];
40
+ /** Where in the checkout flow the failure happened. */
41
+ exports.CHECKOUT_STEPS = [
42
+ "preflight", // before the browser touched the page (amount guard, balance, config)
43
+ "navigate", // opening the checkout URL
44
+ "pre_steps", // walking hints.pre_steps (shipping form, accordion, etc.)
45
+ "fill_form", // injecting card fields
46
+ "submit", // clicking Pay
47
+ "confirm", // waiting for / parsing the confirmation signal
48
+ ];
49
+ // ------------------------------------------------------------
50
+ // Redaction — 🔴 redact at capture time, never after.
51
+ // Screenshots/DOM/HAR/messages must never contain PAN or CVV.
52
+ // ------------------------------------------------------------
53
+ /** Mask any 12–19 digit sequence (with optional space/dash separators) and CVV-looking patterns. */
54
+ function redactCardData(text) {
55
+ if (!text)
56
+ return text;
57
+ return text
58
+ // PAN: 12-19 digits, allowing spaces or dashes between groups
59
+ .replace(/\b(?:\d[ -]?){12,19}\b/g, "[PAN_REDACTED]")
60
+ // CVV mentioned next to a 3-4 digit number
61
+ .replace(/\b(cvv|cvc|security code)\b\s*:?\s*\d{3,4}/gi, "$1 [REDACTED]");
62
+ }
63
+ /** First 6 digits of a PAN — safe to log (BIN is not cardholder data). */
64
+ function extractBin(cardNumber) {
65
+ const digits = (cardNumber || "").replace(/\D/g, "");
66
+ return digits.length >= 6 ? digits.slice(0, 6) : undefined;
67
+ }
68
+ // ------------------------------------------------------------
69
+ // Auto-classification of Playwright bridge outcomes.
70
+ // This is what turns today's traffic into labeled data without
71
+ // waiting for the agent to call report_checkout_fail.
72
+ // ------------------------------------------------------------
73
+ const BIN_BLOCK_RE = /prepaid|virtual card|this card type|card type (?:is )?not (?:accepted|supported)/i;
74
+ const AVS_RE = /billing address|address (?:verification|does not match|mismatch)|avs/i;
75
+ const THREEDS_RE = /3d[\s-]?secure|verified by visa|additional (?:verification|authentication)|authentication required/i;
76
+ const BOT_RE = /captcha|unusual activity|cloudflare|are you a robot|access denied|blocked/i;
77
+ /**
78
+ * Map a bridge PaymentOutcome (+ message) to a failure_class + step.
79
+ * Returns null for 'confirmed' (nothing to record as a failure).
80
+ */
81
+ function classifyBridgeResult(status, message) {
82
+ const msg = message || "";
83
+ switch (status) {
84
+ case "confirmed":
85
+ return null;
86
+ case "declined":
87
+ if (BIN_BLOCK_RE.test(msg))
88
+ return { failure_class: "card_declined_bin_block", step: "confirm" };
89
+ if (AVS_RE.test(msg))
90
+ return { failure_class: "avs_mismatch", step: "confirm" };
91
+ if (THREEDS_RE.test(msg))
92
+ return { failure_class: "3ds_required", step: "confirm" };
93
+ return { failure_class: "card_declined_issuer", step: "confirm" };
94
+ case "unconfirmed":
95
+ return { failure_class: "outcome_unconfirmed", step: "confirm" };
96
+ case "not_submitted":
97
+ return { failure_class: "form_changed", step: "submit" };
98
+ case "no_fields":
99
+ if (BOT_RE.test(msg))
100
+ return { failure_class: "bot_detected", step: "navigate" };
101
+ return { failure_class: "form_changed", step: "fill_form" };
102
+ case "error":
103
+ if (/timeout|timed out/i.test(msg))
104
+ return { failure_class: "timeout", step: "navigate" };
105
+ if (BOT_RE.test(msg))
106
+ return { failure_class: "bot_detected", step: "navigate" };
107
+ return { failure_class: "unknown", step: "navigate" };
108
+ default:
109
+ return { failure_class: "unknown", step: "navigate" };
110
+ }
111
+ }
112
+ /**
113
+ * Legacy string → enum map. Old published MCP versions (and old SOP text)
114
+ * send free-text error_type; the backend uses this same map server-side.
115
+ */
116
+ exports.LEGACY_ERROR_TYPE_MAP = {
117
+ field_not_found: "form_changed",
118
+ timeout: "timeout",
119
+ bot_blocked: "bot_detected",
120
+ unknown_form: "form_changed",
121
+ price_mismatch: "price_changed",
122
+ other: "unknown",
123
+ };
package/dist/index.js CHANGED
@@ -53,6 +53,7 @@ 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;
@@ -64,6 +65,7 @@ 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 failure_taxonomy_js_1 = require("./failure_taxonomy.js");
67
69
  /** Masked, non-reconstructable hint for a secret key (for debug output only). */
68
70
  function maskKey(key) {
69
71
  if (!key)
@@ -73,6 +75,35 @@ function maskKey(key) {
73
75
  return `${key.slice(0, 4)}…${key.slice(-2)}`;
74
76
  }
75
77
  // ============================================================
78
+ // Structured checkout-event emitter (Primitive 2 — labeling)
79
+ // Fire-and-forget: NEVER blocks or fails the payment flow.
80
+ // Auto-called on every non-confirmed outcome so traffic becomes
81
+ // labeled data even when the agent never calls report_checkout_fail.
82
+ // ============================================================
83
+ function emitCheckoutEvent(evt) {
84
+ const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
85
+ const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
86
+ const body = {
87
+ ...evt,
88
+ // 🔴 redact at capture — the event must never carry PAN/CVV
89
+ error_message: evt.error_message ? (0, failure_taxonomy_js_1.redactCardData)(evt.error_message).slice(0, 500) : undefined,
90
+ taxonomy_version: failure_taxonomy_js_1.TAXONOMY_VERSION,
91
+ mcp_version: version_js_2.CURRENT_MCP_VERSION,
92
+ // Legacy field so an older backend still logs something meaningful
93
+ error_type: evt.raw_error_type || evt.failure_class,
94
+ };
95
+ fetch(`${ZZERO_API}/api/checkout-hints`, {
96
+ method: "POST",
97
+ headers: {
98
+ "Content-Type": "application/json",
99
+ "Authorization": `Bearer ${(0, key_store_js_1.getPassportKey)()}`,
100
+ ...(INTERNAL_SECRET ? { "x-internal-secret": INTERNAL_SECRET } : {}),
101
+ "x-mcp-version": version_js_2.CURRENT_MCP_VERSION,
102
+ },
103
+ body: JSON.stringify(body),
104
+ }).catch(() => { });
105
+ }
106
+ // ============================================================
76
107
  // CREATE MCP SERVER
77
108
  // ============================================================
78
109
  const server = new mcp_js_1.McpServer({
@@ -208,7 +239,8 @@ server.tool("get_deposit_addresses", "Get your Base deposit address to top up yo
208
239
  // ============================================================
209
240
  // TOOL 3: Request a temporary payment token (issues secure JIT card)
210
241
  // ============================================================
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.", {
242
+ 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. " +
243
+ "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
244
  card_alias: zod_1.z
213
245
  .string()
214
246
  .describe("Which card to charge, e.g. 'Card_01'"),
@@ -220,8 +252,31 @@ server.tool("request_payment_token", "Request a single-use JIT virtual card ($1
220
252
  merchant: zod_1.z
221
253
  .string()
222
254
  .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);
255
+ cart: zod_1.z
256
+ .array(zod_1.z.object({
257
+ title: zod_1.z.string().describe("Item name as shown on the checkout page"),
258
+ qty: zod_1.z.number().describe("Quantity"),
259
+ unit_price: zod_1.z.number().optional().describe("Unit price if visible"),
260
+ url: zod_1.z.string().optional().describe("Product URL if known"),
261
+ }))
262
+ .max(50)
263
+ .optional()
264
+ .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."),
265
+ ship_to: zod_1.z
266
+ .string()
267
+ .optional()
268
+ .describe("Shipping destination as a single string (only a hash is stored, never the raw address)."),
269
+ }, async ({ card_alias, amount, merchant, cart, ship_to }) => {
270
+ const intentInput = (cart && cart.length) || ship_to
271
+ ? {
272
+ cart,
273
+ subtotal: cart?.every(i => typeof i.unit_price === "number")
274
+ ? Math.round(cart.reduce((s, i) => s + i.unit_price * i.qty, 0) * 100) / 100
275
+ : undefined,
276
+ ship_to,
277
+ }
278
+ : undefined;
279
+ const token = await issueTokenRemote(card_alias, amount, merchant, intentInput);
225
280
  if (token?.error === "AUTH_REQUIRED") {
226
281
  return {
227
282
  content: [{
@@ -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),
@@ -393,6 +456,17 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
393
456
  if (actual_amount > tokenAmount * TOLERANCE) {
394
457
  // Auto-cancel the token to free up funds
395
458
  await cancelTokenRemote(token);
459
+ // 📊 Labeled event: price moved between authorization and checkout
460
+ emitCheckoutEvent({
461
+ url: checkout_url,
462
+ failure_class: "price_changed",
463
+ step: "preflight",
464
+ raw_error_type: "PRICE_MISMATCH",
465
+ error_message: `Checkout total $${actual_amount} exceeds authorized $${tokenAmount} (+5% tolerance)`,
466
+ outcome: "aborted",
467
+ labeled_by: "auto",
468
+ card_bin: (0, failure_taxonomy_js_1.extractBin)(cardData.number),
469
+ });
396
470
  return {
397
471
  content: [{
398
472
  type: "text",
@@ -418,6 +492,21 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
418
492
  // `declined` = merchant rejected → webhook refund flow handles it.
419
493
  // Everything else = we couldn't prove a charge happened → funds stay locked, recoverable.
420
494
  const isDeclined = result.status === 'declined';
495
+ // 📊 Auto-label every non-confirmed run — this is the corpus (Primitive 2)
496
+ const label = (0, failure_taxonomy_js_1.classifyBridgeResult)(result.status, result.message);
497
+ if (label) {
498
+ emitCheckoutEvent({
499
+ url: checkout_url,
500
+ failure_class: label.failure_class,
501
+ step: label.step,
502
+ raw_error_type: result.status,
503
+ error_message: result.message,
504
+ outcome: "failed",
505
+ labeled_by: "auto",
506
+ card_bin: (0, failure_taxonomy_js_1.extractBin)(cardData.number),
507
+ intent_id: cardData.intent_id,
508
+ });
509
+ }
421
510
  return {
422
511
  content: [
423
512
  {
@@ -442,6 +531,16 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
442
531
  if (actual_amount !== undefined) {
443
532
  await refundUnderspendRemote(token, actual_amount);
444
533
  }
534
+ // Step 4.5: Signed receipt (Primitive 3) — proof of what actually settled,
535
+ // diffed server-side against the intent this token was bound to.
536
+ // Never blocks the result: payment is already confirmed at this point.
537
+ const signedReceipt = await postReceiptRemote({
538
+ token,
539
+ checkout_url,
540
+ merchant_order_id: result.receipt_id || null,
541
+ amount_captured: actual_amount,
542
+ card_last4: cardData.number ? cardData.number.replace(/\D/g, "").slice(-4) : undefined,
543
+ }).catch(() => null);
445
544
  // Step 5: Return result (NEVER includes card numbers)
446
545
  return {
447
546
  content: [
@@ -453,6 +552,16 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
453
552
  message: result.message,
454
553
  receipt_id: result.receipt_id || null,
455
554
  token_status: "BURNED",
555
+ ...(signedReceipt ? {
556
+ signed_receipt: {
557
+ receipt_id: signedReceipt.receipt?.receipt_id,
558
+ receipt_hash: signedReceipt.receipt_hash,
559
+ match: signedReceipt.receipt?.match,
560
+ diff: signedReceipt.receipt?.diff,
561
+ verify_url: signedReceipt.verify_url || null,
562
+ note: "Cryptographically signed proof of this purchase. Share verify_url with the user — anyone can check it.",
563
+ },
564
+ } : {}),
456
565
  note: "Token has been permanently invalidated after this confirmed transaction.",
457
566
  }, null, 2),
458
567
  },
@@ -763,6 +872,16 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
763
872
  console.error(`[SMART ROUTE] No Web3. Extracting price...`);
764
873
  const totalPrice = await (0, extract_total_price_js_1.extractTotalPrice)(page);
765
874
  if (!totalPrice) {
875
+ // 📊 Price extraction failed = DOM we don't understand → form_changed
876
+ emitCheckoutEvent({
877
+ url: checkout_url,
878
+ failure_class: "form_changed",
879
+ step: "navigate",
880
+ raw_error_type: "PRICE_NOT_FOUND",
881
+ error_message: "Could not extract total price from checkout page",
882
+ outcome: "aborted",
883
+ labeled_by: "auto",
884
+ });
766
885
  return {
767
886
  content: [{ type: "text", text: JSON.stringify({
768
887
  route: "FIAT", status: "PRICE_NOT_FOUND",
@@ -802,14 +921,37 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
802
921
  const fillResult = await (0, playwright_bridge_js_1.fillCheckoutForm)(checkout_url, cardData, page);
803
922
  // Burn ONLY on a confirmed charge. Any other outcome leaves the JIT token unburned
804
923
  // so the locked funds are recoverable (cancel/expire/decline-webhook).
924
+ let autoReceipt = null;
805
925
  if (fillResult.success) {
806
926
  const burnOk = await burnTokenRemote(token.token, fillResult.receipt_id);
807
927
  if (!burnOk)
808
928
  console.error(`[WARN] Token burn failed for ${token.token} — manual check needed`);
929
+ // Signed receipt (Primitive 3) — never blocks the confirmed result
930
+ autoReceipt = await postReceiptRemote({
931
+ token: token.token,
932
+ checkout_url,
933
+ merchant_order_id: fillResult.receipt_id || null,
934
+ amount_captured: totalPrice,
935
+ card_last4: cardData.number ? cardData.number.replace(/\D/g, "").slice(-4) : undefined,
936
+ }).catch(() => null);
809
937
  }
810
938
  else {
811
939
  // Release the freshly-issued JIT token so the price funds don't sit locked on a non-payment.
812
940
  await cancelTokenRemote(token.token).catch(() => { });
941
+ // 📊 Auto-label the failed run (Primitive 2 corpus)
942
+ const label = (0, failure_taxonomy_js_1.classifyBridgeResult)(fillResult.status, fillResult.message);
943
+ if (label) {
944
+ emitCheckoutEvent({
945
+ url: checkout_url,
946
+ failure_class: label.failure_class,
947
+ step: label.step,
948
+ raw_error_type: fillResult.status,
949
+ error_message: fillResult.message,
950
+ outcome: "failed",
951
+ labeled_by: "auto",
952
+ card_bin: (0, failure_taxonomy_js_1.extractBin)(cardData.number),
953
+ });
954
+ }
813
955
  }
814
956
  return {
815
957
  content: [{ type: "text", text: JSON.stringify({
@@ -824,6 +966,14 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
824
966
  ? `✅ Confirmed: JIT card issued (limit $${issueAmount}) and order confirmed by merchant for ~$${totalPrice}.`
825
967
  : `❌ Not confirmed (${fillResult.status}): ${fillResult.message} Token released.`,
826
968
  receipt_id: fillResult.receipt_id || null,
969
+ ...(autoReceipt ? {
970
+ signed_receipt: {
971
+ receipt_id: autoReceipt.receipt?.receipt_id,
972
+ receipt_hash: autoReceipt.receipt_hash,
973
+ match: autoReceipt.receipt?.match,
974
+ verify_url: autoReceipt.verify_url || null,
975
+ },
976
+ } : {}),
827
977
  }, null, 2) }],
828
978
  isError: !fillResult.success,
829
979
  };
@@ -831,6 +981,19 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
831
981
  catch (err) {
832
982
  // ✅ FIX 8: Sanitize error message before returning to agent — avoid leaking internal paths
833
983
  const safeMsg = (err?.message || String(err)).replace(/\/.*(src|dist)\/.*\.ts/g, '[internal]').slice(0, 200);
984
+ // 📊 Label the exception path too (timeout vs unknown)
985
+ const label = (0, failure_taxonomy_js_1.classifyBridgeResult)("error", safeMsg);
986
+ if (label) {
987
+ emitCheckoutEvent({
988
+ url: checkout_url,
989
+ failure_class: label.failure_class,
990
+ step: label.step,
991
+ raw_error_type: "EXCEPTION",
992
+ error_message: safeMsg,
993
+ outcome: "failed",
994
+ labeled_by: "auto",
995
+ });
996
+ }
834
997
  return {
835
998
  content: [{ type: "text", text: JSON.stringify({
836
999
  status: "ERROR", message: safeMsg,
@@ -848,46 +1011,76 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
848
1011
  // Triggers: stuck mid pre_steps, bot blocked, selector not found, etc.
849
1012
  // Does NOT apply to: user cancelled, insufficient balance, price mismatch.
850
1013
  // ============================================================
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.", {
1014
+ 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
1015
  url: zod_1.z
853
1016
  .string()
854
1017
  .url()
855
1018
  .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'."),
1019
+ failure_class: zod_1.z
1020
+ .enum(failure_taxonomy_js_1.FAILURE_CLASSES)
1021
+ .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'."),
1022
+ step: zod_1.z
1023
+ .enum(failure_taxonomy_js_1.CHECKOUT_STEPS)
1024
+ .optional()
1025
+ .describe("Where it failed: 'navigate' (page load), 'pre_steps' (shipping/navigation steps), 'fill_form' (card fields), 'submit' (Pay button), 'confirm' (after submitting)."),
859
1026
  error_message: zod_1.z
860
1027
  .string()
861
1028
  .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
- }
1029
+ .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."),
1030
+ remediation_tried: zod_1.z
1031
+ .string()
1032
+ .optional()
1033
+ .describe("What you already tried before giving up, e.g. 'retried with submit_selector from hints'."),
1034
+ }, async ({ url, failure_class, step, error_message, remediation_tried }) => {
1035
+ emitCheckoutEvent({
1036
+ url,
1037
+ failure_class,
1038
+ step,
1039
+ error_message,
1040
+ remediation_tried,
1041
+ outcome: "failed",
1042
+ labeled_by: "agent",
1043
+ });
881
1044
  return {
882
1045
  content: [{ type: "text", text: JSON.stringify({
883
1046
  logged: true,
884
1047
  url,
885
- error_type,
886
- message: "Checkout failure logged. Admin will review and improve hints for this domain.",
1048
+ failure_class,
1049
+ message: "Checkout failure recorded with a structured label. This improves merchant hints for future runs.",
887
1050
  }, null, 2) }],
888
1051
  };
889
1052
  });
890
1053
  // ============================================================
1054
+ // TOOL: Verify a signed receipt (Primitive 3)
1055
+ // Lets the agent PROVE a purchase happened instead of claiming it.
1056
+ // Public endpoint — anyone with the receipt_id can verify.
1057
+ // ============================================================
1058
+ server.tool("verify_receipt", "Verify a Z-Zero signed receipt by id. Returns the receipt (what was authorized vs what actually settled, and any diff) plus signature validity. Use this to PROVE to the user that a purchase really happened — never claim a purchase succeeded from memory when a receipt exists.", {
1059
+ receipt_id: zod_1.z
1060
+ .string()
1061
+ .describe("The receipt_id returned by execute_payment / auto_pay_checkout (signed_receipt.receipt_id)."),
1062
+ }, async ({ receipt_id }) => {
1063
+ const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
1064
+ try {
1065
+ const resp = await fetch(`${ZZERO_API}/api/receipts/${encodeURIComponent(receipt_id)}`, {
1066
+ headers: { "x-mcp-version": version_js_2.CURRENT_MCP_VERSION },
1067
+ });
1068
+ const data = await resp.json();
1069
+ return {
1070
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
1071
+ };
1072
+ }
1073
+ catch (err) {
1074
+ return {
1075
+ content: [{ type: "text", text: JSON.stringify({
1076
+ found: false,
1077
+ message: `Could not reach receipts API: ${err?.message || "unknown error"}. The receipt may still be valid — try the public verify page.`,
1078
+ }, null, 2) }],
1079
+ isError: true,
1080
+ };
1081
+ }
1082
+ });
1083
+ // ============================================================
891
1084
  // RESOURCE: Z-ZERO Autonomous Payment SOP
892
1085
  // ============================================================
893
1086
  server.resource("Standard Operating Procedure (SOP) for Autonomous Payments", "mcp://resources/sop", {
@@ -942,8 +1135,17 @@ Tools: \`get_merchant_hints\`, \`request_payment_token\`, \`execute_payment\`, \
942
1135
  2. Follow \`pre_steps\` in YOUR browser: navigate, add to cart, submit shipping (ask the user via
943
1136
  \`request_human_approval\` if shipping info is unknown).
944
1137
  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.
1138
+ 4. **INTENT CHECK (do this yourself — it is free):** look at the checkout page one more time and compare
1139
+ it with what the user actually asked for: same items, same quantity, same variant/size/color, same
1140
+ destination. If ANYTHING differs → do NOT request a token. Fix the cart or ask the user. A mismatch
1141
+ caught now costs nothing; after the token it costs a card. If you give up on the mismatch, call
1142
+ \`report_checkout_fail\` with failure_class \`intent_mismatch\`.
1143
+ 5. \`request_payment_token(card_alias, amount = exact final total, merchant, cart = items as the user
1144
+ agreed to them, ship_to = destination)\` → one-time token, valid 1h. Passing \`cart\` makes Z-Zero SIGN
1145
+ your declared intent and bind the card to it — the user gets cryptographic proof of what was authorized.
1146
+ 6. \`execute_payment(token, checkout_url, actual_amount = final total)\`. ALWAYS pass actual_amount.
1147
+ On success you get \`signed_receipt\` (+ verify_url): a signed statement of what actually settled,
1148
+ diffed against the intent. Share verify_url with the user — prove the purchase, don't claim it.
947
1149
 
948
1150
  ⛔ Never call \`request_payment_token\` before BOTH: shipping submitted AND card fields + final total visible.
949
1151
 
@@ -994,7 +1196,8 @@ After \`confirmed\`/\`unconfirmed\`, prefer to visually confirm the order page w
994
1196
 
995
1197
  If you began PATH B (called \`get_merchant_hints\` + followed \`pre_steps\`) but cannot finish for a
996
1198
  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).
1199
+ → Call \`report_checkout_fail(url, failure_class, step, error_message)\` before giving up (url = the page you got stuck on;
1200
+ pick the closest \`failure_class\` from the tool's enum — use 'unknown' only as last resort).
998
1201
  → Do NOT call it for user-cancelled or insufficient-balance — those are not technical failures.
999
1202
 
1000
1203
  ### Known limitations
@@ -1060,6 +1263,6 @@ async function main() {
1060
1263
  await server.connect(transport);
1061
1264
  console.error(`🔐 Z-Zero MCP Server v${version_js_2.CURRENT_MCP_VERSION} running (Base + USDC, gasless via Coinbase Paymaster)...`);
1062
1265
  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");
1266
+ 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
1267
  }
1065
1268
  main().catch(console.error);
package/dist/types.d.ts CHANGED
@@ -28,6 +28,8 @@ export interface CardData {
28
28
  cvv: string;
29
29
  name: string;
30
30
  authorized_amount?: number;
31
+ intent_id?: string;
32
+ intent_hash?: string;
31
33
  error?: string;
32
34
  message?: string;
33
35
  }
@@ -2,7 +2,24 @@ import type { CardData } from "./types.js";
2
2
  export declare function listCardsRemote(): Promise<any>;
3
3
  export declare function getBalanceRemote(cardAlias: string): Promise<any>;
4
4
  export declare function getDepositAddressesRemote(): Promise<any>;
5
- export declare function issueTokenRemote(cardAlias: string, amount: number, merchant: string): Promise<any | null>;
5
+ export declare function issueTokenRemote(cardAlias: string, amount: number, merchant: string, intent?: {
6
+ cart?: Array<{
7
+ title: string;
8
+ qty: number;
9
+ unit_price?: number;
10
+ url?: string;
11
+ }>;
12
+ subtotal?: number;
13
+ currency?: string;
14
+ ship_to?: string;
15
+ }): Promise<any | null>;
16
+ export declare function postReceiptRemote(payload: {
17
+ token: string;
18
+ checkout_url: string;
19
+ merchant_order_id?: string | null;
20
+ amount_captured?: number;
21
+ card_last4?: string;
22
+ }): Promise<any | null>;
6
23
  export declare function resolveTokenRemote(token: string): Promise<CardData | null>;
7
24
  export declare function burnTokenRemote(token: string, receipt_id?: string): Promise<boolean>;
8
25
  export declare function cancelTokenRemote(token: string): Promise<any>;
@@ -13,6 +13,7 @@ exports.listCardsRemote = listCardsRemote;
13
13
  exports.getBalanceRemote = getBalanceRemote;
14
14
  exports.getDepositAddressesRemote = getDepositAddressesRemote;
15
15
  exports.issueTokenRemote = issueTokenRemote;
16
+ exports.postReceiptRemote = postReceiptRemote;
16
17
  exports.resolveTokenRemote = resolveTokenRemote;
17
18
  exports.burnTokenRemote = burnTokenRemote;
18
19
  exports.cancelTokenRemote = cancelTokenRemote;
@@ -143,7 +144,7 @@ async function getDepositAddressesRemote() {
143
144
  // ──────────────────────────────────────────────────────────────────────────────
144
145
  // Issue Token: On-chain USDC (Base) payment → JIT card
145
146
  // ──────────────────────────────────────────────────────────────────────────────
146
- async function issueTokenRemote(cardAlias, amount, merchant) {
147
+ async function issueTokenRemote(cardAlias, amount, merchant, intent) {
147
148
  // Base AA Flow (reversed from custodial):
148
149
  // 1. Create Partner card first (reservation)
149
150
  // 2. Send USDC on Base from the agent's wallet → system wallet (gasless via Coinbase Paymaster)
@@ -157,6 +158,9 @@ async function issueTokenRemote(cardAlias, amount, merchant) {
157
158
  network_id: process.env.NETWORK_ID || "base-usdc",
158
159
  session_id: `wdk-${Math.random().toString(36).substring(7)}`,
159
160
  wallet_mode: 'wdk', // Signals Dashboard to use on-chain payment path
161
+ // Primitive 1: the intent this card is derived from. Server signs it and
162
+ // returns the signed object; older servers simply ignore this field.
163
+ ...(intent ? { intent } : {}),
160
164
  });
161
165
  if (!data)
162
166
  return null;
@@ -172,10 +176,22 @@ async function issueTokenRemote(cardAlias, amount, merchant) {
172
176
  used: false,
173
177
  tx_hash: data.tx_hash,
174
178
  mode: 'wdk_noncustodial',
179
+ intent: data.intent || null, // signed intent (intent_id, hash, signature) if server supports it
175
180
  mcp_warning: data._mcp_warning || null, // Relay backend version warning to agent
176
181
  };
177
182
  }
178
183
  // ──────────────────────────────────────────────────────────────────────────────
184
+ // Receipt (Primitive 3): ask the Dashboard to build+sign a receipt for a
185
+ // CONFIRMED payment. Never blocks the payment result — caller treats null as
186
+ // "receipt unavailable" and the purchase is still fine.
187
+ // ──────────────────────────────────────────────────────────────────────────────
188
+ async function postReceiptRemote(payload) {
189
+ const data = await apiRequest('/api/receipts', 'POST', payload);
190
+ if (!data || data.error)
191
+ return null;
192
+ return data;
193
+ }
194
+ // ──────────────────────────────────────────────────────────────────────────────
179
195
  // Resolve Token: Same as custodial (returns PAN/CVV for Playwright injection)
180
196
  // ──────────────────────────────────────────────────────────────────────────────
181
197
  async function resolveTokenRemote(token) {
@@ -193,6 +209,8 @@ async function resolveTokenRemote(token) {
193
209
  cvv: data.cvv,
194
210
  name: data.name || "Z-ZERO AI AGENT",
195
211
  authorized_amount: data.authorized_amount ? Number(data.authorized_amount) : undefined,
212
+ intent_id: data.intent_id || undefined, // Primitive 1 linkage (if server supports it)
213
+ intent_hash: data.intent_hash || undefined,
196
214
  };
197
215
  }
198
216
  // ──────────────────────────────────────────────────────────────────────────────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "z-zero-mcp-server",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "description": "Z-ZERO MCP Server — Secure JIT Virtual Card Payment tools for AI Agents (Claude, Cursor, AutoGPT) — Real Single-Use Virtual Cards, settled in USDC on Base",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -10,8 +10,7 @@
10
10
  "build": "tsc",
11
11
  "start": "node dist/index.js",
12
12
  "dev": "npx tsx src/index.ts",
13
- "prepublishOnly": "npm run build",
14
- "postinstall": "echo 'IMPORTANT: Run \"npx playwright install chromium\" to enable automated checkouts.'"
13
+ "prepublishOnly": "npm run build"
15
14
  },
16
15
  "keywords": [
17
16
  "mcp",
@@ -39,10 +38,19 @@
39
38
  "README.md"
40
39
  ],
41
40
  "dependencies": {
42
- "@modelcontextprotocol/sdk": "^1.12.1",
43
- "dotenv": "^16.5.0",
44
- "playwright": "^1.52.0",
45
- "zod": "^3.25.11"
41
+ "@modelcontextprotocol/sdk": "^1.30.0",
42
+ "playwright": "^1.62.0",
43
+ "zod": "^3.25.76"
44
+ },
45
+ "overrides": {
46
+ "es-define-property": "npm:@socketregistry/es-define-property@^1.0.7",
47
+ "function-bind": "npm:@socketregistry/function-bind@^1.0.7",
48
+ "gopd": "npm:@socketregistry/gopd@^1.0.7",
49
+ "has-symbols": "npm:@socketregistry/has-symbols@^1.0.7",
50
+ "hasown": "npm:@socketregistry/hasown@^1.0.7",
51
+ "object-assign": "npm:@socketregistry/object-assign@^1.0.5",
52
+ "safer-buffer": "npm:@socketregistry/safer-buffer@^1.0.10",
53
+ "side-channel": "npm:@socketregistry/side-channel@^1.0.10"
46
54
  },
47
55
  "devDependencies": {
48
56
  "@types/node": "^22.15.21",