agent402-mcp 0.13.29 → 0.13.30
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 +11 -4
- package/index.js +94 -25
- package/known-assets.js +66 -8
- package/output-schemas.js +3 -3
- package/package.json +1 -1
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.
|
|
12
|
+
claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.30
|
|
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.29
|
|
|
19
19
|
"mcpServers": {
|
|
20
20
|
"agent402": {
|
|
21
21
|
"command": "npx",
|
|
22
|
-
"args": ["-y", "agent402-mcp@0.13.
|
|
22
|
+
"args": ["-y", "agent402-mcp@0.13.30"],
|
|
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.29
|
|
|
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.
|
|
33
|
+
Claude Code with a wallet: `claude mcp add agent402 -s user -e AGENT_KEY=0xYOUR_PRIVATE_KEY -- npx -y agent402-mcp@0.13.30`
|
|
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).
|
|
@@ -80,7 +80,14 @@ seller that kept the authorization could still redeem it, so it counts against
|
|
|
80
80
|
(`https://agent402.tools`, matched by exact origin), an error status is never
|
|
81
81
|
settled, so a hold for one ends at the authorization's `validBefore` plus 10
|
|
82
82
|
minutes (15 minutes after the answer when no `validBefore` is readable). A held
|
|
83
|
-
amount whose authorization expires unused is released, never charged.
|
|
83
|
+
amount whose authorization expires unused is released, never charged. A payment
|
|
84
|
+
option asking to stay valid for more than a day is refused before anything is
|
|
85
|
+
signed, so no signed authorization outlives a day.
|
|
86
|
+
|
|
87
|
+
**Keys stay local.** `AGENT_KEY`, `SOLANA_AGENT_KEY` and `AGENT402_CREDITS_KEY`
|
|
88
|
+
are replaced with `[redacted]` wherever they would appear in a tool result, a
|
|
89
|
+
protocol error or a console line, and a key that does not parse is reported by
|
|
90
|
+
its variable name, not its value.
|
|
84
91
|
|
|
85
92
|
## Advanced
|
|
86
93
|
|
package/index.js
CHANGED
|
@@ -26,8 +26,9 @@
|
|
|
26
26
|
// Robinhood Chain, "base,solana", or a raw CAIP-2 like eip155:4663), optional
|
|
27
27
|
import { createHash } from "node:crypto";
|
|
28
28
|
import { readFileSync } from "node:fs";
|
|
29
|
+
import { format } from "node:util";
|
|
29
30
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
30
|
-
import { quoteOf, guardSigning } from "./known-assets.js";
|
|
31
|
+
import { quoteOf, guardSigning, signedExpirySeconds, MAX_VALIDITY_SECONDS } from "./known-assets.js";
|
|
31
32
|
import { parseNetworkPrefs, withNetworkPreference, distrustFetch } from "./networks.js";
|
|
32
33
|
import { fetchDiscovery, discoveryFailure, getDiscoveryJson } from "./discovery.js";
|
|
33
34
|
import { awaitJob, shouldRequestAsync, AsyncJobPendingError, DEFAULT_ASYNC_TIMEOUT_MS, jobState } from "./async-job.js";
|
|
@@ -88,6 +89,62 @@ const CREDITS_KEY = (process.env.AGENT402_CREDITS_KEY || "").trim();
|
|
|
88
89
|
const SHOW_ROUTER = HAS_WALLET || process.env.AGENT402_SHOW_ROUTER === "1";
|
|
89
90
|
const HIDDEN_WITHOUT_WALLET = new Set(["router.execute", META_MCP_NAMES.list_top_sellers]);
|
|
90
91
|
const HAS_CREDITS = /^a402_[A-Za-z0-9_-]{32,64}$/.test(CREDITS_KEY);
|
|
92
|
+
// The secrets this process holds never leave it in text: every tool result,
|
|
93
|
+
// every protocol error and every console line passes through redactSecrets,
|
|
94
|
+
// which replaces each configured key (and the spellings a library may print
|
|
95
|
+
// it in: without its 0x prefix, in either case, a byte array without spaces)
|
|
96
|
+
// with [redacted]. Key parsing also throws fixed messages that name the
|
|
97
|
+
// variable only (walletKeyError), since a parser's own message can quote its
|
|
98
|
+
// input.
|
|
99
|
+
const SECRET_FORMS = (() => {
|
|
100
|
+
const out = new Set();
|
|
101
|
+
for (const raw of [AGENT_KEY, SOLANA_AGENT_KEY, CREDITS_KEY]) {
|
|
102
|
+
const v = String(raw || "").trim();
|
|
103
|
+
if (v.length < 8) continue;
|
|
104
|
+
out.add(v);
|
|
105
|
+
const hex = v.replace(/^0x/i, "");
|
|
106
|
+
if (/^[0-9a-f]+$/i.test(hex) && hex.length >= 8) { out.add(hex); out.add(hex.toLowerCase()); out.add(hex.toUpperCase()); }
|
|
107
|
+
if (v.startsWith("[")) out.add(v.replace(/\s+/g, ""));
|
|
108
|
+
}
|
|
109
|
+
return [...out].sort((a, b) => b.length - a.length);
|
|
110
|
+
})();
|
|
111
|
+
function redactSecrets(text) {
|
|
112
|
+
let t = String(text);
|
|
113
|
+
for (const f of SECRET_FORMS) if (t.includes(f)) t = t.split(f).join("[redacted]");
|
|
114
|
+
return t;
|
|
115
|
+
}
|
|
116
|
+
/** A copy of a tool result (or any JSON value) with every string redacted. */
|
|
117
|
+
function redactDeep(v, depth = 0) {
|
|
118
|
+
if (!SECRET_FORMS.length) return v;
|
|
119
|
+
if (typeof v === "string") return redactSecrets(v);
|
|
120
|
+
if (depth > 64 || v == null || typeof v !== "object") return v;
|
|
121
|
+
if (Array.isArray(v)) return v.map((x) => redactDeep(x, depth + 1));
|
|
122
|
+
const out = {};
|
|
123
|
+
for (const [k, x] of Object.entries(v)) out[k] = redactDeep(x, depth + 1);
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
/** A handler whose answer, and whose thrown error's message, are redacted. */
|
|
127
|
+
const redacted = (handler) => async (req, extra) => {
|
|
128
|
+
try {
|
|
129
|
+
return redactDeep(await handler(req, extra));
|
|
130
|
+
} catch (e) {
|
|
131
|
+
if (SECRET_FORMS.length && e && typeof e.message === "string") {
|
|
132
|
+
try { e.message = redactSecrets(e.message); if (typeof e.stack === "string") e.stack = redactSecrets(e.stack); } catch { /* a frozen error */ throw new Error(redactSecrets(e.message)); }
|
|
133
|
+
}
|
|
134
|
+
throw e;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
// Every console line, a library's included, is redacted before it is written.
|
|
138
|
+
if (SECRET_FORMS.length) {
|
|
139
|
+
for (const m of ["log", "info", "warn", "error", "debug", "trace"]) {
|
|
140
|
+
const orig = console[m].bind(console);
|
|
141
|
+
console[m] = (...a) => orig(redactSecrets(format(...a)));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/** A fixed error for a key that does not parse: the variable's name, never
|
|
145
|
+
* the parser's message (it can quote the value). */
|
|
146
|
+
const walletKeyError = (name, what) => new Error(`${name} is set but is not ${what}; check the value (it is never printed)`);
|
|
147
|
+
|
|
91
148
|
// Slow paid routes (async.recommended on their /api/pricing row) are sent with
|
|
92
149
|
// Prefer: respond-async and collected from their job link (./async-job.js).
|
|
93
150
|
// AGENT402_ASYNC=off waits on the connection instead; =always uses a job on
|
|
@@ -114,7 +171,7 @@ const capFromEnv = (name, def) => {
|
|
|
114
171
|
if (raw === "off") return Infinity;
|
|
115
172
|
const n = Number(raw);
|
|
116
173
|
if (Number.isFinite(n) && n >= 0) return n;
|
|
117
|
-
console.error(`[agent402-mcp] ${name}=${JSON.stringify(process.env[name])} is not a USD amount or "off"; using the default (${def === Infinity ? "no cap" : `$${def}`})`);
|
|
174
|
+
console.error(`[agent402-mcp] ${name}=${String(process.env[name]).length <= 16 ? JSON.stringify(process.env[name]) : "(a long value, not shown)"} is not a USD amount or "off"; using the default (${def === Infinity ? "no cap" : `$${def}`})`);
|
|
118
175
|
return def;
|
|
119
176
|
};
|
|
120
177
|
const MAX_PER_CALL = capFromEnv("AGENT402_MAX_PER_CALL", DEFAULT_MAX_PER_CALL_USD);
|
|
@@ -136,12 +193,13 @@ const holds = []; // [{ usd, until }], until Infinity = the rest of the session
|
|
|
136
193
|
const holdPayment = (usd, until = Infinity) => { holds.push({ usd, until }); };
|
|
137
194
|
const heldNow = () => { const now = Date.now(); let t = 0; for (const h of holds) if (h.until > now) t += h.usd; return t; };
|
|
138
195
|
/** When a sent payload can no longer settle plus the clock slack: an EIP-3009
|
|
139
|
-
* validBefore or a Permit2 deadline, in seconds
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
196
|
+
* validBefore or a Permit2 deadline, in seconds, never later than
|
|
197
|
+
* MAX_VALIDITY_SECONDS from now (the signing guard refuses to send a payload
|
|
198
|
+
* valid for longer); null when none is readable. */
|
|
199
|
+
function signedValidUntilMs(paymentPayload, nowMs = Date.now()) {
|
|
200
|
+
const v = signedExpirySeconds(paymentPayload);
|
|
201
|
+
if (v == null || !Number.isFinite(v)) return null;
|
|
202
|
+
return Math.min(v * 1000, nowMs + MAX_VALIDITY_SECONDS * 1000) + HOLD_SLACK_MS;
|
|
145
203
|
}
|
|
146
204
|
// Wallet calls in flight, each holding what it may sign until it settles or
|
|
147
205
|
// fails, so concurrent calls cannot each pass against the same budget. The
|
|
@@ -248,7 +306,7 @@ function getPayFetch() {
|
|
|
248
306
|
if (AGENT_KEY) {
|
|
249
307
|
const { registerExactEvmScheme } = await import("@x402/evm/exact/client");
|
|
250
308
|
const { privateKeyToAccount } = await import("viem/accounts");
|
|
251
|
-
registerExactEvmScheme(client, { signer: privateKeyToAccount
|
|
309
|
+
registerExactEvmScheme(client, { signer: evmAccount(privateKeyToAccount) });
|
|
252
310
|
}
|
|
253
311
|
if (SOLANA_AGENT_KEY) {
|
|
254
312
|
const { registerExactSvmScheme } = await import("@x402/svm/exact/client");
|
|
@@ -265,6 +323,11 @@ function getPayFetch() {
|
|
|
265
323
|
return payFetchPromise;
|
|
266
324
|
}
|
|
267
325
|
|
|
326
|
+
/** The viem account for AGENT_KEY, or walletKeyError. */
|
|
327
|
+
function evmAccount(privateKeyToAccount) {
|
|
328
|
+
try { return privateKeyToAccount(AGENT_KEY.trim()); } catch { throw walletKeyError("AGENT_KEY", "a 0x-prefixed 32-byte hex private key"); }
|
|
329
|
+
}
|
|
330
|
+
|
|
268
331
|
// @solana/kit KeyPairSigner from SOLANA_AGENT_KEY, base58 64-byte secret key
|
|
269
332
|
// (Phantom / solana-keygen export) or a JSON byte array ([12,34,…]).
|
|
270
333
|
let solanaSignerPromise;
|
|
@@ -272,10 +335,14 @@ function solanaSigner() {
|
|
|
272
335
|
solanaSignerPromise ??= (async () => {
|
|
273
336
|
const { createKeyPairSignerFromBytes, getBase58Encoder } = await import("@solana/kit");
|
|
274
337
|
const raw = SOLANA_AGENT_KEY.trim();
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
338
|
+
try {
|
|
339
|
+
const bytes = raw.startsWith("[")
|
|
340
|
+
? Uint8Array.from(JSON.parse(raw))
|
|
341
|
+
: new Uint8Array(getBase58Encoder().encode(raw));
|
|
342
|
+
return await createKeyPairSignerFromBytes(bytes);
|
|
343
|
+
} catch {
|
|
344
|
+
throw walletKeyError("SOLANA_AGENT_KEY", "a base58 or JSON byte-array 64-byte Solana secret key");
|
|
345
|
+
}
|
|
279
346
|
})();
|
|
280
347
|
return solanaSignerPromise;
|
|
281
348
|
}
|
|
@@ -561,8 +628,10 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
|
|
|
561
628
|
function signingRefusal(tool, d) {
|
|
562
629
|
const text = d.reason === "unknown-asset"
|
|
563
630
|
? `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"
|
|
631
|
+
: d.reason === "signed-amount" || d.reason === "signed-validity"
|
|
565
632
|
? `Refused without paying: for "${tool.slug}", ${d.detail}, so the payment was not sent.`
|
|
633
|
+
: d.reason === "validity"
|
|
634
|
+
? `Refused without paying: for "${tool.slug}", ${d.detail}, so nothing was signed.`
|
|
566
635
|
: `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.`;
|
|
567
636
|
return { content: [{ type: "text", text }], isError: true };
|
|
568
637
|
}
|
|
@@ -689,7 +758,7 @@ const server = new Server(
|
|
|
689
758
|
// MCP-aware client. The list is fetched once at boot in loadCatalog(); the
|
|
690
759
|
// per-prompt rendering is delegated to the hosted service so the npm package
|
|
691
760
|
// stays thin and prompt text stays canonical with the website at /skills.
|
|
692
|
-
server.setRequestHandler(ListPromptsRequestSchema, async () => ({
|
|
761
|
+
server.setRequestHandler(ListPromptsRequestSchema, redacted(async () => ({
|
|
693
762
|
prompts: skillPacks.map((p) => ({
|
|
694
763
|
name: p.slug,
|
|
695
764
|
title: p.title,
|
|
@@ -700,8 +769,8 @@ server.setRequestHandler(ListPromptsRequestSchema, async () => ({
|
|
|
700
769
|
required: a.required ?? true,
|
|
701
770
|
})),
|
|
702
771
|
})),
|
|
703
|
-
}));
|
|
704
|
-
server.setRequestHandler(GetPromptRequestSchema, async (req) => {
|
|
772
|
+
})));
|
|
773
|
+
server.setRequestHandler(GetPromptRequestSchema, redacted(async (req) => {
|
|
705
774
|
const { name, arguments: args = {} } = req.params;
|
|
706
775
|
const pack = skillPacks.find((p) => p.slug === name);
|
|
707
776
|
if (!pack) throw new Error(`Unknown prompt "${name}". List available with prompts/list.`);
|
|
@@ -712,7 +781,7 @@ server.setRequestHandler(GetPromptRequestSchema, async (req) => {
|
|
|
712
781
|
const { res, attempts } = await fetchDiscovery(url);
|
|
713
782
|
if (!res.ok) throw new Error(`Failed to render prompt "${name}" from ${BASE}: ${discoveryFailure(url, res, attempts)}`);
|
|
714
783
|
return await res.json();
|
|
715
|
-
});
|
|
784
|
+
}));
|
|
716
785
|
|
|
717
786
|
let curated = [];
|
|
718
787
|
let pricingInfo = null;
|
|
@@ -747,7 +816,7 @@ async function ensureCatalog() {
|
|
|
747
816
|
}
|
|
748
817
|
const withCatalog = (handler) => async (req, extra) => { await ensureCatalog(); return handler(req, extra); };
|
|
749
818
|
|
|
750
|
-
server.setRequestHandler(ListToolsRequestSchema, withCatalog(async () => {
|
|
819
|
+
server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () => {
|
|
751
820
|
// Read-only only for lookups that stay on this machine (describe, payment
|
|
752
821
|
// info). Anything that reaches the network or can spend is NET: not read-only,
|
|
753
822
|
// open-world. A host reads readOnlyHint to decide whether to ask first.
|
|
@@ -878,9 +947,9 @@ server.setRequestHandler(ListToolsRequestSchema, withCatalog(async () => {
|
|
|
878
947
|
// AGENT402_SHOW_ROUTER=1 opts in. Calls to them still route when unlisted.
|
|
879
948
|
const listed = SHOW_ROUTER ? tools : tools.filter((t) => !HIDDEN_WITHOUT_WALLET.has(t.name));
|
|
880
949
|
return { tools: listed };
|
|
881
|
-
}));
|
|
950
|
+
})));
|
|
882
951
|
|
|
883
|
-
server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) => {
|
|
952
|
+
server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req, extra) => {
|
|
884
953
|
const { name: rawName, arguments: args = {} } = req.params;
|
|
885
954
|
const name = resolveListedName(rawName);
|
|
886
955
|
const overBound = toolInputBoundRefusal(rawName, args);
|
|
@@ -942,7 +1011,7 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
|
|
|
942
1011
|
let address = null;
|
|
943
1012
|
if (AGENT_KEY) {
|
|
944
1013
|
const { privateKeyToAccount } = await import("viem/accounts");
|
|
945
|
-
address = privateKeyToAccount
|
|
1014
|
+
try { address = evmAccount(privateKeyToAccount).address; } catch { address = "invalid AGENT_KEY"; }
|
|
946
1015
|
}
|
|
947
1016
|
let solanaAddress = null;
|
|
948
1017
|
if (SOLANA_AGENT_KEY) {
|
|
@@ -982,7 +1051,7 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
|
|
|
982
1051
|
claudeCodeHosted: `claude mcp add --transport http agent402 ${BASE}/mcp`,
|
|
983
1052
|
claudeCodeNpm: `claude mcp add agent402 -s user -- npx -y agent402-mcp@${AGENT402_MCP_VERSION}`,
|
|
984
1053
|
cursorHosted: { mcpServers: { agent402: { url: `${BASE}/mcp` } } },
|
|
985
|
-
npm: "npx -y agent402-mcp@0.13.
|
|
1054
|
+
npm: "npx -y agent402-mcp@0.13.30",
|
|
986
1055
|
maintainer: "Havok Holdings LLC",
|
|
987
1056
|
},
|
|
988
1057
|
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.`,
|
|
@@ -1002,7 +1071,7 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
|
|
|
1002
1071
|
install: {
|
|
1003
1072
|
claudeCodeHosted: `claude mcp add --transport http agent402 ${BASE}/mcp`,
|
|
1004
1073
|
claudeCodeNpm: `claude mcp add agent402 -s user -- npx -y agent402-mcp@${AGENT402_MCP_VERSION}`,
|
|
1005
|
-
npm: "npx -y agent402-mcp@0.13.
|
|
1074
|
+
npm: "npx -y agent402-mcp@0.13.30",
|
|
1006
1075
|
maintainer: "Havok Holdings LLC",
|
|
1007
1076
|
},
|
|
1008
1077
|
tools: catalog.size,
|
|
@@ -1143,7 +1212,7 @@ server.setRequestHandler(CallToolRequestSchema, withCatalog(async (req, extra) =
|
|
|
1143
1212
|
} catch (err) {
|
|
1144
1213
|
return { content: [{ type: "text", text: `Agent402 call failed: ${err.message}` }], isError: true };
|
|
1145
1214
|
}
|
|
1146
|
-
}));
|
|
1215
|
+
})));
|
|
1147
1216
|
|
|
1148
1217
|
// ---------------------------------------------------------------------------
|
|
1149
1218
|
try {
|
package/known-assets.js
CHANGED
|
@@ -134,6 +134,51 @@ export function quoteOf(accepts, x402Version = undefined) {
|
|
|
134
134
|
return { max, min, unknown, total: accepts.length };
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
// The longest a signed payment may stay redeemable. An EVM "exact" signer
|
|
138
|
+
// sets validBefore (EIP-3009) or deadline (Permit2) to the moment of signing
|
|
139
|
+
// plus the accept's maxTimeoutSeconds, and the signed payload is a bearer
|
|
140
|
+
// claim until then, so a seller that quotes years gets an authorization it
|
|
141
|
+
// could redeem for years and a held amount that never stops counting. Honest
|
|
142
|
+
// accepts ask for minutes (Agent402's own ask 300 s); a day admits every
|
|
143
|
+
// one of them. An accept that asks for longer is dropped before selection,
|
|
144
|
+
// and a payload signed past it is refused before it is sent.
|
|
145
|
+
export const MAX_VALIDITY_SECONDS = 24 * 3600;
|
|
146
|
+
// Signing reads the clock a moment before the check after it does.
|
|
147
|
+
const VALIDITY_CLOCK_SLACK_SECONDS = 60;
|
|
148
|
+
|
|
149
|
+
/** True when an accept asks for a validity window past MAX_VALIDITY_SECONDS.
|
|
150
|
+
* An accept with no readable maxTimeoutSeconds is left to the check of what
|
|
151
|
+
* was signed (signedValidityProblem). */
|
|
152
|
+
export function acceptValidityTooLong(accept, maxSeconds = MAX_VALIDITY_SECONDS) {
|
|
153
|
+
const raw = accept?.maxTimeoutSeconds;
|
|
154
|
+
if (raw == null || raw === "") return false;
|
|
155
|
+
const n = Number(raw);
|
|
156
|
+
return !Number.isFinite(n) || n > maxSeconds;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The expiry a signed payload carries, in unix seconds: an EIP-3009
|
|
160
|
+
* `authorization.validBefore` or a Permit2 `deadline`. null when the payload
|
|
161
|
+
* names none (a Solana transaction, an unknown scheme). NaN when it names
|
|
162
|
+
* one that is not a whole number of seconds. */
|
|
163
|
+
export function signedExpirySeconds(paymentPayload) {
|
|
164
|
+
const p = paymentPayload?.payload;
|
|
165
|
+
const v = p?.authorization?.validBefore ?? p?.permit2Authorization?.deadline;
|
|
166
|
+
if (v == null) return null;
|
|
167
|
+
return /^\d{1,15}$/.test(String(v)) ? Number(v) : NaN;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Why a created payment payload stays redeemable for too long, or null: its
|
|
171
|
+
* expiry is past `nowMs` plus `maxSeconds` (and a minute of clock slack), or
|
|
172
|
+
* it names an expiry that cannot be read. */
|
|
173
|
+
export function signedValidityProblem(paymentPayload, { maxSeconds = MAX_VALIDITY_SECONDS, nowMs = Date.now() } = {}) {
|
|
174
|
+
const exp = signedExpirySeconds(paymentPayload);
|
|
175
|
+
if (exp == null) return null;
|
|
176
|
+
if (!Number.isFinite(exp)) return "the signed authorization's expiry cannot be read";
|
|
177
|
+
const left = exp - Math.floor(nowMs / 1000);
|
|
178
|
+
if (left > maxSeconds + VALIDITY_CLOCK_SLACK_SECONDS) return `the signed authorization stays valid for ${left} seconds, past the ${maxSeconds}-second ceiling`;
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
137
182
|
/** Enforce a USD allowance at signing on an @x402/core x402Client.
|
|
138
183
|
*
|
|
139
184
|
* `allowance()` is the most this buyer may sign for the payment being built
|
|
@@ -141,8 +186,10 @@ export function quoteOf(accepts, x402Version = undefined) {
|
|
|
141
186
|
* for none). A registered policy drops every accept that cannot be priced or
|
|
142
187
|
* is over the allowance, so the client selects among the ones that fit, and a
|
|
143
188
|
* hook before payload creation checks the selected accept again and passes
|
|
144
|
-
* its USD value to `onSign`.
|
|
145
|
-
*
|
|
189
|
+
* its USD value to `onSign`. An accept asking for a validity window past
|
|
190
|
+
* MAX_VALIDITY_SECONDS is dropped and refused the same way. A refusal throws
|
|
191
|
+
* (from the policy) or aborts (from the hook) before any signature exists;
|
|
192
|
+
* `onRefuse` hears why first. */
|
|
146
193
|
export function guardSigning(client, { allowance, onSign = null, onRefuse = null }) {
|
|
147
194
|
if (!client || typeof client.registerPolicy !== "function" || typeof client.onBeforePaymentCreation !== "function") {
|
|
148
195
|
throw new TypeError("guardSigning needs an @x402/core x402Client (registerPolicy and onBeforePaymentCreation)");
|
|
@@ -151,7 +198,12 @@ export function guardSigning(client, { allowance, onSign = null, onRefuse = null
|
|
|
151
198
|
const refuse = (detail) => { try { onRefuse?.(detail); } catch { /* the refusal stands */ } return detail; };
|
|
152
199
|
client.registerPolicy((version, accepts) => {
|
|
153
200
|
const cap = allowance();
|
|
154
|
-
const
|
|
201
|
+
const priced = accepts.filter((a) => { const usd = acceptUsd(a, version); return usd != null && usd <= cap; });
|
|
202
|
+
const kept = priced.filter((a) => !acceptValidityTooLong(a));
|
|
203
|
+
if (!kept.length && priced.length) {
|
|
204
|
+
const d = refuse({ reason: "validity", priceUsd: null, allowanceUsd: cap, detail: `every payment option it may sign asks to stay valid for more than ${MAX_VALIDITY_SECONDS} seconds` });
|
|
205
|
+
throw new Error(`spending guard: ${d.detail}; nothing was signed`);
|
|
206
|
+
}
|
|
155
207
|
if (!kept.length) {
|
|
156
208
|
const q = quoteOf(accepts, version);
|
|
157
209
|
const d = refuse({ reason: q && q.min != null ? "over-allowance" : "unknown-asset", priceUsd: q ? q.min : null, allowanceUsd: cap });
|
|
@@ -172,6 +224,10 @@ export function guardSigning(client, { allowance, onSign = null, onRefuse = null
|
|
|
172
224
|
refuse({ reason: "over-allowance", priceUsd: usd, allowanceUsd: cap });
|
|
173
225
|
return { abort: true, reason: `spending guard: the selected payment option asks $${usd}, above the $${cap} this buyer may sign; nothing was signed` };
|
|
174
226
|
}
|
|
227
|
+
if (acceptValidityTooLong(r)) {
|
|
228
|
+
const d = refuse({ reason: "validity", priceUsd: usd, allowanceUsd: cap, detail: `the selected payment option asks to stay valid for ${r.maxTimeoutSeconds} seconds, past the ${MAX_VALIDITY_SECONDS}-second ceiling` });
|
|
229
|
+
return { abort: true, reason: `spending guard: ${d.detail}; nothing was signed` };
|
|
230
|
+
}
|
|
175
231
|
onSign?.(usd, r);
|
|
176
232
|
return undefined;
|
|
177
233
|
});
|
|
@@ -252,9 +308,10 @@ export async function signedPaymentProblem(paymentPayload, requirements, x402Ver
|
|
|
252
308
|
}
|
|
253
309
|
|
|
254
310
|
/** Refuse to send a payment payload whose signed amount is not the one the
|
|
255
|
-
* allowance passed
|
|
256
|
-
*
|
|
257
|
-
*
|
|
311
|
+
* allowance passed, or whose expiry is past MAX_VALIDITY_SECONDS from now
|
|
312
|
+
* (signedValidityProblem): registered after payload creation, so the check
|
|
313
|
+
* reads what was actually signed, and a throw here stops the payment-aware
|
|
314
|
+
* fetch before the payload leaves the process. guardSigning registers it; a
|
|
258
315
|
* client with its own selector (and no guardSigning) can register it alone. */
|
|
259
316
|
export function guardSignedAmount(client, { allowance = () => Infinity, onRefuse = null } = {}) {
|
|
260
317
|
if (!client || typeof client.onAfterPaymentCreation !== "function") {
|
|
@@ -262,9 +319,10 @@ export function guardSignedAmount(client, { allowance = () => Infinity, onRefuse
|
|
|
262
319
|
}
|
|
263
320
|
client.onAfterPaymentCreation(async ({ paymentRequired, selectedRequirements: r, paymentPayload }) => {
|
|
264
321
|
const cap = allowance();
|
|
265
|
-
const
|
|
322
|
+
const amountProblem = await signedPaymentProblem(paymentPayload, r, paymentRequired?.x402Version, cap);
|
|
323
|
+
const problem = amountProblem || signedValidityProblem(paymentPayload);
|
|
266
324
|
if (!problem) return;
|
|
267
|
-
try { onRefuse?.({ reason: "signed-amount", priceUsd: null, allowanceUsd: cap, detail: problem }); } catch { /* the refusal stands */ }
|
|
325
|
+
try { onRefuse?.({ reason: amountProblem ? "signed-amount" : "signed-validity", priceUsd: null, allowanceUsd: cap, detail: problem }); } catch { /* the refusal stands */ }
|
|
268
326
|
throw new Error(`spending guard: ${problem}; the payment was not sent`);
|
|
269
327
|
});
|
|
270
328
|
return client;
|
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.
|
|
495
|
+
export const AGENT402_MCP_VERSION = "0.13.30";
|
|
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.
|
|
527
|
+
args: ["-y", "agent402-mcp@0.13.30"],
|
|
528
528
|
env: { AGENT_KEY: "0xYOUR_PRIVATE_KEY" },
|
|
529
529
|
},
|
|
530
530
|
},
|
|
531
531
|
},
|
|
532
|
-
npm: "npx -y agent402-mcp@0.13.
|
|
532
|
+
npm: "npx -y agent402-mcp@0.13.30",
|
|
533
533
|
maintainer: "Havok Holdings LLC",
|
|
534
534
|
};
|
|
535
535
|
}
|
package/package.json
CHANGED