z-zero-mcp-server 1.7.0 → 1.9.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/README.md CHANGED
@@ -17,7 +17,8 @@ npx z-zero-mcp-server
17
17
  - ⛽ **Gasless USDC on Base** — auto-detects crypto checkout (EIP-681) and settles as a gasless USDC transfer sponsored by Coinbase Paymaster. The agent holds only USDC — no ETH, no gas UX.
18
18
  - 💳 **JIT single-use virtual cards** — amount-locked, 1-hour TTL, burned after a single use. Fiat fallback for the rest of the web.
19
19
  - 🧠 **Smart Routing + checkout intelligence** — `get_merchant_hints` serves platform-specific checkout playbooks (Shopify, Etsy, WooCommerce…).
20
- - 🔄 **Self-healing network** — every failed checkout is logged via `report_checkout_fail` and feeds back into the hints database. The system doesn't just retry; it evolves.
20
+ - ✍️ **Signed intent + signed receipt** — the card is bound to a signed statement of *what it is for*, and every confirmed purchase returns a signed receipt with a diff against that intent. The agent can **prove** a purchase instead of claiming one (`verify_receipt`, public verify page).
21
+ - 🔄 **Structured failure labels** — failed checkouts are labeled with a fixed 14-class `failure_class` (automatically, not only when an agent remembers to report) and stored as evidence for the merchant knowledge base. Facts are promoted into shared hints only after a later outcome or review verifies them.
21
22
 
22
23
  ---
23
24
 
@@ -146,8 +147,8 @@ Older self-hosted backends without the rotate endpoint keep working — the past
146
147
 
147
148
  | Tool | Description |
148
149
  |------|-------------|
149
- | `request_payment_token` | Issue a JIT single-use virtual-card token for a specific amount (1hr TTL) |
150
- | `execute_payment` | Auto-fill checkout form using a payment token via Playwright |
150
+ | `request_payment_token` | Issue a JIT single-use virtual-card token for a specific amount (1hr TTL). Pass `cart` + `ship_to` and the card is bound to a **signed intent** |
151
+ | `execute_payment` | Auto-fill checkout form using a payment token via Playwright. Returns a **signed receipt** on confirmed payments |
151
152
  | `cancel_payment_token` | Cancel an unused token and refund to wallet |
152
153
  | `request_human_approval` | Pause and request human confirmation before proceeding |
153
154
 
@@ -157,12 +158,82 @@ Older self-hosted backends without the rotate endpoint keep working — the past
157
158
  |------|-------------|
158
159
  | `auto_pay_checkout` | Fully autonomous checkout — auto-detects Web3 or Fiat and completes payment |
159
160
  | `get_merchant_hints` | Fetch platform-specific checkout playbook (pre-steps + selectors) from Knowledge Base |
160
- | `report_checkout_fail` | Log a failed checkout URL for admin review (self-healing feedback loop) |
161
+ | `report_checkout_fail` | Report a failed checkout with a **structured `failure_class`** (14-class enum) — feeds the self-healing loop |
162
+ | `verify_receipt` | Verify a signed receipt by id — prove a purchase happened instead of claiming it |
161
163
 
162
164
  > 📖 **Note:** Version checking is handled automatically in each API call. No separate tool needed.
163
165
 
164
166
  ---
165
167
 
168
+ ## Agent primitives (v1.7.0)
169
+
170
+ Three things an agent can do here that it cannot do with a normal virtual card.
171
+
172
+ ### 1. Signed intent — the card knows what it is for
173
+
174
+ Pass the cart when you request a token:
175
+
176
+ ```jsonc
177
+ request_payment_token({
178
+ card_alias: "Card_01",
179
+ amount: 44.00,
180
+ merchant: "etsy.com",
181
+ cart: [{ title: "Ceramic mug — matte white", qty: 2, unit_price: 18.50 }],
182
+ ship_to: "12 Nguyen Hue, District 1, Ho Chi Minh City, VN"
183
+ })
184
+ ```
185
+
186
+ Z-ZERO signs that statement (EIP-191) and binds it to the card. The user gets
187
+ cryptographic proof of **what this card was authorized to buy** — not just how
188
+ much it could spend. The shipping address is stored as a hash, never raw.
189
+
190
+ **Before you request a token, compare the checkout page with what the user actually
191
+ asked for** — same items, same quantity, same variant, same destination. A mismatch
192
+ you catch there costs nothing. After the token, it costs a card.
193
+
194
+ ### 2. Signed receipt — prove the purchase, don't claim it
195
+
196
+ On a confirmed payment you get back:
197
+
198
+ ```jsonc
199
+ "signed_receipt": {
200
+ "receipt_id": "8ea36791-…",
201
+ "receipt_hash": "0x…",
202
+ "match": { "total": "over", "domain": "ok" },
203
+ "diff": [{ "field": "total", "expected": 44.00, "observed": 46.75 }],
204
+ "verify_url": "https://z-zero.xyz/receipt/8ea36791-…"
205
+ }
206
+ ```
207
+
208
+ `diff` is the part that matters: it is what the merchant actually did versus what
209
+ was authorized. Share `verify_url` with the user — the page is public and anyone
210
+ can check it. Verification is three checks: the signature is valid, the signer is
211
+ Z-ZERO, and the fields shown still hash to what was signed (so editing the record
212
+ afterwards is detectable, including by us).
213
+
214
+ **What a valid receipt does and does not prove.** It proves the record is signed by
215
+ Z-ZERO and unaltered. It does not by itself prove the merchant charged what the
216
+ receipt says — most fields start life as the agent's reading of a web page. Every
217
+ receipt therefore carries `provenance` per field: `zzero_issued` (the limit we set),
218
+ `issuer_captured` (confirmed by the card issuer's capture webhook — settlement
219
+ evidence), `agent_reported` (unverified), `human_verified`. Until the capture webhook
220
+ lands, this is a **signed execution receipt**, not settlement proof, and it says so.
221
+
222
+ ### 3. Structured failure classes — every failure teaches the network
223
+
224
+ `report_checkout_fail` takes a fixed enum, not free text:
225
+
226
+ `card_declined_issuer` · `card_declined_bin_block` · `avs_mismatch` · `3ds_required` ·
227
+ `bot_detected` · `form_changed` · `price_changed` · `out_of_stock` ·
228
+ `shipping_unsupported` · `login_required` · `timeout` · `outcome_unconfirmed` ·
229
+ `intent_mismatch` · `unknown`
230
+
231
+ Failed runs are also labeled automatically from the browser outcome, so the network
232
+ learns even when nobody remembers to report. Card numbers are redacted at capture —
233
+ they never reach a log, screenshot or DOM dump.
234
+
235
+ ---
236
+
166
237
  ## REST API Reference
167
238
 
168
239
  The Z-ZERO backend is hosted at `https://z-zero.xyz`. All endpoints require a `Bearer` token using your Passport Key.
@@ -19,7 +19,14 @@ export declare function postReceiptRemote(payload: {
19
19
  merchant_order_id?: string | null;
20
20
  amount_captured?: number;
21
21
  card_last4?: string;
22
+ /** The purpose record — signed into the receipt alongside the outcome. */
23
+ recheck?: {
24
+ page_shows: string;
25
+ decision: "go" | "pause";
26
+ why?: string;
27
+ };
22
28
  }): Promise<any | null>;
29
+ export declare function getTokenPurposeRemote(token: string): Promise<any>;
23
30
  export declare function resolveTokenRemote(token: string): Promise<CardData | null>;
24
31
  export declare function burnTokenRemote(token: string, receipt_id?: string): Promise<boolean>;
25
32
  export declare function cancelTokenRemote(token: string): Promise<any>;
@@ -1,25 +1,25 @@
1
1
  "use strict";
2
- // Z-ZERO WDK Backend — Non-Custodial Module
3
- // Drop-in replacement for api_backend.ts when Z_ZERO_WALLET_MODE=wdk
4
- // Exports IDENTICAL function signatures so index.ts can swap backends without any changes.
2
+ // Z-ZERO Base Backend (formerly wdk_backend.ts — renamed in the 05/08/2026 WDK purge;
3
+ // the Tether-WDK/Tron era it was named for is gone, this has been Base + USDC throughout).
5
4
  //
6
- // Key differences from custodial api_backend.ts:
7
- // - getBalanceRemote() → reads stablecoin (USDC) balance on-chain on Base (not from Supabase wallets table)
8
- // - getDepositAddressesRemote() → returns the Base wallet address (not HD custodial address)
9
- // - issueTokenRemote() → sends USDC on Base first, THEN issues JIT card
10
- // - cancelTokenRemote() → triggers on-chain USDC refund back to user's Base wallet
5
+ // - getBalanceRemote() → on-chain USDC balance on Base via /api/wallet/balance
6
+ // - getDepositAddressesRemote() → the agent's Base smart-account address
7
+ // - issueTokenRemote() → sends USDC on Base first, THEN issues the JIT card
8
+ // - cancelTokenRemote() → on-chain USDC refund back to the user's Base wallet
11
9
  Object.defineProperty(exports, "__esModule", { value: true });
12
10
  exports.listCardsRemote = listCardsRemote;
13
11
  exports.getBalanceRemote = getBalanceRemote;
14
12
  exports.getDepositAddressesRemote = getDepositAddressesRemote;
15
13
  exports.issueTokenRemote = issueTokenRemote;
16
14
  exports.postReceiptRemote = postReceiptRemote;
15
+ exports.getTokenPurposeRemote = getTokenPurposeRemote;
17
16
  exports.resolveTokenRemote = resolveTokenRemote;
18
17
  exports.burnTokenRemote = burnTokenRemote;
19
18
  exports.cancelTokenRemote = cancelTokenRemote;
20
19
  exports.refundUnderspendRemote = refundUnderspendRemote;
21
20
  const key_store_js_1 = require("./lib/key-store.js");
22
- const API_BASE_URL = process.env.Z_ZERO_API_BASE_URL || "https://z-zero.xyz";
21
+ const api_base_js_1 = require("./lib/api-base.js");
22
+ const API_BASE_URL = (0, api_base_js_1.resolveApiBaseUrl)();
23
23
  const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
24
24
  // Injected at build time — always reflects the actual running version
25
25
  const version_js_1 = require("./version.js");
@@ -46,10 +46,17 @@ async function apiRequest(endpoint, method = 'GET', body = null) {
46
46
  "X-MCP-Version": version_js_1.CURRENT_MCP_VERSION,
47
47
  },
48
48
  body: body ? JSON.stringify(body) : null,
49
+ // Never let fetch follow a redirect while carrying the Passport Key:
50
+ // it would either drop the header (silent 401) or hand the key to
51
+ // whatever host the redirect names. Surface it instead.
52
+ redirect: "manual",
49
53
  });
54
+ if (res.status >= 300 && res.status < 400) {
55
+ return redirectError(url, res);
56
+ }
50
57
  if (!res.ok) {
51
58
  const err = await res.json().catch(() => ({ error: res.statusText }));
52
- return { error: err.error || "API_ERROR", message: err.message || err.error || res.statusText };
59
+ return httpError(res, err);
53
60
  }
54
61
  return await res.json();
55
62
  }
@@ -57,6 +64,36 @@ async function apiRequest(endpoint, method = 'GET', body = null) {
57
64
  return { error: "NETWORK_ERROR", message: err.message };
58
65
  }
59
66
  }
67
+ // Normalise a failed HTTP response into an error object callers can branch on.
68
+ // A 401 becomes AUTH_REQUIRED here — at the source — so no caller can mistake a
69
+ // rejected key for a missing resource. `status` rides along so callers can tell
70
+ // 404 (resource genuinely absent) from 500 (server broke).
71
+ // A redirect on an authenticated call is a configuration bug, not an auth bug.
72
+ // Say so, because the 401 it would otherwise become reads as "your key is dead".
73
+ function redirectError(url, res) {
74
+ const target = res.headers.get("location") || "another host";
75
+ return {
76
+ error: "BASE_URL_REDIRECT",
77
+ status: res.status,
78
+ message: `${url} redirected (${res.status}) to ${target}. The Passport Key was NOT forwarded — ` +
79
+ `a redirected request loses its Authorization header, which shows up as a false 401. ` +
80
+ `Set Z_ZERO_API_BASE_URL to https://z-zero.xyz in your MCP config.`,
81
+ };
82
+ }
83
+ function httpError(res, err) {
84
+ if (res.status === 401) {
85
+ return {
86
+ error: "AUTH_REQUIRED",
87
+ status: 401,
88
+ message: err?.message || err?.error || "Passport Key is missing, invalid, or revoked.",
89
+ };
90
+ }
91
+ return {
92
+ error: err?.error || "API_ERROR",
93
+ status: res.status,
94
+ message: err?.message || err?.error || res.statusText,
95
+ };
96
+ }
60
97
  async function internalApiRequest(endpoint, method, body) {
61
98
  // Auth is the Bearer Passport Key — the server dropped the x-internal-secret
62
99
  // gate on /resolve and /burn (redundant to per-user token ownership, Jul 2026).
@@ -74,10 +111,17 @@ async function internalApiRequest(endpoint, method, body) {
74
111
  "X-MCP-Version": version_js_1.CURRENT_MCP_VERSION,
75
112
  },
76
113
  body: body ? JSON.stringify(body) : null,
114
+ // Never let fetch follow a redirect while carrying the Passport Key:
115
+ // it would either drop the header (silent 401) or hand the key to
116
+ // whatever host the redirect names. Surface it instead.
117
+ redirect: "manual",
77
118
  });
119
+ if (res.status >= 300 && res.status < 400) {
120
+ return redirectError(url, res);
121
+ }
78
122
  if (!res.ok) {
79
123
  const err = await res.json().catch(() => ({ error: res.statusText }));
80
- return { error: err.error || "API_ERROR", message: err.message || err.error || res.statusText };
124
+ return httpError(res, err);
81
125
  }
82
126
  return await res.json();
83
127
  }
@@ -89,24 +133,50 @@ async function internalApiRequest(endpoint, method, body) {
89
133
  // Core API: Same as custodial (cards, tokens still managed by Dashboard)
90
134
  // ──────────────────────────────────────────────────────────────────────────────
91
135
  async function listCardsRemote() {
92
- // Calls /api/tokens/cards — but that route returns balance from Supabase.
93
- // For WDK mode, the Dashboard API must read wallet_mode and return on-chain balance.
94
- // This is handled server-side in the updated /api/tokens/cards route.
136
+ // /api/tokens/cards returns card aliases + the on-chain Base USDC balance.
95
137
  return await apiRequest('/api/tokens/cards', 'GET');
96
138
  }
97
139
  // ──────────────────────────────────────────────────────────────────────────────
98
140
  // Balance: On-chain USDC (stablecoin) on Base via Dashboard API
99
141
  // ──────────────────────────────────────────────────────────────────────────────
100
- async function getBalanceRemote(cardAlias) {
101
- // Call Dashboard to get the agent's Base wallet balance (Dashboard resolves user from
102
- // passport key, finds the connected Base wallet, queries on-chain USDC balance)
103
- const data = await apiRequest('/api/wdk/balance', 'GET');
104
- if (data?.error) {
142
+ // Turn a failed /api/wallet/balance call into an honest, actionable failure.
143
+ // Returns null when the call succeeded.
144
+ //
145
+ // Why this exists: this used to collapse EVERY error into "Base wallet not
146
+ // connected", so a user whose Passport Key had been revoked was sent to the
147
+ // wallet page to fix a problem that was about the key. Only a genuine 404 means
148
+ // "no wallet" — everything else must keep its own identity.
149
+ function walletLookupFailure(data) {
150
+ if (!data?.error)
151
+ return null;
152
+ if (data.error === "AUTH_REQUIRED") {
153
+ return { error: "AUTH_REQUIRED", message: data.message };
154
+ }
155
+ if (data.error === "NETWORK_ERROR") {
156
+ return {
157
+ error: "NETWORK_ERROR",
158
+ message: `Could not reach ${API_BASE_URL}: ${data.message}`,
159
+ };
160
+ }
161
+ if (data.status === 404) {
105
162
  return {
106
- error: true,
107
- message: 'Base wallet not connected. Create one at https://z-zero.xyz/dashboard/agent-wallet'
163
+ error: "NO_WALLET",
164
+ message: 'Base wallet not connected. Create one at https://z-zero.xyz/dashboard/agent-wallet',
108
165
  };
109
166
  }
167
+ return {
168
+ error: data.error,
169
+ status: data.status,
170
+ message: data.message || 'Could not read your Base wallet balance.',
171
+ };
172
+ }
173
+ async function getBalanceRemote(cardAlias) {
174
+ // Call Dashboard to get the agent's Base wallet balance (Dashboard resolves user from
175
+ // passport key, finds the connected Base wallet, queries on-chain USDC balance)
176
+ const data = await apiRequest('/api/wallet/balance', 'GET');
177
+ const failure = walletLookupFailure(data);
178
+ if (failure)
179
+ return failure;
110
180
  return {
111
181
  wallet_balance: data.base_usdc_balance ?? data.balance_usdt,
112
182
  currency: 'USDC',
@@ -120,13 +190,10 @@ async function getBalanceRemote(cardAlias) {
120
190
  // Deposit Address: the agent's Base smart-account address (single chain)
121
191
  // ──────────────────────────────────────────────────────────────────────────────
122
192
  async function getDepositAddressesRemote() {
123
- const data = await apiRequest('/api/wdk/balance', 'GET');
124
- if (data?.error) {
125
- return {
126
- error: true,
127
- message: 'Base wallet not connected. Create one at https://z-zero.xyz/dashboard/agent-wallet'
128
- };
129
- }
193
+ const data = await apiRequest('/api/wallet/balance', 'GET');
194
+ const failure = walletLookupFailure(data);
195
+ if (failure)
196
+ return failure;
130
197
  const balance = data.base_usdc_balance ?? data.balance_usdt;
131
198
  return {
132
199
  cards: [{ alias: 'base-wallet', balance, currency: 'USDC' }],
@@ -134,7 +201,7 @@ async function getDepositAddressesRemote() {
134
201
  base: data.address,
135
202
  note: 'Send USDC (or any supported stablecoin) on Base to your wallet. Gasless spending via the Coinbase Paymaster.'
136
203
  },
137
- wdk_wallet: {
204
+ base_wallet: {
138
205
  address: data.address,
139
206
  chain: data.chain || 'base',
140
207
  balance_usdt: balance
@@ -156,8 +223,7 @@ async function issueTokenRemote(cardAlias, amount, merchant, intent) {
156
223
  merchant,
157
224
  device_fingerprint: `mcp-base-${process.platform}-${process.arch}`,
158
225
  network_id: process.env.NETWORK_ID || "base-usdc",
159
- session_id: `wdk-${Math.random().toString(36).substring(7)}`,
160
- wallet_mode: 'wdk', // Signals Dashboard to use on-chain payment path
226
+ session_id: `base-${Math.random().toString(36).substring(7)}`,
161
227
  // Primitive 1: the intent this card is derived from. Server signs it and
162
228
  // returns the signed object; older servers simply ignore this field.
163
229
  ...(intent ? { intent } : {}),
@@ -175,7 +241,7 @@ async function issueTokenRemote(cardAlias, amount, merchant, intent) {
175
241
  ttl_seconds: 3600,
176
242
  used: false,
177
243
  tx_hash: data.tx_hash,
178
- mode: 'wdk_noncustodial',
244
+ mode: 'base_usdc',
179
245
  intent: data.intent || null, // signed intent (intent_id, hash, signature) if server supports it
180
246
  mcp_warning: data._mcp_warning || null, // Relay backend version warning to agent
181
247
  };
@@ -194,6 +260,14 @@ async function postReceiptRemote(payload) {
194
260
  // ──────────────────────────────────────────────────────────────────────────────
195
261
  // Resolve Token: Same as custodial (returns PAN/CVV for Playwright injection)
196
262
  // ──────────────────────────────────────────────────────────────────────────────
263
+ // ──────────────────────────────────────────────────────────────────────────────
264
+ // Purpose: the criteria this card was issued against, straight from the server.
265
+ // Deliberately NOT part of resolve — resolve pulls a real PAN from the issuer,
266
+ // and asking "what was this for?" must never cost a card fetch.
267
+ // ──────────────────────────────────────────────────────────────────────────────
268
+ async function getTokenPurposeRemote(token) {
269
+ return await apiRequest('/api/tokens/purpose', 'POST', { token });
270
+ }
197
271
  async function resolveTokenRemote(token) {
198
272
  const data = await internalApiRequest('/api/tokens/resolve', 'POST', { token });
199
273
  if (!data || data.error)
@@ -221,7 +295,6 @@ async function burnTokenRemote(token, receipt_id) {
221
295
  token,
222
296
  receipt_id,
223
297
  success: true,
224
- wallet_mode: 'wdk', // Signals Dashboard to refund underspend on-chain
225
298
  });
226
299
  return !!data && !data.error;
227
300
  }
@@ -231,7 +304,6 @@ async function burnTokenRemote(token, receipt_id) {
231
304
  async function cancelTokenRemote(token) {
232
305
  const data = await apiRequest('/api/tokens/cancel', 'POST', {
233
306
  token,
234
- wallet_mode: 'wdk', // Triggers on-chain USDC refund
235
307
  });
236
308
  if (data?.error)
237
309
  return data;
@@ -247,5 +319,5 @@ async function cancelTokenRemote(token) {
247
319
  // ──────────────────────────────────────────────────────────────────────────────
248
320
  async function refundUnderspendRemote(token, actualSpent) {
249
321
  // console.error (NOT console.log) — stdout is the MCP stdio transport; logging there corrupts the protocol.
250
- console.error(`[WDK MCP] Token ${token} burned. Actual spent: $${actualSpent}. On-chain refund handled by Dashboard.`);
322
+ console.error(`[Z-ZERO MCP] Token ${token} burned. Actual spent: $${actualSpent}. On-chain refund handled by Dashboard.`);
251
323
  }
@@ -23,7 +23,13 @@ export interface CheckoutEvent {
23
23
  intent_id?: string;
24
24
  evidence_ref?: string;
25
25
  }
26
- /** Mask any 12–19 digit sequence (with optional space/dash separators) and CVV-looking patterns. */
26
+ /**
27
+ * Mask any 12–19 digit sequence (with optional space/dash separators) and CVV-looking patterns.
28
+ *
29
+ * NFKC first: full-width digits (4242…) read as a card number to a human and
30
+ * to anything downstream, but slip past an ASCII \d regex. Normalising folds
31
+ * them to ASCII so one pattern catches both forms.
32
+ */
27
33
  export declare function redactCardData(text: string): string;
28
34
  /** First 6 digits of a PAN — safe to log (BIN is not cardholder data). */
29
35
  export declare function extractBin(cardNumber: string | undefined): string | undefined;
@@ -50,11 +50,18 @@ exports.CHECKOUT_STEPS = [
50
50
  // Redaction — 🔴 redact at capture time, never after.
51
51
  // Screenshots/DOM/HAR/messages must never contain PAN or CVV.
52
52
  // ------------------------------------------------------------
53
- /** Mask any 12–19 digit sequence (with optional space/dash separators) and CVV-looking patterns. */
53
+ /**
54
+ * Mask any 12–19 digit sequence (with optional space/dash separators) and CVV-looking patterns.
55
+ *
56
+ * NFKC first: full-width digits (4242…) read as a card number to a human and
57
+ * to anything downstream, but slip past an ASCII \d regex. Normalising folds
58
+ * them to ASCII so one pattern catches both forms.
59
+ */
54
60
  function redactCardData(text) {
55
61
  if (!text)
56
62
  return text;
57
63
  return text
64
+ .normalize("NFKC")
58
65
  // PAN: 12-19 digits, allowing spaces or dashes between groups
59
66
  .replace(/\b(?:\d[ -]?){12,19}\b/g, "[PAN_REDACTED]")
60
67
  // CVV mentioned next to a 3-4 digit number
package/dist/index.js CHANGED
@@ -46,8 +46,8 @@ 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;
@@ -57,7 +57,8 @@ const postReceiptRemote = activeBackend.postReceiptRemote;
57
57
  const getBalanceRemote = activeBackend.getBalanceRemote;
58
58
  const listCardsRemote = activeBackend.listCardsRemote;
59
59
  const getDepositAddressesRemote = activeBackend.getDepositAddressesRemote;
60
- console.error(`[Z-ZERO MCP] 🚀 Pure WDK Non-Custodial Mode`);
60
+ const getTokenPurposeRemote = activeBackend.getTokenPurposeRemote;
61
+ console.error(`[Z-ZERO MCP] 🚀 Base + USDC (non-custodial, gasless)`);
61
62
  // ────────────────────────────────────────────────────────────────────────────
62
63
  const playwright_bridge_js_1 = require("./playwright_bridge.js");
63
64
  const web3_detector_js_1 = require("./lib/web3-detector.js");
@@ -65,6 +66,7 @@ const extract_total_price_js_1 = require("./lib/extract-total-price.js");
65
66
  const playwright_1 = require("playwright");
66
67
  const key_store_js_1 = require("./lib/key-store.js"); // ✅ Hot-Swap + rotate-on-connect
67
68
  const url_guard_js_1 = require("./lib/url-guard.js");
69
+ const api_base_js_1 = require("./lib/api-base.js");
68
70
  const failure_taxonomy_js_1 = require("./failure_taxonomy.js");
69
71
  /** Masked, non-reconstructable hint for a secret key (for debug output only). */
70
72
  function maskKey(key) {
@@ -81,7 +83,7 @@ function maskKey(key) {
81
83
  // labeled data even when the agent never calls report_checkout_fail.
82
84
  // ============================================================
83
85
  function emitCheckoutEvent(evt) {
84
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
86
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
85
87
  const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
86
88
  const body = {
87
89
  ...evt,
@@ -111,26 +113,40 @@ const server = new mcp_js_1.McpServer({
111
113
  version: version_js_2.CURRENT_MCP_VERSION,
112
114
  });
113
115
  // ============================================================
116
+ // SHARED: the one AUTH_REQUIRED reply
117
+ // ============================================================
118
+ // A 401 can mean the key is missing, mistyped, revoked, or already rotated onto
119
+ // another machine — the server cannot tell us which, so the message must not
120
+ // claim one of them. It also must not send the reader to a restart: set_api_key
121
+ // activates a new key in place (since 1.5.0).
122
+ function authRequiredResult(detail) {
123
+ return {
124
+ content: [{
125
+ type: "text",
126
+ text: "❌ AUTHENTICATION REQUIRED: Z-ZERO rejected your Passport Key — it is missing, invalid, or has been revoked.\n" +
127
+ (detail ? `Server said: ${detail}\n` : "") +
128
+ "\n👉 Get a fresh key: https://z-zero.xyz/dashboard/agents\n" +
129
+ "👉 Then call set_api_key with it — no restart needed. (Or set Z_ZERO_API_KEY in your MCP config and restart.)\n" +
130
+ "Note: one key belongs to one machine — it rotates on first connect, so a key already used elsewhere will not work here."
131
+ }],
132
+ isError: true,
133
+ };
134
+ }
135
+ // ============================================================
114
136
  // TOOL 1: List available cards (safe - no sensitive data)
115
137
  // ============================================================
116
138
  server.tool("list_cards", "List all available virtual card aliases and their balances. No sensitive data is returned.", {}, async () => {
117
139
  const data = await listCardsRemote();
118
- if (data?.error === "AUTH_REQUIRED") {
119
- return {
120
- content: [{
121
- type: "text",
122
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
123
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents\n" +
124
- "👉 Then SET it as the 'Z_ZERO_API_KEY' environment variable in your AI tool (Claude Desktop/Cursor) and RESTART the tool."
125
- }],
126
- isError: true
127
- };
128
- }
140
+ if (data?.error === "AUTH_REQUIRED")
141
+ return authRequiredResult(data.message);
129
142
  if (data?.error) {
130
143
  return {
131
144
  content: [{
132
145
  type: "text",
133
- text: `❌ API ERROR: ${data.message || data.error}\n\nCould not fetch cards. Please verify your Passport Key is correct.`
146
+ // Don't blame the key here — AUTH_REQUIRED was already handled
147
+ // above, so whatever reaches this branch is something else
148
+ // (redirected base URL, deactivated agent, server error).
149
+ text: `❌ API ERROR: ${data.message || data.error}\n\nCould not fetch cards.`
134
150
  }],
135
151
  isError: true
136
152
  };
@@ -161,23 +177,18 @@ server.tool("check_balance", "Check spendable USD balance for a card alias. For
161
177
  .describe("The alias of the card to check, e.g. 'Card_01'"),
162
178
  }, async ({ card_alias }) => {
163
179
  const data = await getBalanceRemote(card_alias);
164
- if (data?.error === "AUTH_REQUIRED") {
165
- return {
166
- content: [{
167
- type: "text",
168
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
169
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents\n" +
170
- "👉 Then SET it as the 'Z_ZERO_API_KEY' environment variable and RESTART."
171
- }],
172
- isError: true
173
- };
174
- }
180
+ if (data?.error === "AUTH_REQUIRED")
181
+ return authRequiredResult(data.message);
175
182
  if (!data || data.error) {
183
+ // Pass the backend's own reason through — "card not found" was being
184
+ // printed over real causes (no wallet, network down, server error).
185
+ const reason = data?.message
186
+ || `Card "${card_alias}" not found. Use list_cards to see available cards.`;
176
187
  return {
177
188
  content: [
178
189
  {
179
190
  type: "text",
180
- text: `Card "${card_alias}" not found or API issue. Use list_cards to see available cards.`,
191
+ text: reason,
181
192
  },
182
193
  ],
183
194
  isError: true,
@@ -197,21 +208,12 @@ server.tool("check_balance", "Check spendable USD balance for a card alias. For
197
208
  // ============================================================
198
209
  server.tool("get_deposit_addresses", "Get your Base deposit address to top up your wallet with USDC (or any supported stablecoin on Base).", {}, async () => {
199
210
  const data = await getDepositAddressesRemote();
200
- if (data?.error === "AUTH_REQUIRED") {
201
- return {
202
- content: [{
203
- type: "text",
204
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
205
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents\n" +
206
- "👉 Then SET it as the 'Z_ZERO_API_KEY' environment variable and RESTART."
207
- }],
208
- isError: true
209
- };
210
- }
211
+ if (data?.error === "AUTH_REQUIRED")
212
+ return authRequiredResult(data.message);
211
213
  // ── Base smart-account wallet ─────────────────────────────────────────
212
- if (data?.wdk_wallet?.address) {
213
- const walletAddr = data.wdk_wallet.address;
214
- const balance = data.wdk_wallet.balance_usdt ?? 0;
214
+ if (data?.base_wallet?.address) {
215
+ const walletAddr = data.base_wallet.address;
216
+ const balance = data.base_wallet.balance_usdt ?? 0;
215
217
  return {
216
218
  content: [{
217
219
  type: "text",
@@ -227,11 +229,14 @@ server.tool("get_deposit_addresses", "Get your Base deposit address to top up yo
227
229
  }],
228
230
  };
229
231
  }
230
- // No Base wallet connected
232
+ // Anything else: say what actually went wrong. Only a real NO_WALLET
233
+ // sends the reader to the wallet page — a network or server failure that
234
+ // pointed there would have them building a wallet they already have.
231
235
  return {
232
236
  content: [{
233
237
  type: "text",
234
- text: "No Base wallet found. Please create one at https://z-zero.xyz/dashboard/agent-wallet",
238
+ text: data?.message
239
+ || "No Base wallet found. Please create one at https://z-zero.xyz/dashboard/agent-wallet",
235
240
  }],
236
241
  isError: true,
237
242
  };
@@ -240,7 +245,7 @@ server.tool("get_deposit_addresses", "Get your Base deposit address to top up yo
240
245
  // TOOL 3: Request a temporary payment token (issues secure JIT card)
241
246
  // ============================================================
242
247
  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.", {
248
+ "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. Pass `criteria` too: the few things the owner actually cared about, which this purchase gets scored against at payment time.", {
244
249
  card_alias: zod_1.z
245
250
  .string()
246
251
  .describe("Which card to charge, e.g. 'Card_01'"),
@@ -266,27 +271,39 @@ server.tool("request_payment_token", "Request a single-use JIT virtual card ($1
266
271
  .string()
267
272
  .optional()
268
273
  .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
274
+ criteria: zod_1.z
275
+ .object({
276
+ source: zod_1.z
277
+ .enum(["user_link", "user_described", "agent_chose"])
278
+ .describe("Where the choice of THIS product came from. 'user_link' = they gave you the link, so the product is their pick, not yours."),
279
+ items: zod_1.z
280
+ .array(zod_1.z.object({
281
+ key: zod_1.z.string().describe("Short name for the attribute, e.g. item_type, max_price, colour, size, ship_time."),
282
+ stated: zod_1.z.string().describe("What the owner said about it, in their terms."),
283
+ }))
284
+ .min(1)
285
+ .max(12),
286
+ })
287
+ .optional()
288
+ .describe("RECOMMENDED. The things this purchase will be judged against later — write ONLY what the owner actually stated. " +
289
+ "Attributes like price, colour, size, product type or delivery time are examples of the KIND of thing that belongs here, " +
290
+ "not a checklist to fill: an owner who said \"a hat, $10\" gave you exactly two, and inventing three more would mark a good " +
291
+ "purchase as wrong. If they changed their mind, record where they LANDED, not the journey. " +
292
+ "This list is locked and signed now, before the outcome is known, and you will be asked to score against it at payment time."),
293
+ }, async ({ card_alias, amount, merchant, cart, ship_to, criteria }) => {
294
+ const intentInput = (cart && cart.length) || ship_to || criteria
271
295
  ? {
272
296
  cart,
273
297
  subtotal: cart?.every(i => typeof i.unit_price === "number")
274
298
  ? Math.round(cart.reduce((s, i) => s + i.unit_price * i.qty, 0) * 100) / 100
275
299
  : undefined,
276
300
  ship_to,
301
+ criteria,
277
302
  }
278
303
  : undefined;
279
304
  const token = await issueTokenRemote(card_alias, amount, merchant, intentInput);
280
- if (token?.error === "AUTH_REQUIRED") {
281
- return {
282
- content: [{
283
- type: "text",
284
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
285
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents"
286
- }],
287
- isError: true
288
- };
289
- }
305
+ if (token?.error === "AUTH_REQUIRED")
306
+ return authRequiredResult(token.message);
290
307
  if (!token || token.error) {
291
308
  // Show actual API error if available (e.g. 429 max cards, 402 insufficient)
292
309
  if (token?.message) {
@@ -299,7 +316,11 @@ server.tool("request_payment_token", "Request a single-use JIT virtual card ($1
299
316
  };
300
317
  }
301
318
  const balanceData = await getBalanceRemote(card_alias);
302
- const balance = balanceData?.balance;
319
+ // getBalanceRemote returns `wallet_balance` — reading `balance` here
320
+ // always came back undefined, so this fell through to the vague
321
+ // "not found / key invalid / limit exceeded" line even when the real
322
+ // reason was simply an empty wallet.
323
+ const balance = balanceData?.error ? undefined : balanceData?.wallet_balance;
303
324
  return {
304
325
  content: [
305
326
  {
@@ -349,7 +370,7 @@ server.tool("get_merchant_hints", "Get merchant navigation flow for a domain or
349
370
  .string()
350
371
  .describe("The main domain of the checkout page, e.g. 'amazon.com' or 'shopify.com'. Strip 'www.' prefix."),
351
372
  }, async ({ domain }) => {
352
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
373
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
353
374
  const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
354
375
  try {
355
376
  const resp = await fetch(`${ZZERO_API}/api/checkout-hints?domain=${encodeURIComponent(domain)}&fields=merchant`, {
@@ -380,7 +401,7 @@ server.tool("get_merchant_hints", "Get merchant navigation flow for a domain or
380
401
  // ============================================================
381
402
  // TOOL 4b: Execute payment (The "Invisible Hand")
382
403
  // ============================================================
383
- 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.", {
404
+ server.tool("execute_payment", "Execute a payment with a one-time token. TWO CALLS: call it first WITHOUT `recheck` — nothing is charged and it hands you what the owner actually asked for, locked when the card was issued; look at the page again, then call it a second time with `recheck` to pay or to pause. Then Z-Zero opens a headless browser, injects the card (you NEVER see the PAN), clicks Pay, and 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.", {
384
405
  token: zod_1.z
385
406
  .string()
386
407
  .describe("The temporary payment token from request_payment_token"),
@@ -405,7 +426,86 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
405
426
  })
406
427
  .optional()
407
428
  .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."),
408
- }, async ({ token, checkout_url, actual_amount, hints }) => {
429
+ recheck: zod_1.z
430
+ .object({
431
+ page_shows: zod_1.z
432
+ .string()
433
+ .min(1)
434
+ .describe("What is ACTUALLY on the page in front of you right now — item, variant, quantity, final total. Describe it, do not summarise it as 'looks right'."),
435
+ decision: zod_1.z
436
+ .enum(["go", "pause"])
437
+ .describe("go = pay it. pause = something is off; nothing is charged, the card is not typed in, the money stays put and you tell your owner."),
438
+ why: zod_1.z
439
+ .string()
440
+ .optional()
441
+ .describe("Required when you pause: what did not line up."),
442
+ })
443
+ .optional()
444
+ .describe("Your answer to the purpose check. Omit it on the first call — this tool will hand you the owner's locked criteria to read, then you call again with this."),
445
+ }, async ({ token, checkout_url, actual_amount, hints, recheck }) => {
446
+ // ── Purpose check: the last look before there is no way back ─────────
447
+ // Called with no `recheck`, this tool does not pay. It hands back the
448
+ // criteria the owner stated, locked at issue, and asks for an answer.
449
+ // The question comes from the server on purpose: an agent that quotes it
450
+ // from its own memory can soften it until anything matches.
451
+ // No browser, no PAN, nothing spent — asking is free.
452
+ if (!recheck) {
453
+ const purpose = await getTokenPurposeRemote(token);
454
+ if (purpose?.error === "AUTH_REQUIRED")
455
+ return authRequiredResult(purpose.message);
456
+ // A dead token should say so HERE, not send the agent off to look at a
457
+ // page and come back for a second call that was always going to fail.
458
+ if (purpose?.error) {
459
+ return {
460
+ content: [{
461
+ type: "text",
462
+ text: JSON.stringify({
463
+ success: false,
464
+ status: "invalid_token",
465
+ nothing_charged: true,
466
+ message: purpose.message || "Token is invalid, expired, cancelled, or already used. Request a new one.",
467
+ }, null, 2),
468
+ }],
469
+ isError: true,
470
+ };
471
+ }
472
+ const criteria = purpose?.criteria ?? null;
473
+ return {
474
+ content: [{
475
+ type: "text",
476
+ text: JSON.stringify({
477
+ status: "purpose_check",
478
+ nothing_charged: true,
479
+ owner_asked_for: criteria ?? "(no criteria were recorded for this card)",
480
+ authorized_amount: purpose?.authorized_amount ?? null,
481
+ what_to_do: "Look at the checkout page one more time. Write down what is actually there — " +
482
+ "item, variant, quantity, final total — and put it next to what the owner asked for above. " +
483
+ "Then call execute_payment again with `recheck`. If they do not line up, pause: " +
484
+ "nothing is charged and the money stays where it is. Catching it here costs nothing; " +
485
+ "after this call it costs a card.",
486
+ }, null, 2),
487
+ }],
488
+ };
489
+ }
490
+ if (recheck.decision === "pause") {
491
+ // The agent's own verdict. We do not overrule it, and we do not
492
+ // spend on it: the card is never typed in, the token stays alive and
493
+ // refundable, and the human gets told.
494
+ return {
495
+ content: [{
496
+ type: "text",
497
+ text: JSON.stringify({
498
+ success: false,
499
+ status: "paused_by_agent",
500
+ nothing_charged: true,
501
+ token_status: "ACTIVE",
502
+ page_shows: recheck.page_shows,
503
+ why: recheck.why ?? null,
504
+ next: "Tell your owner what did not line up and wait. To release the hold instead, call cancel_payment_token.",
505
+ }, null, 2),
506
+ }],
507
+ };
508
+ }
409
509
  // Step 0: SSRF / scheme guard BEFORE we drive a browser to this URL and inject a real PAN/CVV.
410
510
  try {
411
511
  (0, url_guard_js_1.assertSafeCheckoutUrl)(checkout_url);
@@ -425,16 +525,8 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
425
525
  }
426
526
  // Step 1: Resolve token → card data (RAM only)
427
527
  const cardData = await resolveTokenRemote(token);
428
- if (cardData?.error === "AUTH_REQUIRED") {
429
- return {
430
- content: [{
431
- type: "text",
432
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
433
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents"
434
- }],
435
- isError: true
436
- };
437
- }
528
+ if (cardData?.error === "AUTH_REQUIRED")
529
+ return authRequiredResult(cardData.message);
438
530
  if (!cardData || cardData.error) {
439
531
  return {
440
532
  content: [
@@ -488,7 +580,11 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
488
580
  // Step 3: Burn the token ONLY on a CONFIRMED payment (result.success === status 'confirmed').
489
581
  // Every other outcome (declined / unconfirmed / not_submitted / no_fields / error) leaves the
490
582
  // token UNBURNED so the funds stay recoverable. "Filled a field" is NOT a payment.
491
- if (!result.success) {
583
+ // ONE gate for the irreversible step. `success` is a boolean the bridge sets;
584
+ // `status` is the outcome it observed. Burning a token cannot be undone, so it
585
+ // requires both to say the merchant confirmed the order (backtest E07).
586
+ const isConfirmed = result.success && result.status === 'confirmed';
587
+ if (!isConfirmed) {
492
588
  // `declined` = merchant rejected → webhook refund flow handles it.
493
589
  // Everything else = we couldn't prove a charge happened → funds stay locked, recoverable.
494
590
  const isDeclined = result.status === 'declined';
@@ -525,7 +621,8 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
525
621
  isError: true,
526
622
  };
527
623
  }
528
- // Confirmed — burn the token, passing the REAL receipt id if one was scraped.
624
+ // Past the gate above, so status === 'confirmed'. Burn, passing the REAL
625
+ // receipt id if one was scraped.
529
626
  await burnTokenRemote(token, result.receipt_id);
530
627
  // Step 4: Refund underspend if actual amount was less than token amount
531
628
  if (actual_amount !== undefined) {
@@ -540,6 +637,9 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
540
637
  merchant_order_id: result.receipt_id || null,
541
638
  amount_captured: actual_amount,
542
639
  card_last4: cardData.number ? cardData.number.replace(/\D/g, "").slice(-4) : undefined,
640
+ // The purpose record travels into the signed receipt: the owner's
641
+ // locked criteria and the agent's answer, sealed with the outcome.
642
+ recheck,
543
643
  }).catch(() => null);
544
644
  // Step 5: Return result (NEVER includes card numbers)
545
645
  return {
@@ -580,16 +680,8 @@ server.tool("cancel_payment_token", "Cancel unused token and refund instantly. U
580
680
  .describe("Reason for cancellation, e.g. 'Price mismatch: checkout shows $20 but token is $15'"),
581
681
  }, async ({ token, reason }) => {
582
682
  const result = await cancelTokenRemote(token);
583
- if (result?.error === "AUTH_REQUIRED") {
584
- return {
585
- content: [{
586
- type: "text",
587
- text: "❌ AUTHENTICATION REQUIRED: Your Z_ZERO_API_KEY (Passport Key) is missing from the MCP configuration.\n\n" +
588
- "👉 Please GET your key here: https://z-zero.xyz/dashboard/agents"
589
- }],
590
- isError: true
591
- };
592
- }
683
+ if (result?.error === "AUTH_REQUIRED")
684
+ return authRequiredResult(result.message);
593
685
  if (!result || !result.success) {
594
686
  return {
595
687
  content: [
@@ -675,9 +767,9 @@ server.tool("set_api_key", "Activate a new Passport Key instantly, no restart ne
675
767
  };
676
768
  }
677
769
  // Step 2: Validate new key against Dashboard API before swapping
678
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
770
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
679
771
  try {
680
- const resp = await fetch(`${ZZERO_API}/api/wdk/balance`, {
772
+ const resp = await fetch(`${ZZERO_API}/api/wallet/balance`, {
681
773
  headers: {
682
774
  "Authorization": `Bearer ${trimmed}`,
683
775
  "x-mcp-version": version_js_2.CURRENT_MCP_VERSION,
@@ -792,7 +884,7 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
792
884
  .string()
793
885
  .describe("Card alias to charge for JIT Fiat fallback, e.g. 'Card_01'."),
794
886
  }, async ({ checkout_url, card_alias }) => {
795
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
887
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
796
888
  const API_KEY = (0, key_store_js_1.getPassportKey)(); // ✅ FIX: use hot-swap key store, not process.env
797
889
  // Spend guard for the autonomous path. auto_pay derives the amount itself
798
890
  // (scraped fiat total OR on-chain amount from an EIP-681 link / calldata), so there is
@@ -845,7 +937,7 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
845
937
  isError: true,
846
938
  };
847
939
  }
848
- const resp = await fetch(`${ZZERO_API}/api/wdk/transfer`, {
940
+ const resp = await fetch(`${ZZERO_API}/api/wallet/transfer`, {
849
941
  method: "POST",
850
942
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` },
851
943
  body: JSON.stringify({ to, amount, card_alias }),
@@ -922,7 +1014,9 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
922
1014
  // Burn ONLY on a confirmed charge. Any other outcome leaves the JIT token unburned
923
1015
  // so the locked funds are recoverable (cancel/expire/decline-webhook).
924
1016
  let autoReceipt = null;
925
- if (fillResult.success) {
1017
+ // Same rule as execute_payment: burning needs both the flag and the
1018
+ // observed status to say confirmed (backtest E07).
1019
+ if (fillResult.success && fillResult.status === 'confirmed') {
926
1020
  const burnOk = await burnTokenRemote(token.token, fillResult.receipt_id);
927
1021
  if (!burnOk)
928
1022
  console.error(`[WARN] Token burn failed for ${token.token} — manual check needed`);
@@ -1055,12 +1149,15 @@ server.tool("report_checkout_fail", "Report a checkout you could not complete. P
1055
1149
  // Lets the agent PROVE a purchase happened instead of claiming it.
1056
1150
  // Public endpoint — anyone with the receipt_id can verify.
1057
1151
  // ============================================================
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.", {
1152
+ server.tool("verify_receipt", "Check where an order ENDED UP, and prove it. Returns TWO separate axes: " +
1153
+ "`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) — " +
1154
+ "and `funds_status` — 'no_payout_due' · 'payout_pending' (money owed back but not yet confirmed on-chain) · 'returned' (confirmed on-chain). " +
1155
+ "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.", {
1059
1156
  receipt_id: zod_1.z
1060
1157
  .string()
1061
1158
  .describe("The receipt_id returned by execute_payment / auto_pay_checkout (signed_receipt.receipt_id)."),
1062
1159
  }, async ({ receipt_id }) => {
1063
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
1160
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
1064
1161
  try {
1065
1162
  const resp = await fetch(`${ZZERO_API}/api/receipts/${encodeURIComponent(receipt_id)}`, {
1066
1163
  headers: { "x-mcp-version": version_js_2.CURRENT_MCP_VERSION },
@@ -1147,6 +1244,18 @@ Tools: \`get_merchant_hints\`, \`request_payment_token\`, \`execute_payment\`, \
1147
1244
  On success you get \`signed_receipt\` (+ verify_url): a signed statement of what actually settled,
1148
1245
  diffed against the intent. Share verify_url with the user — prove the purchase, don't claim it.
1149
1246
 
1247
+ 7. **After a confirmed purchase, say it is bought — then watch what the issuer says.**
1248
+ \`status: confirmed\` means the order was really placed, so tell the user it is done; do not
1249
+ hedge. The card issuer reports minutes later. When you check back — or the user asks — call
1250
+ \`verify_receipt(receipt_id)\` and read BOTH axes:
1251
+ · \`order_status\`: 'completed' → 'settled' (confirmed) · 'reversed' (auth voided — the order
1252
+ does NOT stand) · 'partially_refunded'/'refunded' (merchant returned money; the order
1253
+ itself still happened).
1254
+ · \`funds_status\`: 'payout_pending' means money is owed back but NOT yet confirmed on-chain —
1255
+ never tell the user their money is back until it says 'returned'.
1256
+ If order_status comes back 'reversed' after you already said it was bought, correct
1257
+ yourself immediately and unprompted.
1258
+
1150
1259
  ⛔ Never call \`request_payment_token\` before BOTH: shipping submitted AND card fields + final total visible.
1151
1260
 
1152
1261
  ⚠️ **Resumable URL required.** \`execute_payment\` opens its OWN fresh, cookieless browser at \`checkout_url\` —
@@ -0,0 +1,2 @@
1
+ /** The base URL every request should use, with legacy hosts corrected. */
2
+ export declare function resolveApiBaseUrl(): string;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ // api-base.ts
3
+ // One place that decides which host this MCP server talks to.
4
+ //
5
+ // Why this exists: the move to z-zero.xyz left older installs pointing at
6
+ // zzero.xyz, which now answers 308 → https://z-zero.xyz. Node's fetch follows
7
+ // that redirect but DROPS the Authorization header on a cross-origin hop, so
8
+ // the API sees no key and answers 401 "Unauthorized". The result is the worst
9
+ // kind of failure — a perfectly valid Passport Key that looks revoked, on every
10
+ // single tool, with the docs telling the user to go make another one.
11
+ //
12
+ // Rewriting the known legacy hosts here fixes it for every call site at once.
13
+ // We never re-send the key to a redirect target ourselves: that is how a key
14
+ // leaks to whatever host a redirect happens to name.
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.resolveApiBaseUrl = resolveApiBaseUrl;
17
+ const CANONICAL = "https://z-zero.xyz";
18
+ // Hosts that 30x to CANONICAL. Same origin in spirit, different origin to fetch.
19
+ // clawcard.store is the pre-rebrand domain and is still in real configs.
20
+ const LEGACY_HOSTS = new Set([
21
+ "zzero.xyz",
22
+ "www.zzero.xyz",
23
+ "www.z-zero.xyz",
24
+ "clawcard.store",
25
+ "www.clawcard.store",
26
+ ]);
27
+ let warned = false;
28
+ /** The base URL every request should use, with legacy hosts corrected. */
29
+ function resolveApiBaseUrl() {
30
+ const raw = (process.env.Z_ZERO_API_BASE_URL ||
31
+ process.env.Z_ZERO_API_BASE ||
32
+ CANONICAL).trim();
33
+ let url;
34
+ try {
35
+ url = new URL(raw);
36
+ }
37
+ catch {
38
+ console.error(`[Z-ZERO MCP] ⚠️ Z_ZERO_API_BASE_URL is not a valid URL ("${raw}") — using ${CANONICAL}.`);
39
+ return CANONICAL;
40
+ }
41
+ if (LEGACY_HOSTS.has(url.hostname)) {
42
+ if (!warned) {
43
+ warned = true;
44
+ console.error(`[Z-ZERO MCP] ⚠️ Z_ZERO_API_BASE_URL points at ${url.hostname}, which redirects to z-zero.xyz. ` +
45
+ `A cross-origin redirect strips the Authorization header, so every call would fail as 401. ` +
46
+ `Using ${CANONICAL} instead — please update your MCP config.`);
47
+ }
48
+ return CANONICAL;
49
+ }
50
+ return raw.replace(/\/$/, "");
51
+ }
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  // key-store.ts
3
3
  // Shared, mutable in-memory store for the Passport Key (Z_ZERO_API_KEY).
4
- // All API backends (custodial + WDK) import getPassportKey() from here
4
+ // All API backends import getPassportKey() from here
5
5
  // so a single set_api_key MCP tool updates the key for ALL backends at once.
6
6
  //
7
7
  // v1.5.0: keys are also persisted to ~/.z-zero/credentials (chmod 600).
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Throws if `rawUrl` is not a safe public checkout URL.
3
3
  * - must parse as a URL
4
- * - must be HTTPS (except localhost/127.0.0.1 in non-production, for local testing)
4
+ * - must be HTTPS (except a loopback host when local checkout is explicitly enabled)
5
5
  * - must not resolve to a private / loopback / link-local host (SSRF)
6
6
  */
7
7
  export declare function assertSafeCheckoutUrl(rawUrl: string): void;
@@ -20,7 +20,7 @@ const PRIVATE_HOST_PATTERNS = [
20
20
  /**
21
21
  * Throws if `rawUrl` is not a safe public checkout URL.
22
22
  * - must parse as a URL
23
- * - must be HTTPS (except localhost/127.0.0.1 in non-production, for local testing)
23
+ * - must be HTTPS (except a loopback host when local checkout is explicitly enabled)
24
24
  * - must not resolve to a private / loopback / link-local host (SSRF)
25
25
  */
26
26
  function assertSafeCheckoutUrl(rawUrl) {
@@ -32,10 +32,23 @@ function assertSafeCheckoutUrl(rawUrl) {
32
32
  throw new Error(`Invalid checkout_url: ${rawUrl}`);
33
33
  }
34
34
  const hostname = url.hostname;
35
- const isDev = process.env.NODE_ENV !== "production";
36
- const isLocalDev = isDev && (hostname === "localhost" || hostname === "127.0.0.1");
37
- if (isLocalDev)
38
- return;
35
+ // Loopback checkout targets are an EXPLICIT opt-in, never a side effect of
36
+ // NODE_ENV. This server runs on the end user's machine, where NODE_ENV is
37
+ // essentially never "production" — so keying the bypass off that flag left it
38
+ // permanently open in the one place it has to stay shut: this is the call that
39
+ // decides where a real PAN/CVV gets typed. Opting in also waives the HTTPS
40
+ // requirement, which is why it must be a deliberate act by the machine's owner.
41
+ if (hostname === "localhost" || hostname === "127.0.0.1") {
42
+ if (process.env.Z_ZERO_ALLOW_LOCAL_CHECKOUT === "1") {
43
+ console.error(`[URL-GUARD] ⚠️ Local checkout allowed for ${hostname} — ` +
44
+ `Z_ZERO_ALLOW_LOCAL_CHECKOUT=1 is set. Real card data will be typed into a local page. ` +
45
+ `Unset it outside of testing.`);
46
+ return;
47
+ }
48
+ throw new Error(`SSRF blocked host: ${hostname}. Checkout must be a public HTTPS page — ` +
49
+ `a local address would receive real card data. ` +
50
+ `For local testing only, set Z_ZERO_ALLOW_LOCAL_CHECKOUT=1.`);
51
+ }
39
52
  if (url.protocol !== "https:") {
40
53
  throw new Error("checkout_url must use HTTPS.");
41
54
  }
@@ -31,14 +31,14 @@ async function detectWeb3Payment(page, checkoutUrl) {
31
31
  return "8453";
32
32
  if (method === "eth_sendTransaction") {
33
33
  const tx = params?.[0];
34
- window["__wdkCapturedTx"] = tx;
34
+ window["__zzCapturedTx"] = tx;
35
35
  return "0xdeadbeef00000000000000000000000000000000000000000000000000000001";
36
36
  }
37
37
  if (method === "wallet_switchEthereumChain")
38
38
  return null;
39
39
  if (method === "eth_getBalance")
40
40
  return "0x0";
41
- window["__wdkUnknownMethod_" + method] = true;
41
+ window["__zzUnknownMethod_" + method] = true;
42
42
  return null;
43
43
  },
44
44
  on: (event, handler) => {
@@ -120,7 +120,7 @@ async function detectWeb3Payment(page, checkoutUrl) {
120
120
  const start = Date.now();
121
121
  while (Date.now() - start < WEB3_DETECT_TIMEOUT_MS) {
122
122
  const tx = await page.evaluate(() => {
123
- return window["__wdkCapturedTx"] ?? null;
123
+ return window["__zzCapturedTx"] ?? null;
124
124
  });
125
125
  if (tx) {
126
126
  const capturedTx = tx;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "z-zero-mcp-server",
3
- "version": "1.7.0",
3
+ "version": "1.9.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,6 +10,7 @@
10
10
  "build": "tsc",
11
11
  "start": "node dist/index.js",
12
12
  "dev": "npx tsx src/index.ts",
13
+ "test:mock-checkout": "npm run build && node --experimental-strip-types tests/backtest_mock_checkout_e2e.mts",
13
14
  "prepublishOnly": "npm run build"
14
15
  },
15
16
  "keywords": [