agent402-mcp 0.13.28 → 0.13.29

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
@@ -9,7 +9,7 @@ Pick one setup. Both run locally through `npx`.
9
9
  **1. Free, no wallet.** Pure-CPU tools (no outbound calls, keys or models) run free. Each call solves a proof-of-work puzzle with your CPU, typically well under a second on a laptop. Tools that reach the network or a model ask for a wallet.
10
10
 
11
11
  ```
12
- claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.28
12
+ claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.29
13
13
  ```
14
14
 
15
15
  **2. Paid, with a wallet.** Paid tools are settled in USDC on each call.
@@ -19,7 +19,7 @@ claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.28
19
19
  "mcpServers": {
20
20
  "agent402": {
21
21
  "command": "npx",
22
- "args": ["-y", "agent402-mcp@0.13.28"],
22
+ "args": ["-y", "agent402-mcp@0.13.29"],
23
23
  "env": { "AGENT_KEY": "0xYOUR_PRIVATE_KEY" }
24
24
  }
25
25
  }
@@ -30,7 +30,7 @@ claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.28
30
30
 
31
31
  Use `SOLANA_AGENT_KEY` instead for USDC on Solana. Each call is capped at $4 by default; there is no session budget unless you set `AGENT402_BUDGET`.
32
32
 
33
- Claude Code with a wallet: `claude mcp add agent402 -s user -e AGENT_KEY=0xYOUR_PRIVATE_KEY -- npx -y agent402-mcp@0.13.28`
33
+ Claude Code with a wallet: `claude mcp add agent402 -s user -e AGENT_KEY=0xYOUR_PRIVATE_KEY -- npx -y agent402-mcp@0.13.29`
34
34
  (use a new wallet holding only a few dollars of USDC; never your main wallet).
35
35
 
36
36
  Advanced setup (chains, MPP, error codes, the hosted connector) is in [Advanced](#advanced).
@@ -72,6 +72,16 @@ report products run $0.60 to $2.00 per report (domain-audit $0.60 up to the tick
72
72
  so the default per-call cap of $4 covers every tool; set `AGENT402_MAX_PER_CALL` lower for a
73
73
  tighter ceiling.
74
74
 
75
+ **Held payments.** `payment.info` reports `heldThisSessionUsd`: money a wallet
76
+ call sent a signed payment for without a confirmed answer (an error status, a
77
+ dropped connection, a redirect, a job still running). It is held, not spent: a
78
+ seller that kept the authorization could still redeem it, so it counts against
79
+ `AGENT402_BUDGET` for the rest of the session. On the default target
80
+ (`https://agent402.tools`, matched by exact origin), an error status is never
81
+ settled, so a hold for one ends at the authorization's `validBefore` plus 10
82
+ minutes (15 minutes after the answer when no `validBefore` is readable). A held
83
+ amount whose authorization expires unused is released, never charged.
84
+
75
85
  ## Advanced
76
86
 
77
87
  **Hosted connector (no install).** Add `https://agent402.tools/mcp` as a remote MCP server (for example claude.ai → Settings → Connectors → Add custom connector). Pure-CPU tools run free there, rate-limited. Paid tools are payable on the connector over [MPP](https://agent402.tools/what-is-mpp): the connector answers with an `isError` tool result whose text names every way to pay and whose `_meta["org.paymentauth/payment-required"]` carries the challenges. A presented credential that is refused answers JSON-RPC `-32043`, and a call on the tasks path answers `-32042`, both with `data.challenges`. An MCP client wrapped with `mppx`'s `McpClient.wrap()` pays and retries on its own, with the receipt in `_meta`. This package runs locally for no rate limit, or to pay over x402.
package/index.js CHANGED
@@ -57,7 +57,8 @@ import {
57
57
  clipToolDescription,
58
58
  } from "./output-schemas.js";
59
59
 
60
- const BASE = (process.env.AGENT402_URL || "https://agent402.tools").replace(/\/$/, "");
60
+ const DEFAULT_URL = "https://agent402.tools";
61
+ const BASE = (process.env.AGENT402_URL || DEFAULT_URL).replace(/\/$/, "");
61
62
  // Catalog and seller requests (the 402 and the paid retry included) go through
62
63
  // a dedicated dispatcher that refuses a TLS chain through a distrusted
63
64
  // intermediate CA (networks.js).
@@ -119,6 +120,29 @@ const capFromEnv = (name, def) => {
119
120
  const MAX_PER_CALL = capFromEnv("AGENT402_MAX_PER_CALL", DEFAULT_MAX_PER_CALL_USD);
120
121
  const BUDGET = capFromEnv("AGENT402_BUDGET", DEFAULT_BUDGET_USD);
121
122
  let spentUsd = 0;
123
+ // Signed payments that were sent without a confirmed answer (an error status,
124
+ // a dropped connection, a redirect, a job still running). The seller holds a
125
+ // signed authorization it may still redeem, so the amount counts against the
126
+ // session budget for the rest of the session, beside what was spent.
127
+ // The default host (DEFAULT_URL, matched by exact origin) settles a payment
128
+ // only on an answer below 400, so a sent payment it answered with an error
129
+ // status can be redeemed only until its authorization expires: that hold ends
130
+ // at the signed validBefore plus HOLD_SLACK_MS, or OWN_HOST_BLIND_HOLD_MS after
131
+ // the answer when the payload names no readable expiry.
132
+ const HOLD_SLACK_MS = 10 * 60 * 1000;
133
+ const OWN_HOST_BLIND_HOLD_MS = 15 * 60 * 1000;
134
+ const DEFAULT_ORIGIN = new URL(DEFAULT_URL).origin;
135
+ const holds = []; // [{ usd, until }], until Infinity = the rest of the session
136
+ const holdPayment = (usd, until = Infinity) => { holds.push({ usd, until }); };
137
+ const heldNow = () => { const now = Date.now(); let t = 0; for (const h of holds) if (h.until > now) t += h.usd; return t; };
138
+ /** When a sent payload can no longer settle plus the clock slack: an EIP-3009
139
+ * validBefore or a Permit2 deadline, in seconds; null when none is readable. */
140
+ function signedValidUntilMs(paymentPayload) {
141
+ const p = paymentPayload?.payload;
142
+ const v = p?.authorization?.validBefore ?? p?.permit2Authorization?.deadline;
143
+ if (v == null || !/^\d{1,15}$/.test(String(v))) return null;
144
+ return Number(v) * 1000 + HOLD_SLACK_MS;
145
+ }
122
146
  // Wallet calls in flight, each holding what it may sign until it settles or
123
147
  // fails, so concurrent calls cannot each pass against the same budget. The
124
148
  // signing guard reads the one being signed from signCtx.
@@ -128,7 +152,7 @@ const pendingUsd = (except = null) => { let t = 0; for (const e of pendingSpend)
128
152
  /** The most the payment being signed may ask for: the per-call cap and what is
129
153
  * left of the session budget after every other call in flight. */
130
154
  function signAllowance() {
131
- return Math.max(0, Math.min(MAX_PER_CALL, BUDGET - spentUsd - pendingUsd(signCtx.getStore() || null)));
155
+ return Math.max(0, Math.min(MAX_PER_CALL, BUDGET - spentUsd - heldNow() - pendingUsd(signCtx.getStore() || null)));
132
156
  }
133
157
 
134
158
  const DEFAULT_CURATED = [
@@ -218,6 +242,9 @@ function getPayFetch() {
218
242
  onSign: (usd) => { const e = signCtx.getStore(); if (e) { e.usd = usd; e.signed = true; } },
219
243
  onRefuse: (detail) => { const e = signCtx.getStore(); if (e) e.refusal = detail; },
220
244
  });
245
+ // Registered after the guard's check of the signed amount, so it runs only
246
+ // for a payload about to be sent: from here the payment is outstanding.
247
+ client.onAfterPaymentCreation(async ({ paymentPayload } = {}) => { const e = signCtx.getStore(); if (e && e.signed) { e.sent = true; e.until = signedValidUntilMs(paymentPayload); } });
221
248
  if (AGENT_KEY) {
222
249
  const { registerExactEvmScheme } = await import("@x402/evm/exact/client");
223
250
  const { privateKeyToAccount } = await import("viem/accounts");
@@ -404,6 +431,7 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
404
431
  };
405
432
 
406
433
  let res;
434
+ let heldNote = "";
407
435
  if (!HAS_WALLET && HAS_CREDITS) {
408
436
  // Credits key: same budget guards as the wallet path, against the same
409
437
  // number - the credits gate holds and debits what the 402 quotes for THIS
@@ -446,40 +474,51 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
446
474
  };
447
475
  }
448
476
  const inFlight = pendingUsd();
449
- if (spentUsd + inFlight + price > BUDGET) {
477
+ const heldUsd = heldNow();
478
+ if (spentUsd + heldUsd + inFlight + price > BUDGET) {
450
479
  return {
451
- content: [{ type: "text", text: `Refused without paying: session budget exhausted ($${spentUsd.toFixed(4)} of $${BUDGET} spent${inFlight ? `, $${inFlight.toFixed(4)} in flight` : ""}; "${tool.slug}" lists at ${tool.price}). Restart the MCP server or raise AGENT402_BUDGET.` }],
480
+ content: [{ type: "text", text: `Refused without paying: session budget exhausted ($${spentUsd.toFixed(4)} of $${BUDGET} spent${heldUsd ? `, $${heldUsd.toFixed(4)} held for sent payments whose outcome is unknown` : ""}${inFlight ? `, $${inFlight.toFixed(4)} in flight` : ""}; "${tool.slug}" lists at ${tool.price}). Restart the MCP server or raise AGENT402_BUDGET.` }],
452
481
  isError: true,
453
482
  };
454
483
  }
455
484
  const payFetch = await getPayFetch();
456
485
  // Held until the call settles or fails; the guard replaces `usd` with the
457
486
  // amount it lets the wallet sign.
458
- const entry = { usd: price, signed: false, refusal: null };
487
+ const entry = { usd: price, signed: false, sent: false, refusal: null };
459
488
  pendingSpend.add(entry);
460
489
  try {
461
490
  const first = await signCtx.run(entry, () => payFetch(url, { ...paidInit, headers: { ...init.headers, ...asyncHeaders } }));
462
491
  if (isRedirect(first)) {
463
492
  pendingSpend.delete(entry);
464
493
  // A signature already sent leaves that payment's outcome unknown, so
465
- // it counts against the session budget.
466
- if (entry.signed) spentUsd += entry.usd;
494
+ // it is held against the session budget.
495
+ if (entry.sent) holdPayment(entry.usd);
467
496
  return redirectRefusal(first);
468
497
  }
469
498
  res = await collect(first);
470
499
  }
471
500
  catch (e) {
472
501
  pendingSpend.delete(entry);
473
- // Still running past the wait: it may yet settle, so it counts as spent.
474
- if (e instanceof AsyncJobPendingError) { if (entry.signed) spentUsd += entry.usd; return pendingJobResult(tool, e); }
475
- if (entry.refusal) return signingRefusal(tool, entry.refusal);
502
+ // Once a payment was sent, any failure (a job still running, a dropped
503
+ // connection) leaves its authorization redeemable, so it is held.
504
+ if (entry.sent) holdPayment(entry.usd);
505
+ if (e instanceof AsyncJobPendingError) return pendingJobResult(tool, e);
506
+ if (entry.refusal && !entry.sent) return signingRefusal(tool, entry.refusal);
476
507
  throw e;
477
508
  }
478
509
  pendingSpend.delete(entry);
479
- // Count spend when a payment was signed and the server confirms settlement
480
- // (payment receipt header), falling back to any 2xx, conservative in the
481
- // buyer's favor.
482
- if (entry.signed && (res.headers.get("payment-response") || res.headers.get("x-payment-response") || res.ok)) spentUsd += entry.usd;
510
+ // A sent payment is spent when the server confirms settlement (payment
511
+ // receipt header) or answers 2xx; any other answer leaves the signed
512
+ // authorization with the seller, so it is held, never released.
513
+ if (entry.sent) {
514
+ if (res.headers.get("payment-response") || res.headers.get("x-payment-response") || res.ok) spentUsd += entry.usd;
515
+ else if (res.status >= 400 && url.origin === DEFAULT_ORIGIN) {
516
+ // The default host did not settle it: held until it expires unused.
517
+ const until = entry.until ?? Date.now() + OWN_HOST_BLIND_HOLD_MS;
518
+ holdPayment(entry.usd, until);
519
+ heldNote = ` A payment of $${entry.usd} was sent with this request and ${new URL(DEFAULT_URL).host} does not settle a failed answer: it stays held against AGENT402_BUDGET until its authorization expires unused (${new Date(until).toISOString()}), then is released, never charged.`;
520
+ } else { holdPayment(entry.usd); heldNote = ` A payment of $${entry.usd} was sent with this request, so its outcome is unknown: it stays held against AGENT402_BUDGET for this session.`; }
521
+ }
483
522
  } else if (tool.computePayable) {
484
523
  // No wallet: pay with compute up front, solving before the call skips the
485
524
  // 402 round-trip entirely (challenges are single-use and tool-scoped).
@@ -503,7 +542,7 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
503
542
  }
504
543
  const text = await res.text();
505
544
  if (res.status >= 400) {
506
- return { content: [{ type: "text", text: failureText(res.status, text) }], isError: true };
545
+ return { content: [{ type: "text", text: failureText(res.status, text) + heldNote }], isError: true };
507
546
  }
508
547
  let parsed;
509
548
  try { parsed = JSON.parse(text); } catch { parsed = { raw: text }; }
@@ -522,6 +561,8 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
522
561
  function signingRefusal(tool, d) {
523
562
  const text = d.reason === "unknown-asset"
524
563
  ? `Refused without paying: "${tool.slug}" asked to be paid in an asset this server cannot price (USDC or USDG on a known network), so nothing was signed.`
564
+ : d.reason === "signed-amount"
565
+ ? `Refused without paying: for "${tool.slug}", ${d.detail}, so the payment was not sent.`
525
566
  : `Refused without paying: "${tool.slug}" asked for $${d.priceUsd} on the paid request, above the $${Number(d.allowanceUsd.toFixed(6))} this server may sign (AGENT402_MAX_PER_CALL ${MAX_PER_CALL === Infinity ? "off" : `$${MAX_PER_CALL}`}, AGENT402_BUDGET ${BUDGET === Infinity ? "off" : `$${BUDGET}`} with $${spentUsd.toFixed(4)} spent). Nothing was signed.`;
526
567
  return { content: [{ type: "text", text }], isError: true };
527
568
  }
@@ -928,7 +969,8 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
928
969
  maxPerCallUsd: MAX_PER_CALL === Infinity ? "unlimited" : MAX_PER_CALL,
929
970
  sessionBudgetUsd: BUDGET === Infinity ? "unlimited" : BUDGET,
930
971
  spentThisSessionUsd: Number(spentUsd.toFixed(6)),
931
- remainingUsd: BUDGET === Infinity ? "unlimited" : Number(Math.max(0, BUDGET - spentUsd).toFixed(6)),
972
+ heldThisSessionUsd: Number(heldNow().toFixed(6)),
973
+ remainingUsd: BUDGET === Infinity ? "unlimited" : Number(Math.max(0, BUDGET - spentUsd - heldNow()).toFixed(6)),
932
974
  }
933
975
  : "n/a (proof-of-work mode spends CPU, not money)",
934
976
  note: HAS_WALLET
@@ -940,7 +982,7 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
940
982
  claudeCodeHosted: `claude mcp add --transport http agent402 ${BASE}/mcp`,
941
983
  claudeCodeNpm: `claude mcp add agent402 -s user -- npx -y agent402-mcp@${AGENT402_MCP_VERSION}`,
942
984
  cursorHosted: { mcpServers: { agent402: { url: `${BASE}/mcp` } } },
943
- npm: "npx -y agent402-mcp@0.13.28",
985
+ npm: "npx -y agent402-mcp@0.13.29",
944
986
  maintainer: "Havok Holdings LLC",
945
987
  },
946
988
  positioning: `Flagship search/answer first, 500+ long-tail tools via catalog.find / catalog.search / catalog.call. Agent402 is the applied layer of Agentic Finance: agents that pay and get paid per request over x402 or MPP (Machine Payments Protocol), both on the same 402 - ${BASE}/agentic-finance, ${BASE}/glossary.`,
@@ -960,7 +1002,7 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
960
1002
  install: {
961
1003
  claudeCodeHosted: `claude mcp add --transport http agent402 ${BASE}/mcp`,
962
1004
  claudeCodeNpm: `claude mcp add agent402 -s user -- npx -y agent402-mcp@${AGENT402_MCP_VERSION}`,
963
- npm: "npx -y agent402-mcp@0.13.28",
1005
+ npm: "npx -y agent402-mcp@0.13.29",
964
1006
  maintainer: "Havok Holdings LLC",
965
1007
  },
966
1008
  tools: catalog.size,
package/known-assets.js CHANGED
@@ -1,13 +1,16 @@
1
1
  // Known payment assets, and the USD value of an x402 accept priced from them.
2
2
  //
3
- // An x402 "exact" signer signs the accept's raw base-unit `amount` for the
4
- // accept's `asset`. A spending cap therefore has to price that amount with the
5
- // asset's real decimals, and a decimals hint the seller sends beside it (for
6
- // example `extra.decimals`) is not evidence of anything. So the price of an
7
- // accept comes from this table alone: the stablecoins each network settles on
8
- // the Agent402 rails, with their on-chain decimals. An accept whose
9
- // (network, asset) pair is not in the table cannot be priced, and a buyer with
10
- // a cap does not sign it.
3
+ // An x402 "exact" signer signs the accept's raw base-unit amount for the
4
+ // accept's `asset`: `amount` under x402 v2, `maxAmountRequired` under v1. A
5
+ // spending cap therefore has to price the field the signer of that version
6
+ // reads, with the asset's real decimals, and a decimals hint the seller sends
7
+ // beside it (for example `extra.decimals`) is not evidence of anything. So the
8
+ // price of an accept comes from its challenge's version and this table alone:
9
+ // the stablecoins each network settles on the Agent402 rails, with their
10
+ // on-chain decimals. An accept whose (network, asset) pair is not in the table,
11
+ // or that carries both amount fields with different values, cannot be priced,
12
+ // and a buyer with a cap does not sign it. The table is keyed by CAIP-2 ids
13
+ // only: a bare v1 network name (for example "base") is not priced.
11
14
  //
12
15
  // The same file ships in agent402-client, agent402-mcp and agent402-openclaw;
13
16
  // the parent repo's scripts/test-known-assets.js keeps the copies identical and
@@ -85,13 +88,33 @@ export function knownAsset(network, asset) {
85
88
  return list.find((e) => sameAsset(e.asset, asset)) || null;
86
89
  }
87
90
 
88
- /** The USD value of one accept: its base-unit amount (`amount` in x402 v2,
89
- * `maxAmountRequired` in v1) over the KNOWN decimals of its asset. null when
90
- * the asset is not known or the amount is not a whole number of base units. */
91
- export function acceptUsd(accept) {
91
+ /** The base-unit amount the signer of `x402Version` signs for one accept, as
92
+ * a string of digits: `maxAmountRequired` under v1, `amount` under v2. With
93
+ * no version, the one field present (or both, when they agree). null when
94
+ * the field that version signs is missing or not a whole number, when the
95
+ * version is neither 1 nor 2, and whenever the accept carries both fields
96
+ * with different values: such an accept means one price to one reader and
97
+ * another to the next, so it is not priced at all. */
98
+ export function acceptAmount(accept, x402Version = undefined) {
92
99
  if (!accept || typeof accept !== "object") return null;
93
- const raw = accept.amount ?? accept.maxAmountRequired;
94
- if (raw == null || !/^\d+$/.test(String(raw))) return null;
100
+ const has = (x) => x != null && x !== "";
101
+ const v2 = accept.amount, v1 = accept.maxAmountRequired;
102
+ if (has(v2) && has(v1) && String(v2) !== String(v1)) return null;
103
+ let raw;
104
+ if (x402Version === 1) raw = v1;
105
+ else if (x402Version === 2) raw = v2;
106
+ else if (x402Version == null) raw = has(v2) ? v2 : v1;
107
+ else return null;
108
+ if (!has(raw) || !/^\d+$/.test(String(raw))) return null;
109
+ return String(raw);
110
+ }
111
+
112
+ /** The USD value of one accept: the base-unit amount its version's signer
113
+ * signs (acceptAmount) over the KNOWN decimals of its asset. null when the
114
+ * asset is not known or the amount cannot be read. */
115
+ export function acceptUsd(accept, x402Version = undefined) {
116
+ const raw = acceptAmount(accept, x402Version);
117
+ if (raw == null) return null;
95
118
  const entry = knownAsset(accept.network, accept.asset);
96
119
  if (!entry) return null;
97
120
  return Number(raw) / 10 ** entry.decimals;
@@ -99,11 +122,11 @@ export function acceptUsd(accept) {
99
122
 
100
123
  /** The USD values of a 402's accepts: `max` and `min` over the accepts that can
101
124
  * be priced, and `unknown`, the count that cannot. null when there are none. */
102
- export function quoteOf(accepts) {
125
+ export function quoteOf(accepts, x402Version = undefined) {
103
126
  if (!Array.isArray(accepts) || !accepts.length) return null;
104
127
  let max = null, min = null, unknown = 0;
105
128
  for (const a of accepts) {
106
- const usd = acceptUsd(a);
129
+ const usd = acceptUsd(a, x402Version);
107
130
  if (usd == null) { unknown++; continue; }
108
131
  if (max == null || usd > max) max = usd;
109
132
  if (min == null || usd < min) min = usd;
@@ -128,9 +151,9 @@ export function guardSigning(client, { allowance, onSign = null, onRefuse = null
128
151
  const refuse = (detail) => { try { onRefuse?.(detail); } catch { /* the refusal stands */ } return detail; };
129
152
  client.registerPolicy((version, accepts) => {
130
153
  const cap = allowance();
131
- const kept = accepts.filter((a) => { const usd = acceptUsd(a); return usd != null && usd <= cap; });
154
+ const kept = accepts.filter((a) => { const usd = acceptUsd(a, version); return usd != null && usd <= cap; });
132
155
  if (!kept.length) {
133
- const q = quoteOf(accepts);
156
+ const q = quoteOf(accepts, version);
134
157
  const d = refuse({ reason: q && q.min != null ? "over-allowance" : "unknown-asset", priceUsd: q ? q.min : null, allowanceUsd: cap });
135
158
  throw new Error(d.reason === "unknown-asset"
136
159
  ? "spending guard: no payment option is in a known asset, so none can be priced; nothing was signed"
@@ -138,8 +161,8 @@ export function guardSigning(client, { allowance, onSign = null, onRefuse = null
138
161
  }
139
162
  return kept;
140
163
  });
141
- client.onBeforePaymentCreation(async ({ selectedRequirements: r }) => {
142
- const usd = acceptUsd(r);
164
+ client.onBeforePaymentCreation(async ({ paymentRequired, selectedRequirements: r }) => {
165
+ const usd = acceptUsd(r, paymentRequired?.x402Version);
143
166
  const cap = allowance();
144
167
  if (usd == null) {
145
168
  refuse({ reason: "unknown-asset", priceUsd: null, allowanceUsd: cap });
@@ -152,5 +175,97 @@ export function guardSigning(client, { allowance, onSign = null, onRefuse = null
152
175
  onSign?.(usd, r);
153
176
  return undefined;
154
177
  });
178
+ guardSignedAmount(client, { allowance, onRefuse: refuse });
179
+ return client;
180
+ }
181
+
182
+ // The token programs a Solana "exact" payment moves its asset through, and
183
+ // the TransferChecked instruction's tag.
184
+ const SOLANA_TOKEN_PROGRAMS = new Set(["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"]);
185
+ const TRANSFER_CHECKED = 12;
186
+
187
+ /** The amount a Solana payment transaction moves: its one token-program
188
+ * instruction, which must be a TransferChecked, read as base units and
189
+ * decimals. Decoded with @solana/kit, the peer every Solana x402 signer
190
+ * already loads. null when the transaction cannot be read or does not hold
191
+ * exactly that one transfer. */
192
+ async function solanaTransferOf(transaction) {
193
+ if (typeof transaction !== "string" || !transaction) return null;
194
+ try {
195
+ const kit = await import("@solana/kit");
196
+ const tx = kit.getTransactionDecoder().decode(kit.getBase64Encoder().encode(transaction));
197
+ const msg = kit.getCompiledTransactionMessageDecoder().decode(tx.messageBytes);
198
+ const keys = msg.staticAccounts || [];
199
+ const ixs = msg.version === 1
200
+ ? (msg.instructionHeaders || []).map((h, i) => ({ program: keys[h.programAccountIndex], data: msg.instructionPayloads?.[i]?.instructionData }))
201
+ : (msg.instructions || []).map((ix) => ({ program: keys[ix.programAddressIndex], data: ix.data }));
202
+ const token = ixs.filter((ix) => SOLANA_TOKEN_PROGRAMS.has(String(ix.program)));
203
+ if (token.length !== 1) return null;
204
+ const d = token[0].data;
205
+ if (!d || d.length !== 10 || d[0] !== TRANSFER_CHECKED) return null;
206
+ let amount = 0n;
207
+ for (let i = 8; i >= 1; i--) amount = (amount << 8n) | BigInt(d[i]);
208
+ return { amount: amount.toString(), decimals: d[9] };
209
+ } catch {
210
+ return null;
211
+ }
212
+ }
213
+
214
+ /** The base-unit amount a created x402 payment payload commits the buyer to,
215
+ * read from what was signed: an EVM EIP-3009 `authorization.value`, an EVM
216
+ * Permit2 `permitted.amount`, or a Solana transaction's transfer. Returns
217
+ * `{ amount, decimals? }`, `{ unchecked: true }` for a network whose payload
218
+ * this reader does not decode (neither EVM nor Solana), or null when an EVM or
219
+ * Solana payload holds no amount it can read. */
220
+ export async function signedAmountOf(paymentPayload, network) {
221
+ const p = paymentPayload?.payload;
222
+ const net = String(network || "");
223
+ if (net.startsWith("eip155:")) {
224
+ const vals = [p?.authorization?.value, p?.permit2Authorization?.permitted?.amount].filter((x) => x != null);
225
+ if (vals.length !== 1 || !/^\d+$/.test(String(vals[0]))) return null;
226
+ return { amount: BigInt(String(vals[0])).toString() };
227
+ }
228
+ if (net.startsWith("solana:")) return solanaTransferOf(p?.transaction);
229
+ return { unchecked: true };
230
+ }
231
+
232
+ /** Check a created payment payload against the accept it was built for,
233
+ * before it is sent: the amount that was signed must be the amount the
234
+ * allowance was checked against (acceptAmount under the challenge's
235
+ * version), in the known asset's decimals, and within `cap`. Returns null
236
+ * when it holds, else why not. */
237
+ export async function signedPaymentProblem(paymentPayload, requirements, x402Version, cap = Infinity) {
238
+ const expected = acceptAmount(requirements, x402Version);
239
+ const entry = knownAsset(requirements?.network, requirements?.asset);
240
+ if (expected == null) return "the selected payment option's amount cannot be read";
241
+ const signed = await signedAmountOf(paymentPayload, requirements?.network);
242
+ if (signed == null) return "the signed payment's amount cannot be read";
243
+ if (signed.unchecked) return null;
244
+ if (signed.amount !== BigInt(expected).toString()) return `the signed amount (${signed.amount}) differs from the priced amount (${expected})`;
245
+ if (signed.decimals != null && entry && signed.decimals !== entry.decimals) return "the signed transfer's decimals differ from the known asset's";
246
+ if (Number.isFinite(cap)) {
247
+ if (!entry) return "the selected payment option is not in a known asset";
248
+ const usd = Number(signed.amount) / 10 ** entry.decimals;
249
+ if (usd > cap) return `the signed amount asks ${usd}, above the ${cap} this buyer may sign`;
250
+ }
251
+ return null;
252
+ }
253
+
254
+ /** Refuse to send a payment payload whose signed amount is not the one the
255
+ * allowance passed: registered after payload creation, so the check reads
256
+ * what was actually signed, and a throw here stops the payment-aware fetch
257
+ * before the payload leaves the process. guardSigning registers it; a
258
+ * client with its own selector (and no guardSigning) can register it alone. */
259
+ export function guardSignedAmount(client, { allowance = () => Infinity, onRefuse = null } = {}) {
260
+ if (!client || typeof client.onAfterPaymentCreation !== "function") {
261
+ throw new TypeError("guardSignedAmount needs an @x402/core x402Client (onAfterPaymentCreation)");
262
+ }
263
+ client.onAfterPaymentCreation(async ({ paymentRequired, selectedRequirements: r, paymentPayload }) => {
264
+ const cap = allowance();
265
+ const problem = await signedPaymentProblem(paymentPayload, r, paymentRequired?.x402Version, cap);
266
+ if (!problem) return;
267
+ try { onRefuse?.({ reason: "signed-amount", priceUsd: null, allowanceUsd: cap, detail: problem }); } catch { /* the refusal stands */ }
268
+ throw new Error(`spending guard: ${problem}; the payment was not sent`);
269
+ });
155
270
  return client;
156
271
  }
package/output-schemas.js CHANGED
@@ -492,7 +492,7 @@ export function mcpJsonResult(obj) {
492
492
  * Hosted URL is parameterized; npm / Claude Code / Cursor notes
493
493
  * match docs/ecosystem-listings.md + wiki/MCP-Connector.md.
494
494
  */
495
- export const AGENT402_MCP_VERSION = "0.13.28";
495
+ export const AGENT402_MCP_VERSION = "0.13.29";
496
496
 
497
497
  /** A listed MCP tool description, at most `max` characters. Hosts truncate or
498
498
  * skip long descriptions, so the listing keeps the first whole sentences; the
@@ -524,12 +524,12 @@ export function mcpInstallHints(baseUrl) {
524
524
  mcpServers: {
525
525
  agent402: {
526
526
  command: "npx",
527
- args: ["-y", "agent402-mcp@0.13.28"],
527
+ args: ["-y", "agent402-mcp@0.13.29"],
528
528
  env: { AGENT_KEY: "0xYOUR_PRIVATE_KEY" },
529
529
  },
530
530
  },
531
531
  },
532
- npm: "npx -y agent402-mcp@0.13.28",
532
+ npm: "npx -y agent402-mcp@0.13.29",
533
533
  maintainer: "Havok Holdings LLC",
534
534
  };
535
535
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent402-mcp",
3
- "version": "0.13.28",
3
+ "version": "0.13.29",
4
4
  "mcpName": "io.github.MikeyPetrillo/agent402",
5
5
  "author": "Havok Holdings LLC <mike@agent402.tools> (https://agent402.tools)",
6
6
  "homepage": "https://agent402.tools",