z-zero-mcp-server 1.8.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -57,9 +57,11 @@ const postReceiptRemote = activeBackend.postReceiptRemote;
57
57
  const getBalanceRemote = activeBackend.getBalanceRemote;
58
58
  const listCardsRemote = activeBackend.listCardsRemote;
59
59
  const getDepositAddressesRemote = activeBackend.getDepositAddressesRemote;
60
+ const getTokenPurposeRemote = activeBackend.getTokenPurposeRemote;
60
61
  console.error(`[Z-ZERO MCP] 🚀 Base + USDC (non-custodial, gasless)`);
61
62
  // ────────────────────────────────────────────────────────────────────────────
62
63
  const playwright_bridge_js_1 = require("./playwright_bridge.js");
64
+ const ucp_bridge_js_1 = require("./ucp_bridge.js");
63
65
  const web3_detector_js_1 = require("./lib/web3-detector.js");
64
66
  const extract_total_price_js_1 = require("./lib/extract-total-price.js");
65
67
  const playwright_1 = require("playwright");
@@ -132,9 +134,29 @@ function authRequiredResult(detail) {
132
134
  };
133
135
  }
134
136
  // ============================================================
137
+ // QUY ƯỚC ANNOTATIONS (xem docs/mcp_hardening_plan_22_08_26.md §W1)
138
+ // openWorldHint = true → TẠI THỜI ĐIỂM GỌI tool chạm ra ngoài control plane
139
+ // Z-ZERO: merchant, issuer (Airwallex), hoặc public chain (Base).
140
+ // openWorldHint = false → chỉ đọc/ghi DB & API của Z-ZERO, hoặc thuần local — KỂ CẢ khi
141
+ // dữ liệu có nguồn gốc issuer nhưng đã reconcile sẵn vào DB
142
+ // (vì vậy verify_receipt = false).
143
+ // destructiveHint → theo spec MCP là 'destructive vs additive', KHÔNG phải
144
+ // 'nguy hiểm' và KHÔNG phải 'không đảo ngược được'.
145
+ // idempotentHint → chỉ khai khi readOnlyHint === false.
146
+ // Annotations là HINT, không phải hàng rào bảo mật. Chống double-charge là việc của
147
+ // idempotency_key ở backend, không phải của idempotentHint.
148
+ // ============================================================
135
149
  // TOOL 1: List available cards (safe - no sensitive data)
136
150
  // ============================================================
137
- server.tool("list_cards", "List all available virtual card aliases and their balances. No sensitive data is returned.", {}, async () => {
151
+ server.registerTool("list_cards", {
152
+ title: "List Cards",
153
+ description: "List all available virtual card aliases and their balances. No sensitive data is returned.",
154
+ inputSchema: {},
155
+ annotations: {
156
+ readOnlyHint: true,
157
+ openWorldHint: false,
158
+ },
159
+ }, async () => {
138
160
  const data = await listCardsRemote();
139
161
  if (data?.error === "AUTH_REQUIRED")
140
162
  return authRequiredResult(data.message);
@@ -170,10 +192,18 @@ server.tool("list_cards", "List all available virtual card aliases and their bal
170
192
  // ============================================================
171
193
  // TOOL 2: Check card balance (safe)
172
194
  // ============================================================
173
- server.tool("check_balance", "Check spendable USD balance for a card alias. For active token limits, use list_cards instead.", {
174
- card_alias: zod_1.z
175
- .string()
176
- .describe("The alias of the card to check, e.g. 'Card_01'"),
195
+ server.registerTool("check_balance", {
196
+ title: "Check Balance",
197
+ description: "Check spendable USD balance for a card alias. For active token limits, use list_cards instead.",
198
+ inputSchema: {
199
+ card_alias: zod_1.z
200
+ .string()
201
+ .describe("The alias of the card to check, e.g. 'Card_01'"),
202
+ },
203
+ annotations: {
204
+ readOnlyHint: true,
205
+ openWorldHint: true,
206
+ },
177
207
  }, async ({ card_alias }) => {
178
208
  const data = await getBalanceRemote(card_alias);
179
209
  if (data?.error === "AUTH_REQUIRED")
@@ -205,7 +235,15 @@ server.tool("check_balance", "Check spendable USD balance for a card alias. For
205
235
  // ============================================================
206
236
  // TOOL 2.5: Get deposit addresses (Phase 14 feature)
207
237
  // ============================================================
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 () => {
238
+ server.registerTool("get_deposit_addresses", {
239
+ title: "Get Deposit Address",
240
+ description: "Get your Base deposit address to top up your wallet with USDC (or any supported stablecoin on Base).",
241
+ inputSchema: {},
242
+ annotations: {
243
+ readOnlyHint: true,
244
+ openWorldHint: true,
245
+ },
246
+ }, async () => {
209
247
  const data = await getDepositAddressesRemote();
210
248
  if (data?.error === "AUTH_REQUIRED")
211
249
  return authRequiredResult(data.message);
@@ -243,41 +281,71 @@ server.tool("get_deposit_addresses", "Get your Base deposit address to top up yo
243
281
  // ============================================================
244
282
  // TOOL 3: Request a temporary payment token (issues secure JIT card)
245
283
  // ============================================================
246
- server.tool("request_payment_token", "Request a single-use JIT virtual card ($1–$100) locked to one amount + merchant. ⚠️ Read mcp://resources/sop first. Only call once the FINAL total is visible — for physical goods that is AFTER shipping is submitted (use get_merchant_hints to navigate there). For digital goods with the price already visible, prefer auto_pay_checkout instead. " +
247
- "BEFORE requesting: look at the checkout page one more time and compare it against what the user actually asked for — same items, same quantity, same variant, same destination? If anything differs, do NOT request a token; fix the cart or check with the user first. A mismatch you catch here costs nothing; after this point it costs a card. If you pass `cart`, the server signs your declared intent and binds the card to it — the user gets cryptographic proof of what this card was authorized for.", {
248
- card_alias: zod_1.z
249
- .string()
250
- .describe("Which card to charge, e.g. 'Card_01'"),
251
- amount: zod_1.z
252
- .number()
253
- .min(1, "Minimum amount is $1.00")
254
- .max(100, "Maximum amount is $100.00")
255
- .describe("Amount in USD to authorize (min: $1, max: $100)"),
256
- merchant: zod_1.z
257
- .string()
258
- .describe("Name or URL of the merchant/service being purchased"),
259
- cart: zod_1.z
260
- .array(zod_1.z.object({
261
- title: zod_1.z.string().describe("Item name as shown on the checkout page"),
262
- qty: zod_1.z.number().describe("Quantity"),
263
- unit_price: zod_1.z.number().optional().describe("Unit price if visible"),
264
- url: zod_1.z.string().optional().describe("Product URL if known"),
265
- }))
266
- .max(50)
267
- .optional()
268
- .describe("RECOMMENDED: the items you are buying, as the USER agreed to them. This becomes a signed intent bound to the card — proof of what was authorized."),
269
- ship_to: zod_1.z
270
- .string()
271
- .optional()
272
- .describe("Shipping destination as a single string (only a hash is stored, never the raw address)."),
273
- }, async ({ card_alias, amount, merchant, cart, ship_to }) => {
274
- const intentInput = (cart && cart.length) || ship_to
284
+ server.registerTool("request_payment_token", {
285
+ title: "Issue JIT Card (spends $0.10 fee)",
286
+ description: "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. " +
287
+ "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.",
288
+ inputSchema: {
289
+ card_alias: zod_1.z
290
+ .string()
291
+ .describe("Which card to charge, e.g. 'Card_01'"),
292
+ amount: zod_1.z
293
+ .number()
294
+ .min(1, "Minimum amount is $1.00")
295
+ .max(100, "Maximum amount is $100.00")
296
+ .describe("Amount in USD to authorize (min: $1, max: $100)"),
297
+ merchant: zod_1.z
298
+ .string()
299
+ .describe("Name or URL of the merchant/service being purchased"),
300
+ cart: zod_1.z
301
+ .array(zod_1.z.object({
302
+ title: zod_1.z.string().describe("Item name as shown on the checkout page"),
303
+ qty: zod_1.z.number().describe("Quantity"),
304
+ unit_price: zod_1.z.number().optional().describe("Unit price if visible"),
305
+ url: zod_1.z.string().optional().describe("Product URL if known"),
306
+ }))
307
+ .max(50)
308
+ .optional()
309
+ .describe("RECOMMENDED: the items you are buying, as the USER agreed to them. This becomes a signed intent bound to the card — proof of what was authorized."),
310
+ ship_to: zod_1.z
311
+ .string()
312
+ .optional()
313
+ .describe("Shipping destination as a single string (only a hash is stored, never the raw address)."),
314
+ criteria: zod_1.z
315
+ .object({
316
+ source: zod_1.z
317
+ .enum(["user_link", "user_described", "agent_chose"])
318
+ .describe("Where the choice of THIS product came from. 'user_link' = they gave you the link, so the product is their pick, not yours."),
319
+ items: zod_1.z
320
+ .array(zod_1.z.object({
321
+ key: zod_1.z.string().describe("Short name for the attribute, e.g. item_type, max_price, colour, size, ship_time."),
322
+ stated: zod_1.z.string().describe("What the owner said about it, in their terms."),
323
+ }))
324
+ .min(1)
325
+ .max(12),
326
+ })
327
+ .optional()
328
+ .describe("RECOMMENDED. The things this purchase will be judged against later — write ONLY what the owner actually stated. " +
329
+ "Attributes like price, colour, size, product type or delivery time are examples of the KIND of thing that belongs here, " +
330
+ "not a checklist to fill: an owner who said \"a hat, $10\" gave you exactly two, and inventing three more would mark a good " +
331
+ "purchase as wrong. If they changed their mind, record where they LANDED, not the journey. " +
332
+ "This list is locked and signed now, before the outcome is known, and you will be asked to score against it at payment time."),
333
+ },
334
+ annotations: {
335
+ readOnlyHint: false,
336
+ destructiveHint: true,
337
+ idempotentHint: false,
338
+ openWorldHint: true,
339
+ },
340
+ }, async ({ card_alias, amount, merchant, cart, ship_to, criteria }) => {
341
+ const intentInput = (cart && cart.length) || ship_to || criteria
275
342
  ? {
276
343
  cart,
277
344
  subtotal: cart?.every(i => typeof i.unit_price === "number")
278
345
  ? Math.round(cart.reduce((s, i) => s + i.unit_price * i.qty, 0) * 100) / 100
279
346
  : undefined,
280
347
  ship_to,
348
+ criteria,
281
349
  }
282
350
  : undefined;
283
351
  const token = await issueTokenRemote(card_alias, amount, merchant, intentInput);
@@ -344,10 +412,18 @@ server.tool("request_payment_token", "Request a single-use JIT virtual card ($1
344
412
  // Agent MUST call this before execute_payment if unsure about a checkout page.
345
413
  // Returns domain-specific selectors and pre-steps from Z-ZERO cloud DB.
346
414
  // ============================================================
347
- server.tool("get_merchant_hints", "Get merchant navigation flow for a domain or platform key (e.g. '_platform_etsy'). Returns pre_steps (how to navigate checkout) and platform notes. Call BEFORE starting checkout to understand the multi-step flow.", {
348
- domain: zod_1.z
349
- .string()
350
- .describe("The main domain of the checkout page, e.g. 'amazon.com' or 'shopify.com'. Strip 'www.' prefix."),
415
+ server.registerTool("get_merchant_hints", {
416
+ title: "Merchant Checkout Hints",
417
+ description: "Get merchant navigation flow for a domain or platform key (e.g. '_platform_etsy'). Returns pre_steps (how to navigate checkout) and platform notes. Call BEFORE starting checkout to understand the multi-step flow.",
418
+ inputSchema: {
419
+ domain: zod_1.z
420
+ .string()
421
+ .describe("The main domain of the checkout page, e.g. 'amazon.com' or 'shopify.com'. Strip 'www.' prefix."),
422
+ },
423
+ annotations: {
424
+ readOnlyHint: true,
425
+ openWorldHint: false,
426
+ },
351
427
  }, async ({ domain }) => {
352
428
  const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
353
429
  const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
@@ -378,34 +454,224 @@ server.tool("get_merchant_hints", "Get merchant navigation flow for a domain or
378
454
  }
379
455
  });
380
456
  // ============================================================
457
+ // TOOL 3c: UCP probe — the "Official Rail" scout (creates drafts, no money moves)
458
+ // Shopify now ships UCP natively on every store and its robots
459
+ // policy bans browser-automation checkout. This tool checks the
460
+ // UCP lane and returns a REAL merchant quote without any browser
461
+ // and without touching money.
462
+ // ============================================================
463
+ server.registerTool("ucp_probe_checkout", {
464
+ title: "Probe UCP Checkout (creates draft)",
465
+ description: "UCP discovery + quote — creates an UNPAID draft checkout; no money moves; NOT a payment rail yet. Checks whether a merchant speaks UCP (Shopify-native agent commerce), lists its declared payment handlers, and — when variant_gid or query is given — creates a DRAFT checkout and returns the merchant's real quote: total_minor (wire units, 8900 = $89.00), total_major, currency, status, blockers, continue_url. NO payment happens; drafts expire server-side. Completing a UCP checkout needs Shopify Token-tier agent auth, which Z-Zero does not hold yet — to PAY, hand the buyer continue_url or use the standard execute_payment flow where permitted. Call this first on Shopify stores: their robots.txt bans scripted checkout, so the UCP lane is the sanctioned path.",
466
+ inputSchema: {
467
+ shop_url: zod_1.z.string().url().describe("Store URL, e.g. https://meanblvd.com"),
468
+ variant_gid: zod_1.z.string().optional()
469
+ .describe("Exact Shopify variant GID to quote, e.g. gid://shopify/ProductVariant/123"),
470
+ query: zod_1.z.string().optional()
471
+ .describe("Product search query when variant_gid is unknown — first in-stock hit is quoted."),
472
+ quantity: zod_1.z.number().int().min(1).max(10).default(1),
473
+ ship_to: zod_1.z.object({
474
+ first_name: zod_1.z.string().optional(),
475
+ last_name: zod_1.z.string().optional(),
476
+ street_address: zod_1.z.string(),
477
+ address_locality: zod_1.z.string().describe("City"),
478
+ address_region: zod_1.z.string().optional().describe("State/province code, required for US/CA"),
479
+ address_country: zod_1.z.string().describe("ISO 3166-1 alpha-2, e.g. US"),
480
+ postal_code: zod_1.z.string(),
481
+ phone_number: zod_1.z.string().optional(),
482
+ }).optional().describe("Shipping address — supply it to get the REAL total with market pricing + shipping."),
483
+ buyer_email: zod_1.z.string().email().optional(),
484
+ },
485
+ annotations: {
486
+ readOnlyHint: false,
487
+ destructiveHint: false,
488
+ idempotentHint: false,
489
+ openWorldHint: true,
490
+ },
491
+ }, async ({ shop_url, variant_gid, query, quantity, ship_to, buyer_email }) => {
492
+ const reply = (data, isError = false) => ({
493
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
494
+ ...(isError ? { isError: true } : {}),
495
+ });
496
+ try {
497
+ (0, url_guard_js_1.assertSafeCheckoutUrl)(shop_url);
498
+ const disc = await (0, ucp_bridge_js_1.ucpDiscover)(shop_url);
499
+ if (!disc) {
500
+ return reply({
501
+ ucp_available: false,
502
+ message: "Merchant does not expose /.well-known/ucp — use the standard get_merchant_hints + execute_payment flow instead.",
503
+ });
504
+ }
505
+ const base = {
506
+ ucp_available: true,
507
+ ucp_version: disc.version,
508
+ mcp_endpoint: disc.mcpEndpoint,
509
+ payment_handlers: disc.handlers.map((h) => h.handler_name),
510
+ card_lane: disc.cardHandler
511
+ ? { handler_id: disc.cardHandler.id, config: disc.cardHandler.config }
512
+ : null,
513
+ note: disc.cardHandler
514
+ ? "dev.shopify.card is declared: this store ACCEPTS card instruments over UCP. Quote/cart/checkout work anonymously; complete_checkout requires Shopify Token-tier auth, which this server does not hold — so today the UCP lane gives you discovery + draft + continue_url, not completion."
515
+ : "No card handler declared — card payment not possible on the UCP lane here.",
516
+ };
517
+ if (!variant_gid && !query)
518
+ return reply(base);
519
+ const client = new ucp_bridge_js_1.UcpMcpClient(disc.mcpEndpoint);
520
+ let itemIds = [];
521
+ if (variant_gid) {
522
+ itemIds = [variant_gid];
523
+ }
524
+ else {
525
+ const search = await client.callTool("search_catalog", { meta: {}, catalog: { query, limit: 5 } });
526
+ const blob = JSON.stringify(search);
527
+ itemIds = [...new Set((blob.match(/gid:\\?\/\\?\/shopify\/ProductVariant\/\d+/g) ?? []).map((s) => s.replace(/\\\//g, "/")))].slice(0, 4);
528
+ if (itemIds.length === 0)
529
+ return reply({ ...base, quote: null, message: "No variants found for that query." });
530
+ }
531
+ const email = buyer_email ?? "agent@z-zero.xyz";
532
+ let lastQuote = null;
533
+ for (const itemId of itemIds) {
534
+ const q = await (0, ucp_bridge_js_1.ucpCreateCheckout)(client, [{ item_id: itemId, quantity }], { email }, ship_to);
535
+ const rawCheckout = q.raw?.checkout ?? q.raw ?? {};
536
+ lastQuote = {
537
+ variant: itemId,
538
+ title: rawCheckout?.line_items?.[0]?.item?.title ?? null,
539
+ checkout_id: q.checkout_id || null,
540
+ status: q.status,
541
+ total_minor: q.total_minor,
542
+ total_major: q.total_major,
543
+ currency: q.currency,
544
+ messages: q.messages,
545
+ continue_url: q.continue_url,
546
+ };
547
+ const soldOut = !q.checkout_id || q.messages.some((m) => /out_of_stock|item_unavailable/i.test(m));
548
+ if (!soldOut)
549
+ break;
550
+ }
551
+ return reply({ ...base, quote: lastQuote });
552
+ }
553
+ catch (err) {
554
+ return reply({ ucp_available: null, error: err?.message ?? String(err) }, true);
555
+ }
556
+ });
557
+ // ============================================================
381
558
  // TOOL 4b: Execute payment (The "Invisible Hand")
382
559
  // ============================================================
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.", {
384
- token: zod_1.z
385
- .string()
386
- .describe("The temporary payment token from request_payment_token"),
387
- checkout_url: zod_1.z
388
- .string()
389
- .url()
390
- .describe("The full URL of the checkout/payment page"),
391
- actual_amount: zod_1.z
392
- .number()
393
- .optional()
394
- .describe("STRONGLY RECOMMENDED. The final total shown on the checkout page (incl. shipping + tax). Enables the overcharge block and the underspend refund — omit only if it is genuinely unreadable."),
395
- hints: zod_1.z
396
- .object({
397
- pre_steps: zod_1.z.array(zod_1.z.string()).optional(),
398
- card_selector: zod_1.z.string().optional(),
399
- exp_selector: zod_1.z.string().optional(),
400
- exp_month_selector: zod_1.z.string().optional(),
401
- exp_year_selector: zod_1.z.string().optional(),
402
- cvv_selector: zod_1.z.string().optional(),
403
- name_selector: zod_1.z.string().optional(),
404
- submit_selector: zod_1.z.string().optional(),
405
- })
406
- .optional()
407
- .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 }) => {
560
+ server.registerTool("execute_payment", {
561
+ title: "Execute Payment (charges the card)",
562
+ description: "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.",
563
+ inputSchema: {
564
+ token: zod_1.z
565
+ .string()
566
+ .describe("The temporary payment token from request_payment_token"),
567
+ checkout_url: zod_1.z
568
+ .string()
569
+ .url()
570
+ .describe("The full URL of the checkout/payment page"),
571
+ actual_amount: zod_1.z
572
+ .number()
573
+ .optional()
574
+ .describe("STRONGLY RECOMMENDED. The final total shown on the checkout page (incl. shipping + tax). Enables the overcharge block and the underspend refund — omit only if it is genuinely unreadable."),
575
+ hints: zod_1.z
576
+ .object({
577
+ pre_steps: zod_1.z.array(zod_1.z.string()).optional(),
578
+ card_selector: zod_1.z.string().optional(),
579
+ exp_selector: zod_1.z.string().optional(),
580
+ exp_month_selector: zod_1.z.string().optional(),
581
+ exp_year_selector: zod_1.z.string().optional(),
582
+ cvv_selector: zod_1.z.string().optional(),
583
+ name_selector: zod_1.z.string().optional(),
584
+ submit_selector: zod_1.z.string().optional(),
585
+ })
586
+ .optional()
587
+ .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."),
588
+ recheck: zod_1.z
589
+ .object({
590
+ page_shows: zod_1.z
591
+ .string()
592
+ .min(1)
593
+ .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'."),
594
+ decision: zod_1.z
595
+ .enum(["go", "pause"])
596
+ .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."),
597
+ why: zod_1.z
598
+ .string()
599
+ .optional()
600
+ .describe("Required when you pause: what did not line up."),
601
+ })
602
+ .optional()
603
+ .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."),
604
+ },
605
+ annotations: {
606
+ readOnlyHint: false,
607
+ destructiveHint: true,
608
+ idempotentHint: false,
609
+ openWorldHint: true,
610
+ },
611
+ }, async ({ token, checkout_url, actual_amount, hints, recheck }) => {
612
+ // ── Purpose check: the last look before there is no way back ─────────
613
+ // Called with no `recheck`, this tool does not pay. It hands back the
614
+ // criteria the owner stated, locked at issue, and asks for an answer.
615
+ // The question comes from the server on purpose: an agent that quotes it
616
+ // from its own memory can soften it until anything matches.
617
+ // No browser, no PAN, nothing spent — asking is free.
618
+ if (!recheck) {
619
+ const purpose = await getTokenPurposeRemote(token);
620
+ if (purpose?.error === "AUTH_REQUIRED")
621
+ return authRequiredResult(purpose.message);
622
+ // A dead token should say so HERE, not send the agent off to look at a
623
+ // page and come back for a second call that was always going to fail.
624
+ if (purpose?.error) {
625
+ return {
626
+ content: [{
627
+ type: "text",
628
+ text: JSON.stringify({
629
+ success: false,
630
+ status: "invalid_token",
631
+ nothing_charged: true,
632
+ message: purpose.message || "Token is invalid, expired, cancelled, or already used. Request a new one.",
633
+ }, null, 2),
634
+ }],
635
+ isError: true,
636
+ };
637
+ }
638
+ const criteria = purpose?.criteria ?? null;
639
+ return {
640
+ content: [{
641
+ type: "text",
642
+ text: JSON.stringify({
643
+ status: "purpose_check",
644
+ nothing_charged: true,
645
+ owner_asked_for: criteria ?? "(no criteria were recorded for this card)",
646
+ authorized_amount: purpose?.authorized_amount ?? null,
647
+ what_to_do: "Look at the checkout page one more time. Write down what is actually there — " +
648
+ "item, variant, quantity, final total — and put it next to what the owner asked for above. " +
649
+ "Then call execute_payment again with `recheck`. If they do not line up, pause: " +
650
+ "nothing is charged and the money stays where it is. Catching it here costs nothing; " +
651
+ "after this call it costs a card.",
652
+ }, null, 2),
653
+ }],
654
+ };
655
+ }
656
+ if (recheck.decision === "pause") {
657
+ // The agent's own verdict. We do not overrule it, and we do not
658
+ // spend on it: the card is never typed in, the token stays alive and
659
+ // refundable, and the human gets told.
660
+ return {
661
+ content: [{
662
+ type: "text",
663
+ text: JSON.stringify({
664
+ success: false,
665
+ status: "paused_by_agent",
666
+ nothing_charged: true,
667
+ token_status: "ACTIVE",
668
+ page_shows: recheck.page_shows,
669
+ why: recheck.why ?? null,
670
+ next: "Tell your owner what did not line up and wait. To release the hold instead, call cancel_payment_token.",
671
+ }, null, 2),
672
+ }],
673
+ };
674
+ }
409
675
  // Step 0: SSRF / scheme guard BEFORE we drive a browser to this URL and inject a real PAN/CVV.
410
676
  try {
411
677
  (0, url_guard_js_1.assertSafeCheckoutUrl)(checkout_url);
@@ -537,6 +803,9 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
537
803
  merchant_order_id: result.receipt_id || null,
538
804
  amount_captured: actual_amount,
539
805
  card_last4: cardData.number ? cardData.number.replace(/\D/g, "").slice(-4) : undefined,
806
+ // The purpose record travels into the signed receipt: the owner's
807
+ // locked criteria and the agent's answer, sealed with the outcome.
808
+ recheck,
540
809
  }).catch(() => null);
541
810
  // Step 5: Return result (NEVER includes card numbers)
542
811
  return {
@@ -568,13 +837,23 @@ server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero
568
837
  // ============================================================
569
838
  // TOOL 5: Cancel payment token (returns funds to wallet)
570
839
  // ============================================================
571
- server.tool("cancel_payment_token", "Cancel unused token and refund instantly. Use when user cancels the purchase or to free up a card slot.", {
572
- token: zod_1.z
573
- .string()
574
- .describe("The payment token to cancel"),
575
- reason: zod_1.z
576
- .string()
577
- .describe("Reason for cancellation, e.g. 'Price mismatch: checkout shows $20 but token is $15'"),
840
+ server.registerTool("cancel_payment_token", {
841
+ title: "Cancel Token — Safe Refund",
842
+ description: "Cancel unused token and refund instantly. Use when user cancels the purchase or to free up a card slot.",
843
+ inputSchema: {
844
+ token: zod_1.z
845
+ .string()
846
+ .describe("The payment token to cancel"),
847
+ reason: zod_1.z
848
+ .string()
849
+ .describe("Reason for cancellation, e.g. 'Price mismatch: checkout shows $20 but token is $15'"),
850
+ },
851
+ annotations: {
852
+ readOnlyHint: false,
853
+ destructiveHint: true,
854
+ idempotentHint: true,
855
+ openWorldHint: true,
856
+ },
578
857
  }, async ({ token, reason }) => {
579
858
  const result = await cancelTokenRemote(token);
580
859
  if (result?.error === "AUTH_REQUIRED")
@@ -607,21 +886,29 @@ server.tool("cancel_payment_token", "Cancel unused token and refund instantly. U
607
886
  // ============================================================
608
887
  // TOOL 6: Request human approval (Human-in-the-loop)
609
888
  // ============================================================
610
- server.tool("request_human_approval", "Pause and ask the user for approval before risky actions (price mismatch, large amount, unusual request).", {
611
- situation: zod_1.z
612
- .string()
613
- .describe("Clear description of what the bot found, e.g. 'Checkout shows $20 total (includes $3 tax) but current token is only $15'"),
614
- current_token: zod_1.z
615
- .string()
616
- .optional()
617
- .describe("Current active token ID if any"),
618
- recommended_action: zod_1.z
619
- .string()
620
- .describe("What the bot recommends doing, e.g. 'Cancel current $15 token and issue a new $20 token'"),
621
- alternative_action: zod_1.z
622
- .string()
623
- .optional()
624
- .describe("Alternative option if available"),
889
+ server.registerTool("request_human_approval", {
890
+ title: "Show Approval Instructions",
891
+ description: "Pause and ask the user for approval before risky actions (price mismatch, large amount, unusual request).",
892
+ inputSchema: {
893
+ situation: zod_1.z
894
+ .string()
895
+ .describe("Clear description of what the bot found, e.g. 'Checkout shows $20 total (includes $3 tax) but current token is only $15'"),
896
+ current_token: zod_1.z
897
+ .string()
898
+ .optional()
899
+ .describe("Current active token ID if any"),
900
+ recommended_action: zod_1.z
901
+ .string()
902
+ .describe("What the bot recommends doing, e.g. 'Cancel current $15 token and issue a new $20 token'"),
903
+ alternative_action: zod_1.z
904
+ .string()
905
+ .optional()
906
+ .describe("Alternative option if available"),
907
+ },
908
+ annotations: {
909
+ readOnlyHint: true,
910
+ openWorldHint: false,
911
+ },
625
912
  }, async ({ situation, current_token, recommended_action, alternative_action }) => {
626
913
  // This tool surfaces the situation to the human operator via the MCP interface.
627
914
  // The LLM host (Claude/AutoGPT) will pause and show this to the user.
@@ -650,10 +937,20 @@ server.tool("request_human_approval", "Pause and ask the user for approval befor
650
937
  // ============================================================
651
938
  // TOOL 6.5: Set API Key (Hot-Swap Passport Key — NO restart needed)
652
939
  // ============================================================
653
- server.tool("set_api_key", "Activate a new Passport Key instantly, no restart needed. Only call when user explicitly provides a key.", {
654
- api_key: zod_1.z
655
- .string()
656
- .describe("The new Passport Key to activate. Must start with 'zk_live_' or 'zk_test_'. Get from: https://z-zero.xyz/dashboard/agents"),
940
+ server.registerTool("set_api_key", {
941
+ title: "Change Passport Key (switches identity)",
942
+ description: "Activate a new Passport Key instantly, no restart needed. Only call when user explicitly provides a key.",
943
+ inputSchema: {
944
+ api_key: zod_1.z
945
+ .string()
946
+ .describe("The new Passport Key to activate. Must start with 'zk_live_' or 'zk_test_'. Get from: https://z-zero.xyz/dashboard/agents"),
947
+ },
948
+ annotations: {
949
+ readOnlyHint: false,
950
+ destructiveHint: true,
951
+ idempotentHint: false,
952
+ openWorldHint: false,
953
+ },
657
954
  }, async ({ api_key }) => {
658
955
  // Step 1: Format validation
659
956
  const trimmed = api_key.trim();
@@ -756,7 +1053,15 @@ server.tool("set_api_key", "Activate a new Passport Key instantly, no restart ne
756
1053
  // ============================================================
757
1054
  // TOOL 6.6: Show current API Key status (for debugging)
758
1055
  // ============================================================
759
- server.tool("show_api_key_status", "Check if Passport Key is configured. Shows prefix only, for debugging.", {}, async () => {
1056
+ server.registerTool("show_api_key_status", {
1057
+ title: "Passport Key Status",
1058
+ description: "Check if Passport Key is configured. Shows prefix only, for debugging.",
1059
+ inputSchema: {},
1060
+ annotations: {
1061
+ readOnlyHint: true,
1062
+ openWorldHint: false,
1063
+ },
1064
+ }, async () => {
760
1065
  const key = (0, key_store_js_1.getPassportKey)();
761
1066
  const hasKey = key.length > 0;
762
1067
  return {
@@ -772,14 +1077,24 @@ server.tool("show_api_key_status", "Check if Passport Key is configured. Shows p
772
1077
  }],
773
1078
  };
774
1079
  });
775
- server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop first. Only use on PAYMENT pages where final total is visible. Auto-detects Web3 or Fiat and completes payment. For physical goods (Shopify, Etsy), get_merchant_hints first.", {
776
- checkout_url: zod_1.z
777
- .string()
778
- .url()
779
- .describe("Full URL of the checkout/payment page to analyze and pay."),
780
- card_alias: zod_1.z
781
- .string()
782
- .describe("Card alias to charge for JIT Fiat fallback, e.g. 'Card_01'."),
1080
+ server.registerTool("auto_pay_checkout", {
1081
+ title: "Auto-Pay Checkout (charges the card)",
1082
+ description: "⚠️ MANDATORY: Read mcp://resources/sop first. Only use on PAYMENT pages where final total is visible. Auto-detects Web3 or Fiat and completes payment. For physical goods (Shopify, Etsy), get_merchant_hints first.",
1083
+ inputSchema: {
1084
+ checkout_url: zod_1.z
1085
+ .string()
1086
+ .url()
1087
+ .describe("Full URL of the checkout/payment page to analyze and pay."),
1088
+ card_alias: zod_1.z
1089
+ .string()
1090
+ .describe("Card alias to charge for JIT Fiat fallback, e.g. 'Card_01'."),
1091
+ },
1092
+ annotations: {
1093
+ readOnlyHint: false,
1094
+ destructiveHint: true,
1095
+ idempotentHint: false,
1096
+ openWorldHint: true,
1097
+ },
783
1098
  }, async ({ checkout_url, card_alias }) => {
784
1099
  const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
785
1100
  const API_KEY = (0, key_store_js_1.getPassportKey)(); // ✅ FIX: use hot-swap key store, not process.env
@@ -1002,26 +1317,36 @@ server.tool("auto_pay_checkout", "⚠️ MANDATORY: Read mcp://resources/sop fir
1002
1317
  // Triggers: stuck mid pre_steps, bot blocked, selector not found, etc.
1003
1318
  // Does NOT apply to: user cancelled, insufficient balance, price mismatch.
1004
1319
  // ============================================================
1005
- server.tool("report_checkout_fail", "Report a checkout you could not complete. Pick the failure_class that best matches what you saw — this feeds Z-ZERO's self-healing loop (labeled failures become better merchant hints for the next run). If nothing fits, use 'unknown' and describe what happened in error_message.", {
1006
- url: zod_1.z
1007
- .string()
1008
- .url()
1009
- .describe("The checkout/payment page URL where the purchase failed."),
1010
- failure_class: zod_1.z
1011
- .enum(failure_taxonomy_js_1.FAILURE_CLASSES)
1012
- .describe("Fixed failure class: 'card_declined_issuer' (card rejected by bank), 'card_declined_bin_block' (merchant refuses prepaid/virtual cards), 'avs_mismatch' (billing address rejected), '3ds_required' (extra verification/SCA screen appeared), 'bot_detected' (CAPTCHA/Cloudflare/'unusual activity'), 'form_changed' (expected field or button not found), 'price_changed' (total differs from expected), 'out_of_stock', 'shipping_unsupported' (cannot ship to address), 'login_required' (checkout demands an account), 'timeout', 'outcome_unconfirmed' (submitted but no confirmation seen), or 'unknown'."),
1013
- step: zod_1.z
1014
- .enum(failure_taxonomy_js_1.CHECKOUT_STEPS)
1015
- .optional()
1016
- .describe("Where it failed: 'navigate' (page load), 'pre_steps' (shipping/navigation steps), 'fill_form' (card fields), 'submit' (Pay button), 'confirm' (after submitting)."),
1017
- error_message: zod_1.z
1018
- .string()
1019
- .optional()
1020
- .describe("Brief description of what you saw, e.g. 'Card number field is inside a new iframe' or 'Page redirected to CAPTCHA'. NEVER include card numbers."),
1021
- remediation_tried: zod_1.z
1022
- .string()
1023
- .optional()
1024
- .describe("What you already tried before giving up, e.g. 'retried with submit_selector from hints'."),
1320
+ server.registerTool("report_checkout_fail", {
1321
+ title: "Report Checkout Failure",
1322
+ description: "Report a checkout you could not complete. Pick the failure_class that best matches what you saw — this feeds Z-ZERO's self-healing loop (labeled failures become better merchant hints for the next run). If nothing fits, use 'unknown' and describe what happened in error_message.",
1323
+ inputSchema: {
1324
+ url: zod_1.z
1325
+ .string()
1326
+ .url()
1327
+ .describe("The checkout/payment page URL where the purchase failed."),
1328
+ failure_class: zod_1.z
1329
+ .enum(failure_taxonomy_js_1.FAILURE_CLASSES)
1330
+ .describe("Fixed failure class: 'card_declined_issuer' (card rejected by bank), 'card_declined_bin_block' (merchant refuses prepaid/virtual cards), 'avs_mismatch' (billing address rejected), '3ds_required' (extra verification/SCA screen appeared), 'bot_detected' (CAPTCHA/Cloudflare/'unusual activity'), 'form_changed' (expected field or button not found), 'price_changed' (total differs from expected), 'out_of_stock', 'shipping_unsupported' (cannot ship to address), 'login_required' (checkout demands an account), 'timeout', 'outcome_unconfirmed' (submitted but no confirmation seen), or 'unknown'."),
1331
+ step: zod_1.z
1332
+ .enum(failure_taxonomy_js_1.CHECKOUT_STEPS)
1333
+ .optional()
1334
+ .describe("Where it failed: 'navigate' (page load), 'pre_steps' (shipping/navigation steps), 'fill_form' (card fields), 'submit' (Pay button), 'confirm' (after submitting)."),
1335
+ error_message: zod_1.z
1336
+ .string()
1337
+ .optional()
1338
+ .describe("Brief description of what you saw, e.g. 'Card number field is inside a new iframe' or 'Page redirected to CAPTCHA'. NEVER include card numbers."),
1339
+ remediation_tried: zod_1.z
1340
+ .string()
1341
+ .optional()
1342
+ .describe("What you already tried before giving up, e.g. 'retried with submit_selector from hints'."),
1343
+ },
1344
+ annotations: {
1345
+ readOnlyHint: false,
1346
+ destructiveHint: false,
1347
+ idempotentHint: false,
1348
+ openWorldHint: false,
1349
+ },
1025
1350
  }, async ({ url, failure_class, step, error_message, remediation_tried }) => {
1026
1351
  emitCheckoutEvent({
1027
1352
  url,
@@ -1046,13 +1371,21 @@ server.tool("report_checkout_fail", "Report a checkout you could not complete. P
1046
1371
  // Lets the agent PROVE a purchase happened instead of claiming it.
1047
1372
  // Public endpoint — anyone with the receipt_id can verify.
1048
1373
  // ============================================================
1049
- server.tool("verify_receipt", "Check where an order ENDED UP, and prove it. Returns TWO separate axes: " +
1050
- "`order_status` — 'completed' (bought, issuer not reported yet) · 'settled' (issuer confirmed) · 'reversed' (auth voided before clearing — the order does NOT stand) · 'partially_refunded' / 'refunded' (merchant returned money AFTER settlement — the order still happened) — " +
1051
- "and `funds_status` — 'no_payout_due' · 'payout_pending' (money owed back but not yet confirmed on-chain) · 'returned' (confirmed on-chain). " +
1052
- "Read BOTH before speaking: 'reversed' or 'refunded' with funds 'payout_pending' means the buyer has NOT got the money back yet — never say they have. If you told the user a purchase was done and a later check returns 'reversed', tell them unprompted.", {
1053
- receipt_id: zod_1.z
1054
- .string()
1055
- .describe("The receipt_id returned by execute_payment / auto_pay_checkout (signed_receipt.receipt_id)."),
1374
+ server.registerTool("verify_receipt", {
1375
+ title: "Verify Receipt",
1376
+ description: "Check where an order ENDED UP, and prove it. Returns TWO separate axes: " +
1377
+ "`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) — " +
1378
+ "and `funds_status` — 'no_payout_due' · 'payout_pending' (money owed back but not yet confirmed on-chain) · 'returned' (confirmed on-chain). " +
1379
+ "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.",
1380
+ inputSchema: {
1381
+ receipt_id: zod_1.z
1382
+ .string()
1383
+ .describe("The receipt_id returned by execute_payment / auto_pay_checkout (signed_receipt.receipt_id)."),
1384
+ },
1385
+ annotations: {
1386
+ readOnlyHint: true,
1387
+ openWorldHint: false,
1388
+ },
1056
1389
  }, async ({ receipt_id }) => {
1057
1390
  const ZZERO_API = (0, api_base_js_1.resolveApiBaseUrl)();
1058
1391
  try {
@@ -1269,6 +1602,6 @@ async function main() {
1269
1602
  await server.connect(transport);
1270
1603
  console.error(`🔐 Z-Zero MCP Server v${version_js_2.CURRENT_MCP_VERSION} running (Base + USDC, gasless via Coinbase Paymaster)...`);
1271
1604
  console.error("Status: Secure & Connected to Z-ZERO Gateway");
1272
- console.error("Tools: list_cards, check_balance, get_deposit_addresses, request_payment_token, get_merchant_hints, execute_payment, auto_pay_checkout, cancel_payment_token, request_human_approval, report_checkout_fail, verify_receipt, set_api_key, show_api_key_status");
1605
+ console.error("Tools: list_cards, check_balance, get_deposit_addresses, request_payment_token, get_merchant_hints, execute_payment, auto_pay_checkout, cancel_payment_token, request_human_approval, report_checkout_fail, ucp_probe_checkout, verify_receipt, set_api_key, show_api_key_status");
1273
1606
  }
1274
1607
  main().catch(console.error);