z-zero-mcp-server 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.
@@ -1,13 +1,11 @@
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;
@@ -19,7 +17,8 @@ exports.burnTokenRemote = burnTokenRemote;
19
17
  exports.cancelTokenRemote = cancelTokenRemote;
20
18
  exports.refundUnderspendRemote = refundUnderspendRemote;
21
19
  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";
20
+ const api_base_js_1 = require("./lib/api-base.js");
21
+ const API_BASE_URL = (0, api_base_js_1.resolveApiBaseUrl)();
23
22
  const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
24
23
  // Injected at build time — always reflects the actual running version
25
24
  const version_js_1 = require("./version.js");
@@ -46,10 +45,17 @@ async function apiRequest(endpoint, method = 'GET', body = null) {
46
45
  "X-MCP-Version": version_js_1.CURRENT_MCP_VERSION,
47
46
  },
48
47
  body: body ? JSON.stringify(body) : null,
48
+ // Never let fetch follow a redirect while carrying the Passport Key:
49
+ // it would either drop the header (silent 401) or hand the key to
50
+ // whatever host the redirect names. Surface it instead.
51
+ redirect: "manual",
49
52
  });
53
+ if (res.status >= 300 && res.status < 400) {
54
+ return redirectError(url, res);
55
+ }
50
56
  if (!res.ok) {
51
57
  const err = await res.json().catch(() => ({ error: res.statusText }));
52
- return { error: err.error || "API_ERROR", message: err.message || err.error || res.statusText };
58
+ return httpError(res, err);
53
59
  }
54
60
  return await res.json();
55
61
  }
@@ -57,6 +63,36 @@ async function apiRequest(endpoint, method = 'GET', body = null) {
57
63
  return { error: "NETWORK_ERROR", message: err.message };
58
64
  }
59
65
  }
66
+ // Normalise a failed HTTP response into an error object callers can branch on.
67
+ // A 401 becomes AUTH_REQUIRED here — at the source — so no caller can mistake a
68
+ // rejected key for a missing resource. `status` rides along so callers can tell
69
+ // 404 (resource genuinely absent) from 500 (server broke).
70
+ // A redirect on an authenticated call is a configuration bug, not an auth bug.
71
+ // Say so, because the 401 it would otherwise become reads as "your key is dead".
72
+ function redirectError(url, res) {
73
+ const target = res.headers.get("location") || "another host";
74
+ return {
75
+ error: "BASE_URL_REDIRECT",
76
+ status: res.status,
77
+ message: `${url} redirected (${res.status}) to ${target}. The Passport Key was NOT forwarded — ` +
78
+ `a redirected request loses its Authorization header, which shows up as a false 401. ` +
79
+ `Set Z_ZERO_API_BASE_URL to https://z-zero.xyz in your MCP config.`,
80
+ };
81
+ }
82
+ function httpError(res, err) {
83
+ if (res.status === 401) {
84
+ return {
85
+ error: "AUTH_REQUIRED",
86
+ status: 401,
87
+ message: err?.message || err?.error || "Passport Key is missing, invalid, or revoked.",
88
+ };
89
+ }
90
+ return {
91
+ error: err?.error || "API_ERROR",
92
+ status: res.status,
93
+ message: err?.message || err?.error || res.statusText,
94
+ };
95
+ }
60
96
  async function internalApiRequest(endpoint, method, body) {
61
97
  // Auth is the Bearer Passport Key — the server dropped the x-internal-secret
62
98
  // gate on /resolve and /burn (redundant to per-user token ownership, Jul 2026).
@@ -74,10 +110,17 @@ async function internalApiRequest(endpoint, method, body) {
74
110
  "X-MCP-Version": version_js_1.CURRENT_MCP_VERSION,
75
111
  },
76
112
  body: body ? JSON.stringify(body) : null,
113
+ // Never let fetch follow a redirect while carrying the Passport Key:
114
+ // it would either drop the header (silent 401) or hand the key to
115
+ // whatever host the redirect names. Surface it instead.
116
+ redirect: "manual",
77
117
  });
118
+ if (res.status >= 300 && res.status < 400) {
119
+ return redirectError(url, res);
120
+ }
78
121
  if (!res.ok) {
79
122
  const err = await res.json().catch(() => ({ error: res.statusText }));
80
- return { error: err.error || "API_ERROR", message: err.message || err.error || res.statusText };
123
+ return httpError(res, err);
81
124
  }
82
125
  return await res.json();
83
126
  }
@@ -89,24 +132,50 @@ async function internalApiRequest(endpoint, method, body) {
89
132
  // Core API: Same as custodial (cards, tokens still managed by Dashboard)
90
133
  // ──────────────────────────────────────────────────────────────────────────────
91
134
  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.
135
+ // /api/tokens/cards returns card aliases + the on-chain Base USDC balance.
95
136
  return await apiRequest('/api/tokens/cards', 'GET');
96
137
  }
97
138
  // ──────────────────────────────────────────────────────────────────────────────
98
139
  // Balance: On-chain USDC (stablecoin) on Base via Dashboard API
99
140
  // ──────────────────────────────────────────────────────────────────────────────
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) {
141
+ // Turn a failed /api/wallet/balance call into an honest, actionable failure.
142
+ // Returns null when the call succeeded.
143
+ //
144
+ // Why this exists: this used to collapse EVERY error into "Base wallet not
145
+ // connected", so a user whose Passport Key had been revoked was sent to the
146
+ // wallet page to fix a problem that was about the key. Only a genuine 404 means
147
+ // "no wallet" — everything else must keep its own identity.
148
+ function walletLookupFailure(data) {
149
+ if (!data?.error)
150
+ return null;
151
+ if (data.error === "AUTH_REQUIRED") {
152
+ return { error: "AUTH_REQUIRED", message: data.message };
153
+ }
154
+ if (data.error === "NETWORK_ERROR") {
105
155
  return {
106
- error: true,
107
- message: 'Base wallet not connected. Create one at https://z-zero.xyz/dashboard/agent-wallet'
156
+ error: "NETWORK_ERROR",
157
+ message: `Could not reach ${API_BASE_URL}: ${data.message}`,
108
158
  };
109
159
  }
160
+ if (data.status === 404) {
161
+ return {
162
+ error: "NO_WALLET",
163
+ message: 'Base wallet not connected. Create one at https://z-zero.xyz/dashboard/agent-wallet',
164
+ };
165
+ }
166
+ return {
167
+ error: data.error,
168
+ status: data.status,
169
+ message: data.message || 'Could not read your Base wallet balance.',
170
+ };
171
+ }
172
+ async function getBalanceRemote(cardAlias) {
173
+ // Call Dashboard to get the agent's Base wallet balance (Dashboard resolves user from
174
+ // passport key, finds the connected Base wallet, queries on-chain USDC balance)
175
+ const data = await apiRequest('/api/wallet/balance', 'GET');
176
+ const failure = walletLookupFailure(data);
177
+ if (failure)
178
+ return failure;
110
179
  return {
111
180
  wallet_balance: data.base_usdc_balance ?? data.balance_usdt,
112
181
  currency: 'USDC',
@@ -120,13 +189,10 @@ async function getBalanceRemote(cardAlias) {
120
189
  // Deposit Address: the agent's Base smart-account address (single chain)
121
190
  // ──────────────────────────────────────────────────────────────────────────────
122
191
  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
- }
192
+ const data = await apiRequest('/api/wallet/balance', 'GET');
193
+ const failure = walletLookupFailure(data);
194
+ if (failure)
195
+ return failure;
130
196
  const balance = data.base_usdc_balance ?? data.balance_usdt;
131
197
  return {
132
198
  cards: [{ alias: 'base-wallet', balance, currency: 'USDC' }],
@@ -134,7 +200,7 @@ async function getDepositAddressesRemote() {
134
200
  base: data.address,
135
201
  note: 'Send USDC (or any supported stablecoin) on Base to your wallet. Gasless spending via the Coinbase Paymaster.'
136
202
  },
137
- wdk_wallet: {
203
+ base_wallet: {
138
204
  address: data.address,
139
205
  chain: data.chain || 'base',
140
206
  balance_usdt: balance
@@ -156,8 +222,7 @@ async function issueTokenRemote(cardAlias, amount, merchant, intent) {
156
222
  merchant,
157
223
  device_fingerprint: `mcp-base-${process.platform}-${process.arch}`,
158
224
  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
225
+ session_id: `base-${Math.random().toString(36).substring(7)}`,
161
226
  // Primitive 1: the intent this card is derived from. Server signs it and
162
227
  // returns the signed object; older servers simply ignore this field.
163
228
  ...(intent ? { intent } : {}),
@@ -175,7 +240,7 @@ async function issueTokenRemote(cardAlias, amount, merchant, intent) {
175
240
  ttl_seconds: 3600,
176
241
  used: false,
177
242
  tx_hash: data.tx_hash,
178
- mode: 'wdk_noncustodial',
243
+ mode: 'base_usdc',
179
244
  intent: data.intent || null, // signed intent (intent_id, hash, signature) if server supports it
180
245
  mcp_warning: data._mcp_warning || null, // Relay backend version warning to agent
181
246
  };
@@ -221,7 +286,6 @@ async function burnTokenRemote(token, receipt_id) {
221
286
  token,
222
287
  receipt_id,
223
288
  success: true,
224
- wallet_mode: 'wdk', // Signals Dashboard to refund underspend on-chain
225
289
  });
226
290
  return !!data && !data.error;
227
291
  }
@@ -231,7 +295,6 @@ async function burnTokenRemote(token, receipt_id) {
231
295
  async function cancelTokenRemote(token) {
232
296
  const data = await apiRequest('/api/tokens/cancel', 'POST', {
233
297
  token,
234
- wallet_mode: 'wdk', // Triggers on-chain USDC refund
235
298
  });
236
299
  if (data?.error)
237
300
  return data;
@@ -247,5 +310,5 @@ async function cancelTokenRemote(token) {
247
310
  // ──────────────────────────────────────────────────────────────────────────────
248
311
  async function refundUnderspendRemote(token, actualSpent) {
249
312
  // 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.`);
313
+ console.error(`[Z-ZERO MCP] Token ${token} burned. Actual spent: $${actualSpent}. On-chain refund handled by Dashboard.`);
251
314
  }
@@ -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,7 @@ 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
+ console.error(`[Z-ZERO MCP] 🚀 Base + USDC (non-custodial, gasless)`);
61
61
  // ────────────────────────────────────────────────────────────────────────────
62
62
  const playwright_bridge_js_1 = require("./playwright_bridge.js");
63
63
  const web3_detector_js_1 = require("./lib/web3-detector.js");
@@ -65,6 +65,7 @@ const extract_total_price_js_1 = require("./lib/extract-total-price.js");
65
65
  const playwright_1 = require("playwright");
66
66
  const key_store_js_1 = require("./lib/key-store.js"); // ✅ Hot-Swap + rotate-on-connect
67
67
  const url_guard_js_1 = require("./lib/url-guard.js");
68
+ const api_base_js_1 = require("./lib/api-base.js");
68
69
  const failure_taxonomy_js_1 = require("./failure_taxonomy.js");
69
70
  /** Masked, non-reconstructable hint for a secret key (for debug output only). */
70
71
  function maskKey(key) {
@@ -81,7 +82,7 @@ function maskKey(key) {
81
82
  // labeled data even when the agent never calls report_checkout_fail.
82
83
  // ============================================================
83
84
  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 ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
85
86
  const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
86
87
  const body = {
87
88
  ...evt,
@@ -111,26 +112,40 @@ const server = new mcp_js_1.McpServer({
111
112
  version: version_js_2.CURRENT_MCP_VERSION,
112
113
  });
113
114
  // ============================================================
115
+ // SHARED: the one AUTH_REQUIRED reply
116
+ // ============================================================
117
+ // A 401 can mean the key is missing, mistyped, revoked, or already rotated onto
118
+ // another machine — the server cannot tell us which, so the message must not
119
+ // claim one of them. It also must not send the reader to a restart: set_api_key
120
+ // activates a new key in place (since 1.5.0).
121
+ function authRequiredResult(detail) {
122
+ return {
123
+ content: [{
124
+ type: "text",
125
+ text: "❌ AUTHENTICATION REQUIRED: Z-ZERO rejected your Passport Key — it is missing, invalid, or has been revoked.\n" +
126
+ (detail ? `Server said: ${detail}\n` : "") +
127
+ "\n👉 Get a fresh key: https://z-zero.xyz/dashboard/agents\n" +
128
+ "👉 Then call set_api_key with it — no restart needed. (Or set Z_ZERO_API_KEY in your MCP config and restart.)\n" +
129
+ "Note: one key belongs to one machine — it rotates on first connect, so a key already used elsewhere will not work here."
130
+ }],
131
+ isError: true,
132
+ };
133
+ }
134
+ // ============================================================
114
135
  // TOOL 1: List available cards (safe - no sensitive data)
115
136
  // ============================================================
116
137
  server.tool("list_cards", "List all available virtual card aliases and their balances. No sensitive data is returned.", {}, async () => {
117
138
  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
- }
139
+ if (data?.error === "AUTH_REQUIRED")
140
+ return authRequiredResult(data.message);
129
141
  if (data?.error) {
130
142
  return {
131
143
  content: [{
132
144
  type: "text",
133
- text: `❌ API ERROR: ${data.message || data.error}\n\nCould not fetch cards. Please verify your Passport Key is correct.`
145
+ // Don't blame the key here — AUTH_REQUIRED was already handled
146
+ // above, so whatever reaches this branch is something else
147
+ // (redirected base URL, deactivated agent, server error).
148
+ text: `❌ API ERROR: ${data.message || data.error}\n\nCould not fetch cards.`
134
149
  }],
135
150
  isError: true
136
151
  };
@@ -161,23 +176,18 @@ server.tool("check_balance", "Check spendable USD balance for a card alias. For
161
176
  .describe("The alias of the card to check, e.g. 'Card_01'"),
162
177
  }, async ({ card_alias }) => {
163
178
  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
- }
179
+ if (data?.error === "AUTH_REQUIRED")
180
+ return authRequiredResult(data.message);
175
181
  if (!data || data.error) {
182
+ // Pass the backend's own reason through — "card not found" was being
183
+ // printed over real causes (no wallet, network down, server error).
184
+ const reason = data?.message
185
+ || `Card "${card_alias}" not found. Use list_cards to see available cards.`;
176
186
  return {
177
187
  content: [
178
188
  {
179
189
  type: "text",
180
- text: `Card "${card_alias}" not found or API issue. Use list_cards to see available cards.`,
190
+ text: reason,
181
191
  },
182
192
  ],
183
193
  isError: true,
@@ -197,21 +207,12 @@ server.tool("check_balance", "Check spendable USD balance for a card alias. For
197
207
  // ============================================================
198
208
  server.tool("get_deposit_addresses", "Get your Base deposit address to top up your wallet with USDC (or any supported stablecoin on Base).", {}, async () => {
199
209
  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
- }
210
+ if (data?.error === "AUTH_REQUIRED")
211
+ return authRequiredResult(data.message);
211
212
  // ── 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;
213
+ if (data?.base_wallet?.address) {
214
+ const walletAddr = data.base_wallet.address;
215
+ const balance = data.base_wallet.balance_usdt ?? 0;
215
216
  return {
216
217
  content: [{
217
218
  type: "text",
@@ -227,11 +228,14 @@ server.tool("get_deposit_addresses", "Get your Base deposit address to top up yo
227
228
  }],
228
229
  };
229
230
  }
230
- // No Base wallet connected
231
+ // Anything else: say what actually went wrong. Only a real NO_WALLET
232
+ // sends the reader to the wallet page — a network or server failure that
233
+ // pointed there would have them building a wallet they already have.
231
234
  return {
232
235
  content: [{
233
236
  type: "text",
234
- text: "No Base wallet found. Please create one at https://z-zero.xyz/dashboard/agent-wallet",
237
+ text: data?.message
238
+ || "No Base wallet found. Please create one at https://z-zero.xyz/dashboard/agent-wallet",
235
239
  }],
236
240
  isError: true,
237
241
  };
@@ -277,16 +281,8 @@ server.tool("request_payment_token", "Request a single-use JIT virtual card ($1
277
281
  }
278
282
  : undefined;
279
283
  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
- }
284
+ if (token?.error === "AUTH_REQUIRED")
285
+ return authRequiredResult(token.message);
290
286
  if (!token || token.error) {
291
287
  // Show actual API error if available (e.g. 429 max cards, 402 insufficient)
292
288
  if (token?.message) {
@@ -299,7 +295,11 @@ server.tool("request_payment_token", "Request a single-use JIT virtual card ($1
299
295
  };
300
296
  }
301
297
  const balanceData = await getBalanceRemote(card_alias);
302
- const balance = balanceData?.balance;
298
+ // getBalanceRemote returns `wallet_balance` — reading `balance` here
299
+ // always came back undefined, so this fell through to the vague
300
+ // "not found / key invalid / limit exceeded" line even when the real
301
+ // reason was simply an empty wallet.
302
+ const balance = balanceData?.error ? undefined : balanceData?.wallet_balance;
303
303
  return {
304
304
  content: [
305
305
  {
@@ -349,7 +349,7 @@ server.tool("get_merchant_hints", "Get merchant navigation flow for a domain or
349
349
  .string()
350
350
  .describe("The main domain of the checkout page, e.g. 'amazon.com' or 'shopify.com'. Strip 'www.' prefix."),
351
351
  }, async ({ domain }) => {
352
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
352
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
353
353
  const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
354
354
  try {
355
355
  const resp = await fetch(`${ZZERO_API}/api/checkout-hints?domain=${encodeURIComponent(domain)}&fields=merchant`, {
@@ -425,16 +425,8 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
425
425
  }
426
426
  // Step 1: Resolve token → card data (RAM only)
427
427
  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
- }
428
+ if (cardData?.error === "AUTH_REQUIRED")
429
+ return authRequiredResult(cardData.message);
438
430
  if (!cardData || cardData.error) {
439
431
  return {
440
432
  content: [
@@ -488,7 +480,11 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
488
480
  // Step 3: Burn the token ONLY on a CONFIRMED payment (result.success === status 'confirmed').
489
481
  // Every other outcome (declined / unconfirmed / not_submitted / no_fields / error) leaves the
490
482
  // token UNBURNED so the funds stay recoverable. "Filled a field" is NOT a payment.
491
- if (!result.success) {
483
+ // ONE gate for the irreversible step. `success` is a boolean the bridge sets;
484
+ // `status` is the outcome it observed. Burning a token cannot be undone, so it
485
+ // requires both to say the merchant confirmed the order (backtest E07).
486
+ const isConfirmed = result.success && result.status === 'confirmed';
487
+ if (!isConfirmed) {
492
488
  // `declined` = merchant rejected → webhook refund flow handles it.
493
489
  // Everything else = we couldn't prove a charge happened → funds stay locked, recoverable.
494
490
  const isDeclined = result.status === 'declined';
@@ -525,7 +521,8 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
525
521
  isError: true,
526
522
  };
527
523
  }
528
- // Confirmed — burn the token, passing the REAL receipt id if one was scraped.
524
+ // Past the gate above, so status === 'confirmed'. Burn, passing the REAL
525
+ // receipt id if one was scraped.
529
526
  await burnTokenRemote(token, result.receipt_id);
530
527
  // Step 4: Refund underspend if actual amount was less than token amount
531
528
  if (actual_amount !== undefined) {
@@ -580,16 +577,8 @@ server.tool("cancel_payment_token", "Cancel unused token and refund instantly. U
580
577
  .describe("Reason for cancellation, e.g. 'Price mismatch: checkout shows $20 but token is $15'"),
581
578
  }, async ({ token, reason }) => {
582
579
  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
- }
580
+ if (result?.error === "AUTH_REQUIRED")
581
+ return authRequiredResult(result.message);
593
582
  if (!result || !result.success) {
594
583
  return {
595
584
  content: [
@@ -675,9 +664,9 @@ server.tool("set_api_key", "Activate a new Passport Key instantly, no restart ne
675
664
  };
676
665
  }
677
666
  // 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";
667
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
679
668
  try {
680
- const resp = await fetch(`${ZZERO_API}/api/wdk/balance`, {
669
+ const resp = await fetch(`${ZZERO_API}/api/wallet/balance`, {
681
670
  headers: {
682
671
  "Authorization": `Bearer ${trimmed}`,
683
672
  "x-mcp-version": version_js_2.CURRENT_MCP_VERSION,
@@ -792,7 +781,7 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
792
781
  .string()
793
782
  .describe("Card alias to charge for JIT Fiat fallback, e.g. 'Card_01'."),
794
783
  }, 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";
784
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
796
785
  const API_KEY = (0, key_store_js_1.getPassportKey)(); // ✅ FIX: use hot-swap key store, not process.env
797
786
  // Spend guard for the autonomous path. auto_pay derives the amount itself
798
787
  // (scraped fiat total OR on-chain amount from an EIP-681 link / calldata), so there is
@@ -845,7 +834,7 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
845
834
  isError: true,
846
835
  };
847
836
  }
848
- const resp = await fetch(`${ZZERO_API}/api/wdk/transfer`, {
837
+ const resp = await fetch(`${ZZERO_API}/api/wallet/transfer`, {
849
838
  method: "POST",
850
839
  headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` },
851
840
  body: JSON.stringify({ to, amount, card_alias }),
@@ -922,7 +911,9 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
922
911
  // Burn ONLY on a confirmed charge. Any other outcome leaves the JIT token unburned
923
912
  // so the locked funds are recoverable (cancel/expire/decline-webhook).
924
913
  let autoReceipt = null;
925
- if (fillResult.success) {
914
+ // Same rule as execute_payment: burning needs both the flag and the
915
+ // observed status to say confirmed (backtest E07).
916
+ if (fillResult.success && fillResult.status === 'confirmed') {
926
917
  const burnOk = await burnTokenRemote(token.token, fillResult.receipt_id);
927
918
  if (!burnOk)
928
919
  console.error(`[WARN] Token burn failed for ${token.token} — manual check needed`);
@@ -1055,12 +1046,15 @@ server.tool("report_checkout_fail", "Report a checkout you could not complete. P
1055
1046
  // Lets the agent PROVE a purchase happened instead of claiming it.
1056
1047
  // Public endpoint — anyone with the receipt_id can verify.
1057
1048
  // ============================================================
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.", {
1049
+ server.tool("verify_receipt", "Check where an order ENDED UP, and prove it. Returns TWO separate axes: " +
1050
+ "`order_status` — 'completed' (bought, issuer not reported yet) · 'settled' (issuer confirmed) · 'reversed' (auth voided before clearing — the order does NOT stand) · 'partially_refunded' / 'refunded' (merchant returned money AFTER settlement — the order still happened) — " +
1051
+ "and `funds_status` — 'no_payout_due' · 'payout_pending' (money owed back but not yet confirmed on-chain) · 'returned' (confirmed on-chain). " +
1052
+ "Read BOTH before speaking: 'reversed' or 'refunded' with funds 'payout_pending' means the buyer has NOT got the money back yet — never say they have. If you told the user a purchase was done and a later check returns 'reversed', tell them unprompted.", {
1059
1053
  receipt_id: zod_1.z
1060
1054
  .string()
1061
1055
  .describe("The receipt_id returned by execute_payment / auto_pay_checkout (signed_receipt.receipt_id)."),
1062
1056
  }, async ({ receipt_id }) => {
1063
- const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://z-zero.xyz";
1057
+ const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
1064
1058
  try {
1065
1059
  const resp = await fetch(`${ZZERO_API}/api/receipts/${encodeURIComponent(receipt_id)}`, {
1066
1060
  headers: { "x-mcp-version": version_js_2.CURRENT_MCP_VERSION },
@@ -1147,6 +1141,18 @@ Tools: \`get_merchant_hints\`, \`request_payment_token\`, \`execute_payment\`, \
1147
1141
  On success you get \`signed_receipt\` (+ verify_url): a signed statement of what actually settled,
1148
1142
  diffed against the intent. Share verify_url with the user — prove the purchase, don't claim it.
1149
1143
 
1144
+ 7. **After a confirmed purchase, say it is bought — then watch what the issuer says.**
1145
+ \`status: confirmed\` means the order was really placed, so tell the user it is done; do not
1146
+ hedge. The card issuer reports minutes later. When you check back — or the user asks — call
1147
+ \`verify_receipt(receipt_id)\` and read BOTH axes:
1148
+ · \`order_status\`: 'completed' → 'settled' (confirmed) · 'reversed' (auth voided — the order
1149
+ does NOT stand) · 'partially_refunded'/'refunded' (merchant returned money; the order
1150
+ itself still happened).
1151
+ · \`funds_status\`: 'payout_pending' means money is owed back but NOT yet confirmed on-chain —
1152
+ never tell the user their money is back until it says 'returned'.
1153
+ If order_status comes back 'reversed' after you already said it was bought, correct
1154
+ yourself immediately and unprompted.
1155
+
1150
1156
  ⛔ Never call \`request_payment_token\` before BOTH: shipping submitted AND card fields + final total visible.
1151
1157
 
1152
1158
  ⚠️ **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).
@@ -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.8.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": [
File without changes