agent402-mcp 0.13.31 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # agent402-mcp
2
2
 
3
- MCP server for [Agent402](https://agent402.tools), the applied layer of Agentic Finance: a catalog of **500+ web tools** that AI agents call one request at a time, paid per call in USDC over x402 or MPP (Machine Payments Protocol). Pure-CPU tools are free: each call solves a small proof-of-work puzzle on your own machine. Other tools are paid per call in USDC over the [x402 protocol](https://www.x402.org) from a wallet you control. Built by [Havok Holdings LLC](https://github.com/MikeyPetrillo/Agent402).
3
+ MCP server for [Agent402](https://agent402.tools), the applied layer of Agentic Finance. Agent402 is a catalog of 500+ tools that AI agents find, pay for per request over x402 or MPP, and call with no account or API key. Paid calls settle in USDC over x402 or MPP (Machine Payments Protocol). Pure-CPU tools are free: each call solves a small proof-of-work puzzle on your own machine. Other tools are paid per call in USDC over the [x402 protocol](https://www.x402.org) from a wallet you control. Built by [Havok Holdings LLC](https://github.com/MikeyPetrillo/Agent402).
4
4
 
5
5
  ## Quick start
6
6
 
@@ -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.31
12
+ claude mcp add agent402 -s user -- npx -y agent402-mcp@0.14.0
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.31
19
19
  "mcpServers": {
20
20
  "agent402": {
21
21
  "command": "npx",
22
- "args": ["-y", "agent402-mcp@0.13.31"],
22
+ "args": ["-y", "agent402-mcp@0.14.0"],
23
23
  "env": { "AGENT_KEY": "0xYOUR_PRIVATE_KEY" }
24
24
  }
25
25
  }
@@ -28,9 +28,9 @@ claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.31
28
28
 
29
29
  > Use a new wallet holding only a few dollars of USDC. Never use your main wallet.
30
30
 
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`.
31
+ Use `SOLANA_AGENT_KEY` instead for USDC on Solana. Each call is capped at $5 by default to protect your wallet (`AGENT402_MAX_PER_CALL`, `0` or `off` turns it off); 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.31`
33
+ Claude Code with a wallet: `claude mcp add agent402 -s user -e AGENT_KEY=0xYOUR_PRIVATE_KEY -- npx -y agent402-mcp@0.14.0`
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).
@@ -46,8 +46,8 @@ Every variable the server reads (all optional):
46
46
  | `AGENT402_CREDITS_KEY` | _(unset)_ | A prepaid credits key (`a402_...`; [agent402.tools/credits](https://agent402.tools/credits) says whether packs are on sale). Sent as `Authorization: Bearer` on every catalog call; the server debits the list price only on a successful (200) call and answers `X-Credits-Balance`. Used only when no wallet key is set (a wallet key wins); in credits mode every call - pure-CPU tools included - is debited from the key. Credits pay Agent402's own services only: `router.execute`, `seller-payability`, `decide.execute` and the flight tools buy from outside sellers and need a wallet key, and memory and usage need a wallet identity. |
47
47
  | `AGENT402_URL` | `https://agent402.tools` | Target service (point at your own deployment). Paid calls never follow redirects, so use the address that serves the routes directly; a redirect is refused with the origin to use. |
48
48
  | `AGENT402_TOOLS` | curated set | Comma-separated slugs to expose as first-class tools. |
49
- | `AGENT402_MAX_PER_CALL` | `4` | Refuse any single call priced above this many USD (e.g. `0.05`); `off` disables it. Applies to the wallet and the credits path. |
50
- | `AGENT402_BUDGET` | _(unset, no cap)_ | Optional hard cap on total USD spent per session (e.g. `1.00`); unset or `off` means no session cap. Applies to the wallet and the credits path. |
49
+ | `AGENT402_MAX_PER_CALL` | `5` | Refuse any single call priced above this many USD (e.g. `0.05`); `0` or `off` disables it. A call it refuses names the price, the cap and the setting to raise. Applies to the wallet and the credits path. |
50
+ | `AGENT402_BUDGET` | _(unset, no cap)_ | Optional hard cap on total USD spent per session (e.g. `1.00`); unset or `off` means no session cap. A call it refuses names the setting to raise. Applies to the wallet and the credits path. |
51
51
  | `AGENT402_SHOW_ROUTER` | _(unset)_ | `1` lists `router.execute` and `sellers.list` even without a wallet. Both are listed automatically when a wallet key is set; a credits key does not pay `router.execute`, which buys from outside sellers and takes a wallet payment. |
52
52
  | `AGENT402_NETWORKS` | _(unset)_ | Restrict + order the chains to pay on - e.g. `robinhood` (USDG on Robinhood Chain), `base,solana`, or a raw CAIP-2 like `eip155:4663`. Unset = the client picks (effectively Base on multi-chain sellers). |
53
53
  | `AGENT402_ASYNC` | `auto` | Slow routes (reports, video, the premium image; `async.recommended` on their `/api/pricing` row) are paid with `Prefer: respond-async` and collected from their job link, so a long run never outlives the connection. `off` waits on the connection instead (since 0.13.18 sending `Prefer: wait=<maxSeconds>` where the row gives `async.preferWait`); `always` uses a job on every route that runs as one. |
@@ -61,16 +61,17 @@ per-call cap or what is left of the budget, so the 402 the wallet signs is held
61
61
  to the caps, and a wallet call sends no unpaid preflight first. Each option is priced from the
62
62
  known decimals of its asset (USDC on each rail, USDG on Robinhood Chain), never
63
63
  from a decimals value in the challenge, and an option in any other asset is not
64
- signed. A value that is not a USD amount or `off` reads as the default (the
65
- $4 per-call cap and no session budget). Set `AGENT402_BUDGET` to cap the session total.
64
+ signed. A value that is not a USD amount, `0` or `off` (text, a negative number, an
65
+ empty string) keeps the default, the $5 per-call cap and no session budget, and the
66
+ server names the variable on stderr. Set `AGENT402_BUDGET` to cap the session total.
66
67
  `payment.info` reports the caps, what's been spent, and what remains. With no wallet key and no credits key,
67
68
  the server runs in proof-of-work mode (pure-CPU tools stay free). Use dedicated
68
69
  low-value wallets for `AGENT_KEY` / `SOLANA_AGENT_KEY`, funded only with what
69
70
  you intend to spend. Most tools cost $0.001 to $0.02. The routing tiers top out
70
71
  at $3.30 (`route-execute-pro`); multi-tool skill packs run $0.003 to $0.101; and the
71
72
  report products run $0.60 to $2.00 per report (domain-audit $0.60 up to the ticker pack at $2.00),
72
- so the default per-call cap of $4 covers every tool; set `AGENT402_MAX_PER_CALL` lower for a
73
- tighter ceiling.
73
+ so the default per-call cap of $5 covers every tool; set `AGENT402_MAX_PER_CALL` lower for a
74
+ tighter ceiling, or `off` for none.
74
75
 
75
76
  **Held payments.** `payment.info` reports `heldThisSessionUsd`: money a wallet
76
77
  call sent a signed payment for without a confirmed answer (an error status, a
@@ -107,7 +108,12 @@ its variable name, not its value.
107
108
  - The rest of the 500+ tool catalog is reachable via the meta tools `catalog.search` / `catalog.find` + `catalog.call` - keeping your context window small. The same dotted names are listed on the hosted connector; the older snake names (`search_tools`, `find_tool`, `call_tool`, `get_payment_info`, `describe_server`, `list_top_sellers`, and the flagship `search_web` …) remain accepted as CallTool aliases, so existing configs keep working.
108
109
  - When a call hits HTTP 402: with a wallet key set (`AGENT_KEY` for the EVM chains, Robinhood Chain included; `SOLANA_AGENT_KEY` for Solana), the server signs an x402 payment on a chain the seller accepts and retries; with only a credits key it sends `Authorization: Bearer a402_…` and the server debits the balance on success; with neither it solves the tool's proof-of-work challenge (~0.2 s of CPU) on the eligible tools. (The service settles USDC on Base, Solana, Polygon, Arbitrum, Monad, Celo, Avalanche, Sei, Optimism, Arc, Ink, Stellar and Algorand, plus USDG on Robinhood Chain - 14 chains total - for callers using a raw x402 client rather than this package. Where the server also offers a Circle Gateway batched accept on Arc or Base, this package pays the plain accept beside it.)
109
110
  - Since 0.13.15 the server's requests to the catalog and to sellers (catalog reads, the 402 and the paid retry) refuse a TLS chain through one of the intermediate CAs listed in `networks.js` (keys reported recoverable in Mozilla bug 2083449), keyed on each certificate's SubjectPublicKeyInfo hash, on a dedicated dispatcher. With a proxy or custom dispatcher installed, requests go out through it unchanged.
110
- - **Slow routes run as jobs** (since 0.13.17): a paid call to a route the catalog marks slow carries `Prefer: respond-async`, answers `202` with a job link, and the server polls `GET /api/jobs/{id}` (free), waiting `Retry-After` seconds between polls, until the answer is ready, reading the job's `state` and falling back to its `status`. Payment settles only on the delivered answer. A caller that sends a `progressToken` gets `notifications/progress` from the job's stage, steps and ETA. A job still running when `AGENT402_ASYNC_TIMEOUT_MS` ends comes back with its `jobUrl` instead.
111
+ - **Slow routes run as jobs** (since 0.13.17): a paid call to a route the catalog marks slow carries `Prefer: respond-async`, answers `202` with a job link, and the server polls `GET /api/jobs/{id}` (free), waiting `Retry-After` seconds between polls, until the answer is ready, reading the job's `state` and falling back to its `status`. The x402 payment settles only on the delivered answer. A caller that sends a `progressToken` gets `notifications/progress` from the job's stage, steps and ETA. A job still running when `AGENT402_ASYNC_TIMEOUT_MS` ends comes back with its `jobUrl` instead.
112
+ - Proof-of-work challenges are solved on a worker thread, so the server keeps answering while it searches, and a challenge asking for more than 28 bits (the most an Agent402 server asks) is refused rather than searched (since 0.14.0).
113
+ - `catalog.search` returns at most 25 results (`limit`, default 10); `catalog.call` and `router.execute` take `params` as an object or as a JSON string of one, for hosts that serialize nested arguments (since 0.14.0).
114
+ - Tool annotations match the hosted connector's: the catalog lookups, `payment.info` and `server.describe` are read-only; `catalog.call` and `router.execute` can run a tool that writes, deletes or buys, so they are marked destructive, as is `memory.write`.
115
+ - At start, a wallet key that does not parse is named in the log (never printed) instead of being reported as a configured wallet.
116
+ - TypeScript: `index.d.ts` types the configuration (`Agent402McpEnv`) and the tools' `structuredContent` (`CatalogSearchResult`, `CatalogFindResult`, `PaymentInfoResult`, ...) for code that drives this server through an MCP client.
111
117
  - `payment.info` tells the model which mode it's in and what a wallet or a credits key would unlock.
112
118
  - `server.describe` returns orientation (flagship-first tools, install one-liners, free vs paid, discovery URLs). Call it first.
113
119
  - `sellers.list` returns the live leaderboards - `wire: "x402"` (default) ranks x402 sellers settling the most USDC (primarily on Base) in the last ~24h from on-chain transfers; `wire: "mpp"` ranks live-verified MPP sellers by inbound USDC.e transfers on Tempo. Free to call (no payment, no proof-of-work). Useful for agents discovering the wider x402 / MPP economy beyond this single service's catalog.
package/async-job.js CHANGED
@@ -12,7 +12,9 @@
12
12
  // on a delivered result, which may still happen).
13
13
  //
14
14
  // The job link must be on the same origin as the server: a Location naming
15
- // another host is refused rather than fetched.
15
+ // another host is refused rather than fetched, and so is a redirect on a poll
16
+ // that points off the origin (each hop is read with redirect: "manual" and its
17
+ // target checked before it is fetched).
16
18
  //
17
19
  // Kept in lockstep with client/async-job.js (agent402-client).
18
20
 
@@ -53,6 +55,36 @@ function sameOrigin(url, baseUrl) {
53
55
  try { return new URL(url).origin === new URL(baseUrl).origin; } catch { return false; }
54
56
  }
55
57
 
58
+ const MAX_POLL_REDIRECTS = 5;
59
+ // One poll of the job link. Redirects are followed by hand, each hop's target
60
+ // checked against the server's origin first; a hop off the origin, an opaque
61
+ // redirect (a browser's "manual" answer, which hides its target) or too many
62
+ // hops throws instead of fetching. A fetch that followed a redirect anyway is
63
+ // refused when it landed off the origin.
64
+ async function pollJobLink(fetchImpl, jobUrl, baseUrl, slug, doc) {
65
+ let url = jobUrl;
66
+ for (let hop = 0; ; hop++) {
67
+ const g = await fetchImpl(url, { headers: { Accept: "application/json" }, redirect: "manual" });
68
+ if (!g) return g;
69
+ if (g.redirected && g.url && !sameOrigin(g.url, baseUrl)) {
70
+ throw new AsyncJobPendingError(`the job link for "${slug}" redirected to another origin; it was not followed`, { jobUrl, slug, job: doc });
71
+ }
72
+ const redirect = g.type === "opaqueredirect" || (g.status >= 300 && g.status < 400 && g.status !== 304);
73
+ if (!redirect) return g;
74
+ const loc = g.headers && typeof g.headers.get === "function" ? g.headers.get("location") : null;
75
+ let next = null;
76
+ try { next = loc ? new URL(loc, url).href : null; } catch { next = null; }
77
+ if (!next || !sameOrigin(next, baseUrl) || hop >= MAX_POLL_REDIRECTS) {
78
+ // A browser's opaque redirect hides its target: where it pointed is unknown.
79
+ const msg = !next && g.type === "opaqueredirect"
80
+ ? `the job link for "${slug}" answered with a redirect this client could not follow (its target is hidden here)`
81
+ : `the job link for "${slug}" redirected ${!next ? "with no readable target" : sameOrigin(next, baseUrl) ? "too many times" : "to another origin"}; it was not followed`;
82
+ throw new AsyncJobPendingError(msg, { jobUrl, slug, job: doc });
83
+ }
84
+ url = next;
85
+ }
86
+ }
87
+
56
88
  // The job's lifecycle: `state` (queued | running | succeeded | failed) when
57
89
  // the server sends it, else the original `status` (working | completed | failed).
58
90
  const STATUS_TO_STATE = { working: "running", completed: "succeeded", failed: "failed", cancelled: "failed" };
@@ -105,8 +137,8 @@ export async function awaitJob(res, { baseUrl, fetchImpl, timeoutMs = DEFAULT_AS
105
137
  }
106
138
  await sleep(wait);
107
139
  let g;
108
- try { g = await fetchImpl(jobUrl, { headers: { Accept: "application/json" } }); }
109
- catch { g = null; }
140
+ try { g = await pollJobLink(fetchImpl, jobUrl, baseUrl, slug, doc); }
141
+ catch (e) { if (e instanceof AsyncJobPendingError) throw e; g = null; }
110
142
  if (!g || g.status >= 500 || g.status === 429) {
111
143
  if (++failures >= MAX_POLL_FAILURES) throw new AsyncJobPendingError(`the job link for "${slug}" could not be read (${g ? `HTTP ${g.status}` : "network error"}); collect it from ${jobUrl}`, { jobUrl, slug, job: doc });
112
144
  wait = retryAfterMs(g?.headers, doc);
package/index.d.ts ADDED
@@ -0,0 +1,123 @@
1
+ // Type declarations for agent402-mcp. The package is an MCP server run as a
2
+ // command (npx agent402-mcp), so it exports no runtime values; these types
3
+ // describe its configuration and the structuredContent of the tools it lists,
4
+ // for code that drives it through an MCP client.
5
+
6
+ /** Environment the server reads at start. */
7
+ export interface Agent402McpEnv {
8
+ /** Target service (default https://agent402.tools). */
9
+ AGENT402_URL?: string;
10
+ /** Hex private key of a funded EVM wallet (USDC). */
11
+ AGENT_KEY?: string;
12
+ /** Base58 or JSON byte-array secret key of a funded Solana wallet (USDC). */
13
+ SOLANA_AGENT_KEY?: string;
14
+ /** Comma-separated slugs listed first-class (replaces the default set). */
15
+ AGENT402_TOOLS?: string;
16
+ /** Refuse a single call above this many USD (default "5"; "0" or "off" means none). */
17
+ AGENT402_MAX_PER_CALL?: string;
18
+ /** Optional cap on USD spent this session (no cap unless set; "off" means none). */
19
+ AGENT402_BUDGET?: string;
20
+ /** A prepaid credits key (a402_...). */
21
+ AGENT402_CREDITS_KEY?: string;
22
+ /** "1" lists router.execute and sellers.list without a wallet. */
23
+ AGENT402_SHOW_ROUTER?: string;
24
+ /** Restrict and order the chains paid on, e.g. "base,solana" or "eip155:4663". */
25
+ AGENT402_NETWORKS?: string;
26
+ /** "auto" (default), "off" or "always": run slow routes as jobs. */
27
+ AGENT402_ASYNC?: string;
28
+ /** Overall wait for a job in ms. */
29
+ AGENT402_ASYNC_TIMEOUT_MS?: string;
30
+ }
31
+
32
+ /** Names this server lists in tools/list. */
33
+ export type Agent402McpToolName =
34
+ | "catalog.search" | "catalog.find" | "catalog.call"
35
+ | "payment.info" | "server.describe" | "sellers.list" | "router.execute"
36
+ | "web.search" | "web.answer" | "web.news" | "browser.render" | "market.quote"
37
+ | "audio.transcribe" | "memory.read" | "memory.write" | "decide.plan" | "decide.execute";
38
+
39
+ /** catalog.search arguments. `limit` is clamped to 1..25 (default 10). */
40
+ export interface CatalogSearchArgs { query: string; limit?: number }
41
+ export interface CatalogSearchHit {
42
+ slug: string;
43
+ method: string;
44
+ path: string;
45
+ price: string;
46
+ payment: string;
47
+ description: string;
48
+ inputSchema: Record<string, unknown>;
49
+ }
50
+ export interface CatalogSearchResult {
51
+ results: CatalogSearchHit[];
52
+ workflows?: Array<{ slug: string; title?: string; tagline?: string; toolCount: number; promptName: string; score: number }>;
53
+ workflowsUsage?: string;
54
+ usage?: string;
55
+ message?: string;
56
+ }
57
+
58
+ /** catalog.find arguments. `limit` is clamped to 1..25 (default 5). */
59
+ export interface CatalogFindArgs { task: string; limit?: number }
60
+ export interface CatalogFindMatch {
61
+ slug: string;
62
+ name?: string;
63
+ price?: string;
64
+ description?: string;
65
+ example?: unknown;
66
+ required?: string[];
67
+ inputSchema?: Record<string, unknown>;
68
+ callWith: { name: "catalog.call"; arguments: { slug: string; params: Record<string, unknown> } };
69
+ }
70
+ export interface CatalogFindResult {
71
+ task: string;
72
+ matches: CatalogFindMatch[];
73
+ results: CatalogFindMatch[];
74
+ workflows?: unknown[];
75
+ usage: string;
76
+ }
77
+
78
+ /** catalog.call arguments: `params` is an object, or a JSON string of one. */
79
+ export interface CatalogCallArgs { slug: string; params?: Record<string, unknown> | string }
80
+ export interface CatalogCallResult<T = unknown> { slug: string; result: T }
81
+
82
+ /** router.execute arguments. */
83
+ export interface RouterExecuteArgs { task: string; params?: Record<string, unknown> | string; maxUsd?: number }
84
+
85
+ export interface SpendControls {
86
+ maxPerCallUsd: number | "unlimited";
87
+ sessionBudgetUsd: number | "unlimited";
88
+ spentThisSessionUsd: number;
89
+ heldThisSessionUsd: number;
90
+ remainingUsd: number | "unlimited";
91
+ }
92
+ export interface PaymentInfoResult {
93
+ service: string;
94
+ mode: "usdc" | "credits" | "proof-of-work";
95
+ wallet: string | null;
96
+ solanaWallet: string | null;
97
+ network: string;
98
+ networks?: unknown;
99
+ tools: number;
100
+ payableWithCompute: number;
101
+ walletOnly: number;
102
+ workflows: number;
103
+ credits: Record<string, unknown>;
104
+ spendControls: SpendControls | string;
105
+ note: string;
106
+ install: Record<string, unknown>;
107
+ positioning: string;
108
+ ecosystem: string;
109
+ }
110
+
111
+ export interface SellersListArgs { limit?: number; sort?: "usd" | "calls"; include?: "external" | "all"; wire?: "x402" | "mpp" }
112
+ export interface SellersListResult {
113
+ window: string | null;
114
+ asOf: string | null;
115
+ sort: string;
116
+ include: string;
117
+ totalSellers: number;
118
+ results: Array<Record<string, unknown> & { untrustedContent?: true }>;
119
+ containsUntrustedContent?: true;
120
+ note?: string;
121
+ source: string;
122
+ wire?: "mpp";
123
+ }
package/index.js CHANGED
@@ -16,7 +16,7 @@
16
16
  // AGENT_KEY hex private key of a funded EVM wallet (USDC on Base/Polygon/Arbitrum), optional
17
17
  // SOLANA_AGENT_KEY base58 (or JSON byte-array) secret key of a funded Solana wallet (USDC on Solana), optional
18
18
  // AGENT402_TOOLS comma-separated slugs to expose first-class (overrides default)
19
- // AGENT402_MAX_PER_CALL refuse any single call priced above this many USD (default 4; off disables)
19
+ // AGENT402_MAX_PER_CALL refuse any single call priced above this many USD (default 5; 0 or off disables)
20
20
  // AGENT402_CREDITS_KEY a prepaid credits key (a402_...); pays per successful call with no wallet,
21
21
  // on Agent402's own services only (outside-seller routes need a wallet)
22
22
  // AGENT402_BUDGET optional hard cap on total USD spent this session (no cap by default)
@@ -24,7 +24,6 @@
24
24
  // when a wallet or credits key is set)
25
25
  // AGENT402_NETWORKS restrict + order the chains to pay on (e.g. "robinhood" for USDG on
26
26
  // Robinhood Chain, "base,solana", or a raw CAIP-2 like eip155:4663), optional
27
- import { createHash } from "node:crypto";
28
27
  import { readFileSync } from "node:fs";
29
28
  import { format } from "node:util";
30
29
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -32,16 +31,15 @@ import { quoteOf, guardSigning, signedExpirySeconds, MAX_VALIDITY_SECONDS } from
32
31
  import { parseNetworkPrefs, withNetworkPreference, distrustFetch } from "./networks.js";
33
32
  import { fetchDiscovery, discoveryFailure, getDiscoveryJson } from "./discovery.js";
34
33
  import { awaitJob, shouldRequestAsync, AsyncJobPendingError, DEFAULT_ASYNC_TIMEOUT_MS, jobState } from "./async-job.js";
35
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
36
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
37
- import {
38
- CallToolRequestSchema,
39
- ListToolsRequestSchema,
40
- ListPromptsRequestSchema,
41
- GetPromptRequestSchema,
42
- McpError,
43
- ErrorCode,
44
- } from "@modelcontextprotocol/sdk/types.js";
34
+ import { solvePowAsync } from "./pow-solver.js";
35
+ // MCP SDK v2 (@modelcontextprotocol/server, pinned exactly in package.json).
36
+ // Handlers are registered by method name. The server answers the 2024-11-05
37
+ // through 2025-11-25 revisions it did under SDK v1, and the SDK lifts every
38
+ // io.modelcontextprotocol/* key out of params._meta before a handler runs, so
39
+ // a handler that needs one reads it from the raw message (this server reads
40
+ // none: progressToken is not such a key).
41
+ import { Server, ProtocolError, ProtocolErrorCode as ErrorCode } from "@modelcontextprotocol/server";
42
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
45
43
  import {
46
44
  FLAGSHIP_MCP_NAMES,
47
45
  META_MCP_NAMES,
@@ -53,11 +51,18 @@ import {
53
51
  mcpJsonResult,
54
52
  outputSchemaFromExample,
55
53
  mcpInitializeInstructions,
54
+ hostedConnectorWiresFor,
56
55
  toolInputBoundRefusal,
57
56
  AGENT402_MCP_VERSION,
58
57
  clipToolDescription,
59
58
  } from "./output-schemas.js";
60
59
 
60
+ // A protocol error whose message starts "MCP error <code>: ", as SDK v1's
61
+ // McpError wrote it, so every error answer reads as it did before the move.
62
+ class McpError extends ProtocolError {
63
+ constructor(code, message, data) { super(code, `MCP error ${code}: ${message}`, data); }
64
+ }
65
+
61
66
  const DEFAULT_URL = "https://agent402.tools";
62
67
  const BASE = (process.env.AGENT402_URL || DEFAULT_URL).replace(/\/$/, "");
63
68
  // Catalog and seller requests (the 402 and the paid retry included) go through
@@ -157,24 +162,28 @@ const ASYNC_TIMEOUT_MS = Number(process.env.AGENT402_ASYNC_TIMEOUT_MS) > 0 ? Num
157
162
  const VERSION = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version;
158
163
 
159
164
  // Spend controls, enforced on the payment that is signed (see getPayFetch), so
160
- // a confused or runaway model cannot drain the wallet. The per-call cap is on
161
- // by default, at the dearest list price in the Agent402 catalog rounded up to
162
- // a whole dollar (mcp/test.js checks it still covers the catalog), and `off`
163
- // disables it; a malformed value reads as that default, never as off. The
164
- // session budget is opt-in: unset (or `off`) is no session cap, so a heavy user
165
- // is never stopped by a default. The per-call cap above still applies.
166
- const DEFAULT_MAX_PER_CALL_USD = 4;
165
+ // a confused or runaway model cannot drain the wallet it was handed. The
166
+ // per-call ceiling is on by default at $5, which covers every fixed price in
167
+ // the Agent402 catalog (mcp/test.js and scripts/test-package-cap-defaults.js
168
+ // check it still does); `0` or `off` turns it off. The session budget is
169
+ // opt-in: unset, empty or `off` is no session cap. A value that does not read
170
+ // as a USD amount (text, a negative number, for the per-call ceiling an empty
171
+ // string) keeps the default and is named on stderr, so a typo never removes
172
+ // the per-call ceiling. A call a cap refuses names the setting to raise.
173
+ const DEFAULT_MAX_PER_CALL_USD = 5;
167
174
  const DEFAULT_BUDGET_USD = Infinity;
168
- const capFromEnv = (name, def) => {
169
- const raw = String(process.env[name] ?? "").trim().toLowerCase();
170
- if (raw === "") return def;
175
+ const capFromEnv = (name, def, { zeroIsOff = false } = {}) => {
176
+ if (!Object.prototype.hasOwnProperty.call(process.env, name)) return def;
177
+ const original = String(process.env[name]);
178
+ const raw = original.trim().toLowerCase();
179
+ if (raw === "" && !zeroIsOff) return def;
171
180
  if (raw === "off") return Infinity;
172
- const n = Number(raw);
173
- if (Number.isFinite(n) && n >= 0) return n;
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}`})`);
181
+ const n = raw === "" ? NaN : Number(raw);
182
+ if (Number.isFinite(n) && n >= 0) return n === 0 && zeroIsOff ? Infinity : n;
183
+ console.error(`[agent402-mcp] ${name}=${original.length <= 16 ? JSON.stringify(original) : "(a long value, not shown)"} is not a USD amount${zeroIsOff ? ", 0" : ""} or "off"; keeping the default (${def === Infinity ? "no cap" : `$${def} per call`})`);
175
184
  return def;
176
185
  };
177
- const MAX_PER_CALL = capFromEnv("AGENT402_MAX_PER_CALL", DEFAULT_MAX_PER_CALL_USD);
186
+ const MAX_PER_CALL = capFromEnv("AGENT402_MAX_PER_CALL", DEFAULT_MAX_PER_CALL_USD, { zeroIsOff: true });
178
187
  const BUDGET = capFromEnv("AGENT402_BUDGET", DEFAULT_BUDGET_USD);
179
188
  let spentUsd = 0;
180
189
  // Signed payments that were sent without a confirmed answer (an error status,
@@ -347,21 +356,6 @@ function solanaSigner() {
347
356
  return solanaSignerPromise;
348
357
  }
349
358
 
350
- function solvePow(challenge) {
351
- const leadingZeroBits = (buf) => {
352
- let total = 0;
353
- for (const byte of buf) {
354
- if (byte === 0) { total += 8; continue; }
355
- total += Math.clz32(byte) - 24;
356
- break;
357
- }
358
- return total;
359
- };
360
- let nonce = 0;
361
- while (leadingZeroBits(createHash("sha256").update(`${challenge.challenge}:${nonce}`).digest()) < challenge.difficulty) nonce++;
362
- return nonce;
363
- }
364
-
365
359
  function walletRequiredText(tool) {
366
360
  return [
367
361
  `"${tool.slug}" costs ${tool.price}/call and requires a USDC wallet (it is not eligible for the proof-of-work tier).`,
@@ -448,8 +442,11 @@ function failureText(status, text) {
448
442
  /** A job's progress as MCP notifications/progress, when the caller asked for
449
443
  * progress (a progressToken on the tools/call). Progress only ever rises. */
450
444
  function progressNotifier(req, extra) {
451
- const token = req?.params?._meta?.progressToken;
452
- if (token === undefined || token === null || typeof extra?.sendNotification !== "function") return null;
445
+ const token = req?.params?._meta?.progressToken ?? extra?.mcpReq?._meta?.progressToken;
446
+ // SDK v2 hands handlers ctx.mcpReq.notify; v1 handed extra.sendNotification.
447
+ const send = typeof extra?.mcpReq?.notify === "function" ? (n) => extra.mcpReq.notify(n)
448
+ : typeof extra?.sendNotification === "function" ? (n) => extra.sendNotification(n) : null;
449
+ if (token === undefined || token === null || !send) return null;
453
450
  let last = -1;
454
451
  return (doc) => {
455
452
  const pct = Number.isFinite(doc?.progress) ? Math.round(doc.progress * 100) : 0;
@@ -459,7 +456,7 @@ function progressNotifier(req, extra) {
459
456
  last = value;
460
457
  const eta = Number.isFinite(doc?.etaSeconds) ? `, about ${doc.etaSeconds} s left` : "";
461
458
  const message = `${jobState(doc) || "running"}${doc?.stage ? `: ${doc.stage}` : ""}${doc?.steps ? ` (${doc.steps.done} of ${doc.steps.total} steps)` : ""}${doc?.progressEstimated ? " (estimated)" : ""}${eta}`;
462
- extra.sendNotification({ method: "notifications/progress", params: { progressToken: token, progress: value, total: 100, message } }).catch(() => {});
459
+ send({ method: "notifications/progress", params: { progressToken: token, progress: value, total: 100, message } }).catch(() => {});
463
460
  };
464
461
  }
465
462
 
@@ -506,10 +503,10 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
506
503
  const listUsd = parseFloat(String(tool.price).replace(/[^0-9.]/g, "")) || 0;
507
504
  const { usd: price } = await quotedUsd(url, paidInit, listUsd);
508
505
  if (price > MAX_PER_CALL) {
509
- return { content: [{ type: "text", text: `Refused: "${tool.slug}" is quoted $${price} for this request${price !== listUsd ? ` (list price ${tool.price})` : ""}, above the AGENT402_MAX_PER_CALL cap of $${MAX_PER_CALL}.` }], isError: true };
506
+ return { content: [{ type: "text", text: `Refused: "${tool.slug}" is quoted $${price} for this request${price !== listUsd ? ` (list price ${tool.price})` : ""}, above the AGENT402_MAX_PER_CALL cap of $${MAX_PER_CALL}. Raise AGENT402_MAX_PER_CALL, or set it to 0 or off, on this MCP server to allow it.` }], isError: true };
510
507
  }
511
508
  if (spentUsd + price > BUDGET) {
512
- return { content: [{ type: "text", text: `Refused: session budget exhausted ($${spentUsd.toFixed(4)} of $${BUDGET} spent; "${tool.slug}" is quoted $${price} for this request).` }], isError: true };
509
+ return { content: [{ type: "text", text: `Refused: session budget exhausted ($${spentUsd.toFixed(4)} of $${BUDGET} spent; "${tool.slug}" is quoted $${price} for this request). Raise AGENT402_BUDGET (or set it to off) on this MCP server to continue.` }], isError: true };
513
510
  }
514
511
  try {
515
512
  const first = await ownFetch(url, { ...paidInit, headers: { ...init.headers, ...asyncHeaders, Authorization: `Bearer ${CREDITS_KEY}` } });
@@ -536,7 +533,7 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
536
533
  const price = parseFloat(String(tool.price).replace(/[^0-9.]/g, "")) || 0;
537
534
  if (price > MAX_PER_CALL) {
538
535
  return {
539
- content: [{ type: "text", text: `Refused without paying: "${tool.slug}" lists at ${tool.price}, above the AGENT402_MAX_PER_CALL cap of $${MAX_PER_CALL}. Raise the cap on this MCP server to allow it.` }],
536
+ content: [{ type: "text", text: `Refused without paying: "${tool.slug}" lists at ${tool.price}, above the AGENT402_MAX_PER_CALL cap of $${MAX_PER_CALL}. Raise AGENT402_MAX_PER_CALL, or set it to 0 or off, on this MCP server to allow it.` }],
540
537
  isError: true,
541
538
  };
542
539
  }
@@ -544,7 +541,7 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
544
541
  const heldUsd = heldNow();
545
542
  if (spentUsd + heldUsd + inFlight + price > BUDGET) {
546
543
  return {
547
- 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.` }],
544
+ 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}). Raise AGENT402_BUDGET (or set it to off) on this MCP server, or restart it, to continue.` }],
548
545
  isError: true,
549
546
  };
550
547
  }
@@ -590,7 +587,11 @@ async function callEndpoint(tool, args = {}, { onProgress = null } = {}) {
590
587
  // No wallet: pay with compute up front, solving before the call skips the
591
588
  // 402 round-trip entirely (challenges are single-use and tool-scoped).
592
589
  const challenge = await getDiscoveryJson(`proof-of-work challenge for "${tool.slug}"`, `${BASE}/api/pow/challenge?slug=${encodeURIComponent(tool.slug)}`);
593
- const nonce = solvePow(challenge);
590
+ // Solved on a worker thread (./pow-solver.js), so this server keeps
591
+ // answering the client while it searches; a difficulty above 28 bits is
592
+ // refused rather than searched.
593
+ const nonce = await solvePowAsync(challenge);
594
+ if (typeof challenge.token !== "string" || !challenge.token) throw new Error(`the proof-of-work challenge for "${tool.slug}" carried no token`);
594
595
  res = await ownFetch(url, { ...init, headers: { ...init.headers, "X-Pow-Solution": `${challenge.token}:${nonce}` } });
595
596
  } else {
596
597
  return { content: [{ type: "text", text: walletRequiredText(tool) }], isError: true };
@@ -632,7 +633,7 @@ function signingRefusal(tool, d) {
632
633
  ? `Refused without paying: for "${tool.slug}", ${d.detail}, so the payment was not sent.`
633
634
  : d.reason === "validity"
634
635
  ? `Refused without paying: for "${tool.slug}", ${d.detail}, so nothing was signed.`
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.`;
636
+ : `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; raise the setting that refused it (AGENT402_MAX_PER_CALL also takes 0 or off) on this MCP server to allow it.`;
636
637
  return { content: [{ type: "text", text }], isError: true };
637
638
  }
638
639
 
@@ -669,6 +670,29 @@ function applyFrontDoorTerms(terms, q) {
669
670
  }
670
671
  }
671
672
 
673
+ /** catalog.search's limit: a whole number from 1 to MAX_SEARCH_RESULTS, the
674
+ * default for anything else (a string that reads as a number counts). */
675
+ const MAX_SEARCH_RESULTS = 25;
676
+ function searchLimit(raw) {
677
+ const n = Math.floor(Number(raw));
678
+ return Number.isFinite(n) && n >= 1 ? Math.min(n, MAX_SEARCH_RESULTS) : 10;
679
+ }
680
+
681
+ /** A tool's `params` as an object: a JSON string that encodes an object (a
682
+ * host that serializes nested arguments sends one) is parsed; anything else
683
+ * that is not an object is refused with what was expected. */
684
+ function paramsObject(raw, where) {
685
+ if (raw === undefined || raw === null || raw === "") return { ok: true, value: {} };
686
+ if (typeof raw === "object" && !Array.isArray(raw)) return { ok: true, value: raw };
687
+ if (typeof raw === "string") {
688
+ try {
689
+ const v = JSON.parse(raw);
690
+ if (v && typeof v === "object" && !Array.isArray(v)) return { ok: true, value: v };
691
+ } catch { /* falls through to the refusal */ }
692
+ }
693
+ return { ok: false, text: `${where} "params" must be an object of the tool's inputs, or a JSON string of one (got ${Array.isArray(raw) ? "an array" : typeof raw}).` };
694
+ }
695
+
672
696
  function searchTools(query, limit = 10) {
673
697
  const q = String(query || "");
674
698
  const terms = q.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
@@ -741,7 +765,8 @@ function rankWorkflows(query, k = 2) {
741
765
  // MCP wiring
742
766
  // Initialize instructions mirror src/mcp-flagship.js mcpInitializeInstructions
743
767
  // (stdio package cannot import src/ when published). Keep tool names listed-only.
744
- const INIT_INSTRUCTIONS = mcpInitializeInstructions(BASE);
768
+ // This server lists no demand.request, so its instructions do not name it.
769
+ const INIT_INSTRUCTIONS = mcpInitializeInstructions(BASE, { ...hostedConnectorWiresFor(BASE), demand: false });
745
770
 
746
771
  const server = new Server(
747
772
  {
@@ -758,7 +783,7 @@ const server = new Server(
758
783
  // MCP-aware client. The list is fetched once at boot in loadCatalog(); the
759
784
  // per-prompt rendering is delegated to the hosted service so the npm package
760
785
  // stays thin and prompt text stays canonical with the website at /skills.
761
- server.setRequestHandler(ListPromptsRequestSchema, redacted(async () => ({
786
+ server.setRequestHandler("prompts/list", redacted(async () => ({
762
787
  prompts: skillPacks.map((p) => ({
763
788
  name: p.slug,
764
789
  title: p.title,
@@ -770,7 +795,7 @@ server.setRequestHandler(ListPromptsRequestSchema, redacted(async () => ({
770
795
  })),
771
796
  })),
772
797
  })));
773
- server.setRequestHandler(GetPromptRequestSchema, redacted(async (req) => {
798
+ server.setRequestHandler("prompts/get", redacted(async (req) => {
774
799
  const { name, arguments: args = {} } = req.params;
775
800
  const pack = skillPacks.find((p) => p.slug === name);
776
801
  if (!pack) throw new Error(`Unknown prompt "${name}". List available with prompts/list.`);
@@ -816,16 +841,24 @@ async function ensureCatalog() {
816
841
  }
817
842
  const withCatalog = (handler) => async (req, extra) => { await ensureCatalog(); return handler(req, extra); };
818
843
 
819
- server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () => {
820
- // Read-only only for lookups that stay on this machine (describe, payment
821
- // info). Anything that reaches the network or can spend is NET: not read-only,
822
- // open-world. A host reads readOnlyHint to decide whether to ask first.
844
+ server.setRequestHandler("tools/list", redacted(withCatalog(async () => {
845
+ // The same hints as the hosted connector (src/mcp-http.js). A host may run
846
+ // a read-only tool without asking its user, so readOnlyHint is true only for
847
+ // a tool that never charges and never writes: the local catalog search,
848
+ // describe and payment info (closed-world), and the free lookups that read
849
+ // the service (catalog.find, sellers.list: open-world). Every tool that can
850
+ // charge is not read-only; catalog.call and router.execute can run a tool
851
+ // that writes, deletes or buys, so they are marked destructive, and
852
+ // memory.write replaces the value a key held.
823
853
  const SAFE = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
854
+ const OPEN = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
824
855
  const NET = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
856
+ const CALL_PAID = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true };
857
+ const OVERWRITE = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true };
825
858
  const tools = curated.map((t) => {
826
859
  // verb_noun exposed names (match hosted /mcp). CallTool accepts kebab + plain snake too.
827
860
  const name = FLAGSHIP_MCP_NAMES[t.slug] || t.slug.replace(/-/g, "_");
828
- const ann = NET;
861
+ const ann = t.slug === "memory-write" ? OVERWRITE : NET;
829
862
  return {
830
863
  name,
831
864
  title: t.slug,
@@ -839,14 +872,14 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
839
872
  {
840
873
  name: META_MCP_NAMES.search_tools,
841
874
  title: "Search the Agent402 tool catalog",
842
- annotations: { title: "Search the Agent402 tool catalog", ...NET },
875
+ annotations: { title: "Search the Agent402 tool catalog", ...SAFE },
843
876
  description:
844
877
  `Keyword search over the Agent402 catalog of 500+ tools (${catalog.size} loaded by this server). Returns matching tools and workflow templates; run one with catalog.call. Pure-CPU tools are free through proof-of-work; the others are paid per call in USDC when a wallet key is set.`,
845
878
  inputSchema: {
846
879
  type: "object",
847
880
  properties: {
848
881
  query: { type: "string", description: "What you need, e.g. \"search the web for x402\", \"answer a question with citations\", \"convert miles to km\"" },
849
- limit: { type: "number", description: "Max results (default 10)" },
882
+ limit: { type: "number", minimum: 1, maximum: MAX_SEARCH_RESULTS, description: `Max results (default 10, at most ${MAX_SEARCH_RESULTS})` },
850
883
  },
851
884
  required: ["query"],
852
885
  },
@@ -855,7 +888,7 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
855
888
  {
856
889
  name: META_MCP_NAMES.find_tool,
857
890
  title: "Resolve a task to the one best Agent402 tool",
858
- annotations: { title: "Resolve a task to the one best Agent402 tool", ...NET },
891
+ annotations: { title: "Resolve a task to the one best Agent402 tool", ...OPEN },
859
892
  description:
860
893
  "Resolve a plain-language task to the single best-matching Agent402 tool through the hosted /api/find resolver. Returns { task, matches } with the top pick first. Run the pick with catalog.call and the slug and params it lists. Use catalog.search to compare several candidates.",
861
894
  inputSchema: {
@@ -871,14 +904,14 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
871
904
  {
872
905
  name: META_MCP_NAMES.call_tool,
873
906
  title: "Run an Agent402 tool",
874
- annotations: { title: "Run an Agent402 tool", ...NET },
907
+ annotations: { title: "Run an Agent402 tool", ...CALL_PAID },
875
908
  description:
876
909
  "Call any Agent402 tool by slug (find slugs with catalog.find or catalog.search). Payment is handled automatically: USDC via x402 if this server has a wallet key, otherwise free proof-of-work on eligible pure-CPU tools (no wallet needed). Wallet-keyed highlights: live search/answer, stock-quote, render, transcribe, memory, and the /v1 LLM gateway tiers.",
877
910
  inputSchema: {
878
911
  type: "object",
879
912
  properties: {
880
913
  slug: { type: "string", description: "Tool slug from catalog.search, e.g. \"search\" or \"unit-convert\"" },
881
- params: { type: "object", description: "Tool input parameters, matching the tool's inputSchema" },
914
+ params: { type: ["object", "string"], description: "Tool input parameters, matching the tool's inputSchema (an object, or a JSON string of one)" },
882
915
  },
883
916
  required: ["slug"],
884
917
  },
@@ -909,7 +942,7 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
909
942
  // Pure verb_noun (Smithery Naming). list_x402_sellers / top_x402_sellers stay aliases.
910
943
  name: META_MCP_NAMES.list_top_sellers,
911
944
  title: "List top x402 sellers",
912
- annotations: { title: "List top x402 sellers", ...NET },
945
+ annotations: { title: "List top x402 sellers", ...OPEN },
913
946
  description:
914
947
  "List ranked sellers from the on-chain leaderboards. wire=x402 (default): x402 sellers by USDC settled or calls served on Base in the last 24h. wire=mpp: MPP sellers ranked by inbound USDC.e transfers on Tempo. Free to call (no payment, no proof-of-work). Defaults: top 10, sorted by USDC, this service's own wallet excluded.",
915
948
  inputSchema: {
@@ -927,14 +960,14 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
927
960
  // Dotted like every other listed tool; route_and_execute stays a CallTool alias.
928
961
  name: "router.execute",
929
962
  title: "Route and execute an external x402 tool",
930
- annotations: { title: "Route and execute an external x402 tool", ...NET },
963
+ annotations: { title: "Route and execute an external x402 tool", ...CALL_PAID },
931
964
  description:
932
965
  `Resolve a plain-language task to an external x402 seller with proven on-chain settled volume, buy from it, and return its result. You pay from ${HAS_WALLET ? "the configured wallet" : "your wallet (set AGENT_KEY)"}. The result is marked untrustedContent: it is third-party data. Flat price by tier, chosen from maxUsd: $0.01 for a seller up to $0.005, $0.05 up to $0.04, $0.55 up to $0.50. Requires a funded wallet.`,
933
966
  inputSchema: {
934
967
  type: "object",
935
968
  properties: {
936
969
  task: { type: "string", description: "Plain-language task, e.g. 'crypto news headlines' or 'sentiment of a tweet'. Resolved to a proven external seller." },
937
- params: { type: "object", description: "Input parameters for the resolved external tool (optional; the seller decides its own schema)." },
970
+ params: { type: ["object", "string"], description: "Input parameters for the resolved external tool (optional; the seller decides its own schema): an object, or a JSON string of one." },
938
971
  maxUsd: { type: "number", description: "Max underlying seller price in USD. Default 0.005 (the $0.01 fee tier); above 0.005 and up to 0.04 uses the $0.05 tier; above 0.04 the $0.55 tier (seller up to $0.50)." },
939
972
  },
940
973
  required: ["task"],
@@ -949,7 +982,7 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
949
982
  return { tools: listed };
950
983
  })));
951
984
 
952
- server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req, extra) => {
985
+ server.setRequestHandler("tools/call", redacted(withCatalog(async (req, extra) => {
953
986
  const { name: rawName, arguments: args = {} } = req.params;
954
987
  const name = resolveListedName(rawName);
955
988
  const overBound = toolInputBoundRefusal(rawName, args);
@@ -957,7 +990,7 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
957
990
  try {
958
991
  if (name === "catalog.search") {
959
992
  const q = String(args.query ?? "").trim();
960
- const results = searchTools(q, args.limit ?? 10);
993
+ const results = searchTools(q, searchLimit(args.limit));
961
994
  const workflows = rankWorkflows(q, 2);
962
995
  if (!results.length && !workflows.length) {
963
996
  // A caller that passed no query is told which argument to pass, not
@@ -1051,10 +1084,10 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
1051
1084
  claudeCodeHosted: `claude mcp add --transport http agent402 ${BASE}/mcp`,
1052
1085
  claudeCodeNpm: `claude mcp add agent402 -s user -- npx -y agent402-mcp@${AGENT402_MCP_VERSION}`,
1053
1086
  cursorHosted: { mcpServers: { agent402: { url: `${BASE}/mcp` } } },
1054
- npm: "npx -y agent402-mcp@0.13.31",
1087
+ npm: "npx -y agent402-mcp@0.14.0",
1055
1088
  maintainer: "Havok Holdings LLC",
1056
1089
  },
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.`,
1090
+ positioning: `Agent402 is a catalog of 500+ tools that AI agents find, pay for per request over x402 or MPP, and call with no account or API key. 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.`,
1058
1091
  ecosystem: "Call sellers.list to see which x402 sellers (any wallet, not just this host) are settling the most USDC (primarily on Base) in the last 24h, or sellers.list with wire=mpp for MPP sellers ranked by on-chain USDC.e transfers on Tempo - discovers the live economy beyond this catalog.",
1059
1092
  });
1060
1093
  }
@@ -1063,7 +1096,7 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
1063
1096
  service: BASE,
1064
1097
  connector: "stdio npm package (agent402-mcp)",
1065
1098
  maintainer: "Havok Holdings LLC",
1066
- positioning: `Agent402 is the applied layer of Agentic Finance: software agents that pay and get paid on their own, per request, over x402 or MPP (Machine Payments Protocol) - both answered on the same 402. ${BASE}/agentic-finance, ${BASE}/glossary.`,
1099
+ positioning: `Agent402 is a catalog of 500+ tools that AI agents find, pay for per request over x402 or MPP, and call with no account or API key. It is the applied layer of Agentic Finance: software agents that pay and get paid on their own, per request, over x402 or MPP (Machine Payments Protocol) - both answered on the same 402. ${BASE}/agentic-finance, ${BASE}/glossary.`,
1067
1100
  startHere: {
1068
1101
  firstJob: "Search the web and answer questions. Call web.search or web.answer directly, or catalog.find with your task.",
1069
1102
  mode: HAS_WALLET ? "usdc" : HAS_CREDITS ? "credits" : "proof-of-work",
@@ -1071,7 +1104,7 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
1071
1104
  install: {
1072
1105
  claudeCodeHosted: `claude mcp add --transport http agent402 ${BASE}/mcp`,
1073
1106
  claudeCodeNpm: `claude mcp add agent402 -s user -- npx -y agent402-mcp@${AGENT402_MCP_VERSION}`,
1074
- npm: "npx -y agent402-mcp@0.13.31",
1107
+ npm: "npx -y agent402-mcp@0.14.0",
1075
1108
  maintainer: "Havok Holdings LLC",
1076
1109
  },
1077
1110
  tools: catalog.size,
@@ -1186,7 +1219,9 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
1186
1219
  if (!tool) return { content: [{ type: "text", text: `External routing (${slug}) is not in the catalog from ${BASE} yet. It may be rolling out; retry shortly.` }], isError: true };
1187
1220
  // Body matches the route-execute input schema; include:"external" is what
1188
1221
  // pays an OUTSIDE seller (vs this host's catalog). Paid via callEndpoint.
1189
- return await callEndpoint(tool, { task, include: "external", maxUsd, ...(args.params && typeof args.params === "object" ? { params: args.params } : {}) }, { onProgress: progressNotifier(req, extra) });
1222
+ const routed = paramsObject(args.params, "router.execute");
1223
+ if (!routed.ok) return { content: [{ type: "text", text: routed.text }], isError: true };
1224
+ return await callEndpoint(tool, { task, include: "external", maxUsd, ...(Object.keys(routed.value).length ? { params: routed.value } : {}) }, { onProgress: progressNotifier(req, extra) });
1190
1225
  }
1191
1226
  // Curated tools are exposed verb_noun for tools/list consistency, but the
1192
1227
  // real slug is kebab, accept exposed name, plain snake, or raw slug.
@@ -1199,7 +1234,13 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
1199
1234
  if (!tool) {
1200
1235
  return { content: [{ type: "text", text: `Unknown tool slug "${wanted}". Use catalog.search to find the right slug.` }], isError: true };
1201
1236
  }
1202
- const out = await callEndpoint(tool, name === "catalog.call" ? (args.params ?? {}) : args, { onProgress: progressNotifier(req, extra) });
1237
+ let input = args;
1238
+ if (name === "catalog.call") {
1239
+ const p = paramsObject(args.params, "catalog.call");
1240
+ if (!p.ok) return { content: [{ type: "text", text: p.text }], isError: true };
1241
+ input = p.value;
1242
+ }
1243
+ const out = await callEndpoint(tool, input, { onProgress: progressNotifier(req, extra) });
1203
1244
  // call_tool: wrap structuredContent in {slug, result} to match META_OUTPUT_SCHEMAS["catalog.call"]
1204
1245
  // while keeping content text as the native tool JSON.
1205
1246
  if (name === "catalog.call" && !out.isError && out.structuredContent) {
@@ -1230,10 +1271,26 @@ const requested = (process.env.AGENT402_TOOLS || DEFAULT_CURATED.join(","))
1230
1271
  .split(",").map((s) => s.trim()).filter(Boolean);
1231
1272
  curated = requested.map((slug) => catalog.get(slug)).filter(Boolean);
1232
1273
  log(`catalog: ${catalog.size} tools from ${BASE}; ${curated.length} first-class, rest via catalog.search/catalog.call`);
1233
- log(
1234
- HAS_WALLET
1235
- ? `payment: USDC via x402 (${[AGENT_KEY && "EVM", SOLANA_AGENT_KEY && "Solana"].filter(Boolean).join(" + ")} wallet configured; max/call ${MAX_PER_CALL === Infinity ? "unlimited" : `$${MAX_PER_CALL}`}, budget ${BUDGET === Infinity ? "unlimited" : `$${BUDGET}`})`
1236
- : "payment: proof-of-work on eligible tools (no AGENT_KEY / SOLANA_AGENT_KEY)"
1237
- );
1274
+ // A key is reported configured only once it parses: a key that does not
1275
+ // parse is named (never printed) so the operator sees it before the first
1276
+ // paid call fails on it.
1277
+ {
1278
+ const parsed = [], broken = [];
1279
+ if (AGENT_KEY) {
1280
+ try { const { privateKeyToAccount } = await import("viem/accounts"); evmAccount(privateKeyToAccount); parsed.push("EVM"); } catch { broken.push("AGENT_KEY"); }
1281
+ }
1282
+ if (SOLANA_AGENT_KEY) {
1283
+ try { await solanaSigner(); parsed.push("Solana"); } catch { broken.push("SOLANA_AGENT_KEY"); }
1284
+ }
1285
+ const caps = `max/call ${MAX_PER_CALL === Infinity ? "unlimited" : `$${MAX_PER_CALL}`}, session budget ${BUDGET === Infinity ? "unlimited" : `$${BUDGET}`}`;
1286
+ if (broken.length) log(`payment: ${broken.join(" and ")} ${broken.length > 1 ? "are set but do" : "is set but does"} not parse as a key (the value is never printed); paid calls that need ${broken.length > 1 ? "them fail until they are" : "it fail until it is"} fixed`);
1287
+ log(parsed.length
1288
+ ? `payment: USDC via x402 (${parsed.join(" + ")} wallet configured; ${caps})`
1289
+ : HAS_WALLET
1290
+ ? "payment: no usable wallet key"
1291
+ : HAS_CREDITS
1292
+ ? `payment: credits key configured (${caps})`
1293
+ : "payment: proof-of-work on eligible tools (no AGENT_KEY / SOLANA_AGENT_KEY)");
1294
+ }
1238
1295
 
1239
1296
  await server.connect(new StdioServerTransport());
package/output-schemas.js CHANGED
@@ -119,7 +119,7 @@ export const FLAGSHIP_WRITERS = new Set(["memory-write", "decide-execute"]);
119
119
 
120
120
  /** initialize.serverInfo description (MCP Implementation.description). */
121
121
  export const MCP_SERVER_DESCRIPTION =
122
- "Agent402 - pay-per-call tools and models for AI agents: live web search and cited answers, news, browser render, market data, speech-to-text, wallet-keyed memory, plus 500+ long-tail tools via catalog.find. Settle in USDC via x402 or MPP (Machine Payments Protocol) on the same 402, or free via proof-of-work. The applied layer of Agentic Finance. Maintained by Havok Holdings LLC.";
122
+ "Agent402 is a catalog of 500+ tools that AI agents find, pay for per request over x402 or MPP, and call with no account or API key. Flagships: live web search and cited answers, news, browser render, market data, speech-to-text and wallet-keyed memory; the rest via catalog.find. Settle in USDC via x402 or MPP (Machine Payments Protocol) on the same 402, or free via proof-of-work. The applied layer of Agentic Finance. Maintained by Havok Holdings LLC.";
123
123
 
124
124
  /** initialize.serverInfo.websiteUrl */
125
125
  export const MCP_SERVER_WEBSITE = "https://agent402.tools";
@@ -421,6 +421,8 @@ export const FLAGSHIP_OUTPUT_SCHEMAS = {
421
421
  text: { type: "string" },
422
422
  language: { type: "string" },
423
423
  duration: { type: "number" },
424
+ trimmedToCapSeconds: { type: "number", description: "Present only when the file's length could not be confirmed: the audio was transcribed up to this many seconds (the tier's cap)" },
425
+ durationUnconfirmed: { type: "boolean", description: "Present (true) only with trimmedToCapSeconds: the file's full length was not confirmed" },
424
426
  },
425
427
  required: ["text"],
426
428
  },
@@ -447,7 +449,7 @@ export const FLAGSHIP_OUTPUT_SCHEMAS = {
447
449
  key: { type: "string" },
448
450
  bytes: { type: "integer" },
449
451
  updated: { type: "number" },
450
- expiresAt: { type: "number" },
452
+ expiresAt: { type: ["number", "null"], description: "Expiry in unix seconds; null when the key does not expire" },
451
453
  owner: { type: "string" },
452
454
  persistent: { type: "boolean" },
453
455
  deleted: { type: "boolean" },
@@ -492,7 +494,7 @@ export function mcpJsonResult(obj) {
492
494
  * Hosted URL is parameterized; npm / Claude Code / Cursor notes
493
495
  * match docs/ecosystem-listings.md + wiki/MCP-Connector.md.
494
496
  */
495
- export const AGENT402_MCP_VERSION = "0.13.31";
497
+ export const AGENT402_MCP_VERSION = "0.14.0";
496
498
 
497
499
  /** A listed MCP tool description, at most `max` characters. Hosts truncate or
498
500
  * skip long descriptions, so the listing keeps the first whole sentences; the
@@ -524,12 +526,12 @@ export function mcpInstallHints(baseUrl) {
524
526
  mcpServers: {
525
527
  agent402: {
526
528
  command: "npx",
527
- args: ["-y", "agent402-mcp@0.13.31"],
529
+ args: ["-y", "agent402-mcp@0.14.0"],
528
530
  env: { AGENT_KEY: "0xYOUR_PRIVATE_KEY" },
529
531
  },
530
532
  },
531
533
  },
532
- npm: "npx -y agent402-mcp@0.13.31",
534
+ npm: "npx -y agent402-mcp@0.14.0",
533
535
  maintainer: "Havok Holdings LLC",
534
536
  };
535
537
  }
@@ -539,19 +541,34 @@ export function mcpInstallHints(baseUrl) {
539
541
  * server.describe. Keep tool names listed-only (dotted Smithery form) (self-consistency) and lead
540
542
  * with search/answer as the front door.
541
543
  */
542
- export function mcpInitializeInstructions(baseUrl, { decide = false, mpp = false } = {}) {
544
+ // The wires the hosted connector at agent402.tools takes in the call (x402
545
+ // and MPP): this package describes that service, so its hosted line names
546
+ // both, as src/mcp-flagship.js renders it for a boot with both wires on.
547
+ export const HOSTED_CONNECTOR_WIRES = Object.freeze({ x402: true, mpp: true });
548
+ // The hosted service's origin. A package pointed at any other server
549
+ // (AGENT402_URL, a self-host) names no wire on its hosted line: that server's
550
+ // own wires are not known here.
551
+ export const HOSTED_SERVICE_URL = "https://agent402.tools";
552
+ /** The wires the hosted line names for `baseUrl`: both for the hosted
553
+ * service, none for any other server. */
554
+ export function hostedConnectorWiresFor(baseUrl) {
555
+ return String(baseUrl || "").replace(/\/+$/, "") === HOSTED_SERVICE_URL ? HOSTED_CONNECTOR_WIRES : {};
556
+ }
557
+
558
+ export function mcpInitializeInstructions(baseUrl, { decide = false, mpp = false, x402 = false, demand = true } = {}) {
543
559
  const install = mcpInstallHints(baseUrl);
544
560
  const hosted = install.hostedUrl;
545
561
  return [
546
- "Agent402 is the applied layer of Agentic Finance: a catalog of 500+ tools for AI agents: per-call tools and metered models, paid in USDC over x402 or MPP, or free through proof-of-work for the pure-CPU tools.",
562
+ "Agent402 is a catalog of 500+ tools that AI agents find, pay for per request over x402 or MPP, and call with no account or API key. Per-call tools and metered models, paid in USDC, or free through proof-of-work for the pure-CPU tools; the applied layer of Agentic Finance.",
547
563
  "Flagship tools: web.search (live web search), web.answer (answers with citations), web.news, browser.render, market.quote, audio.transcribe, memory.read, memory.write.",
548
564
  "Long tail: catalog.search lists tools by keyword, catalog.find returns the best match with its input schema and price, catalog.call runs a tool by slug.",
549
565
  // Only where the decide tools are listed: an instruction must never name a
550
566
  // tool the connector does not advertise.
551
567
  ...(decide ? ["Multi-step jobs: decide.plan returns a call-ready plan (tools, order, fallbacks, inputs); decide.execute runs it. The plan fee is credited toward the run."] : []),
552
- "Also: server.describe (connector details), payment.info (wallet and payment setup), demand.request (report a missing tool).",
568
+ // demand.request is named only where it is listed (the hosted connector).
569
+ `Also: server.describe (connector details), payment.info (wallet and payment setup)${demand ? ", demand.request (report a missing tool)" : ""}.`,
553
570
  `Install (npm package, pinned): ${install.claudeCodeNpm}`,
554
- `${mpp ? "Hosted connector (proof-of-work tools free; other tools payable over MPP from a wallet)" : "Hosted connector (proof-of-work tools free; others need a wallet on the npm package)"}: ${install.claudeCodeHosted}`,
571
+ `Hosted connector (proof-of-work tools free; ${x402 || mpp ? `other tools paid in the call over ${[x402 && "x402", mpp && "MPP"].filter(Boolean).join(" or ")} from a wallet` : "others need a wallet on the npm package"}): ${install.claudeCodeHosted}`,
555
572
  `Cursor mcp.json: { "mcpServers": { "agent402": { "url": "${hosted}" } } }`,
556
573
  `Docs: ${baseUrl}/llms.txt · status ${baseUrl}/status`,
557
574
  ].join("\n");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent402-mcp",
3
- "version": "0.13.31",
3
+ "version": "0.14.0",
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",
@@ -9,19 +9,21 @@
9
9
  "url": "git+https://github.com/MikeyPetrillo/Agent402.git",
10
10
  "directory": "mcp"
11
11
  },
12
- "description": "Agent402 MCP server: 500+ pay-per-call tools + skill packs for AI agents over x402 (USDC or USDG on 14 chains) or MPP on the same 402, or free via proof-of-work - the applied layer of Agentic Finance. Catalog: browser, web search + cited answers, PDFs, OCR, images, LLM inference, image generation, code execution, STT, embeddings, live financial/crypto/macro data, SEC EDGAR filings, deterministic stats & forecasting, compression, payments. Open source, self-hostable.",
12
+ "description": "Agent402 MCP server. Agent402 is a catalog of 500+ tools that AI agents find, pay for per request over x402 or MPP, and call with no account or API key. The applied layer of Agentic Finance: skill packs too, USDC or USDG on 14 chains, or free via proof-of-work. Catalog: browser, web search + cited answers, PDFs, OCR, images, LLM inference, image generation, code execution, STT, embeddings, live financial/crypto/macro data, SEC EDGAR filings, deterministic stats & forecasting, compression, payments. Open source, self-hostable.",
13
13
  "type": "module",
14
14
  "bin": {
15
15
  "agent402-mcp": "index.js"
16
16
  },
17
17
  "files": [
18
18
  "index.js",
19
+ "index.d.ts",
19
20
  "async-job.js",
20
21
  "known-assets.js",
21
22
  "networks.js",
22
23
  "discovery.js",
23
24
  "output-schemas.js",
24
- "README.md"
25
+ "README.md",
26
+ "pow-solver.js"
25
27
  ],
26
28
  "engines": {
27
29
  "node": ">=20"
@@ -73,7 +75,7 @@
73
75
  ],
74
76
  "license": "MIT",
75
77
  "dependencies": {
76
- "@modelcontextprotocol/sdk": "1.32.2",
78
+ "@modelcontextprotocol/server": "2.4.0",
77
79
  "@solana/kit": "8.4.0",
78
80
  "@x402/core": "2.30.0",
79
81
  "@x402/evm": "2.30.0",
@@ -84,17 +86,24 @@
84
86
  "overrides": {
85
87
  "qs": "6.16.1",
86
88
  "ws": "^8.21.0",
87
- "hono": "4.13.13",
89
+ "hono": "4.13.16",
88
90
  "fast-uri": "3.1.9",
89
91
  "body-parser": "2.4.0",
90
- "@hono/node-server": "2.1.3",
92
+ "@hono/node-server": "2.1.6",
91
93
  "ip-address": "10.7.4",
92
94
  "@solana-program/token": "0.17.0",
93
95
  "@solana-program/compute-budget": "0.19.0",
94
96
  "@solana-program/token-2022": "0.19.0",
95
97
  "@solana/program-client-core": "8.4.0",
96
- "@modelcontextprotocol/sdk": {
98
+ "@modelcontextprotocol/server": {
99
+ "zod": "4.6.7"
100
+ },
101
+ "@modelcontextprotocol/client": {
97
102
  "zod": "4.6.7"
98
103
  }
104
+ },
105
+ "types": "index.d.ts",
106
+ "devDependencies": {
107
+ "@modelcontextprotocol/client": "2.4.0"
99
108
  }
100
109
  }
package/pow-solver.js ADDED
@@ -0,0 +1,114 @@
1
+ // Proof-of-work solving for a seller's challenge: find a nonce such that
2
+ // sha256("<challenge>:<nonce>") has at least `difficulty` leading zero bits.
3
+ //
4
+ // Two bounds keep a hostile or broken server from hanging the caller:
5
+ // - the difficulty is refused above MAX_POW_DIFFICULTY (28 bits, the most an
6
+ // Agent402 server can be configured to ask for: src/pow.js clamps
7
+ // POW_DIFFICULTY to 8..28), so a challenge asking for 60 bits is an error,
8
+ // not a search that never ends;
9
+ // - the search stops after MAX_POW_TRIES_FACTOR times the expected number of
10
+ // hashes (2^difficulty). The search is memoryless, so running past 64 times
11
+ // the expectation has a chance of about e^-64: a stop there is a broken
12
+ // challenge, never bad luck.
13
+ // solvePowAsync runs the search on a worker thread, so the event loop of the
14
+ // process that asked keeps serving while it runs. Where worker threads are not
15
+ // available it searches in slices on the main thread, yielding between them.
16
+ //
17
+ // This file is shipped byte-identical in agent402-client and agent402-mcp
18
+ // (scripts/test-known-assets.js checks the copies).
19
+ import { createHash } from "node:crypto";
20
+
21
+ export const MAX_POW_DIFFICULTY = 28;
22
+ export const MAX_POW_TRIES_FACTOR = 64;
23
+ const MAX_CHALLENGE_CHARS = 512;
24
+ const MAX_TOKEN_CHARS = 4096;
25
+ const SLICE = 4096;
26
+
27
+ export function leadingZeroBits(buf) {
28
+ let n = 0;
29
+ for (const b of buf) { if (b === 0) { n += 8; continue; } n += Math.clz32(b) - 24; break; }
30
+ return n;
31
+ }
32
+
33
+ /** The checked challenge ({ challenge, difficulty, maxTries }), or a thrown
34
+ * Error naming what is wrong with it. `token` is checked only when `needToken`. */
35
+ export function checkPowChallenge(pow, { needToken = false } = {}) {
36
+ if (!pow || typeof pow !== "object") throw new Error("proof-of-work challenge is not an object");
37
+ const challenge = pow.challenge;
38
+ if (typeof challenge !== "string" || challenge.length === 0 || challenge.length > MAX_CHALLENGE_CHARS) {
39
+ throw new Error(`proof-of-work challenge must be a string of 1 to ${MAX_CHALLENGE_CHARS} characters`);
40
+ }
41
+ const difficulty = pow.difficulty;
42
+ if (typeof difficulty !== "number" || !Number.isInteger(difficulty) || difficulty < 0 || difficulty > MAX_POW_DIFFICULTY) {
43
+ throw new Error(`proof-of-work difficulty ${JSON.stringify(pow.difficulty)} is refused: this solver accepts a whole number of bits from 0 to ${MAX_POW_DIFFICULTY}`);
44
+ }
45
+ if (needToken && (typeof pow.token !== "string" || pow.token.length === 0 || pow.token.length > MAX_TOKEN_CHARS)) {
46
+ throw new Error(`proof-of-work token must be a string of 1 to ${MAX_TOKEN_CHARS} characters`);
47
+ }
48
+ return { challenge, difficulty, maxTries: MAX_POW_TRIES_FACTOR * 2 ** difficulty };
49
+ }
50
+
51
+ const exhausted = (difficulty, maxTries) => new Error(`proof-of-work search stopped after ${maxTries} hashes without a ${difficulty}-bit solution (${MAX_POW_TRIES_FACTOR} times the expected count): the challenge is not solvable as stated`);
52
+
53
+ /** Solve on the calling thread. Returns the nonce. Blocks the event loop for
54
+ * the whole search; solvePowAsync does not. */
55
+ export function solvePowSync(pow) {
56
+ const { challenge, difficulty, maxTries } = checkPowChallenge(pow);
57
+ for (let n = 0; n < maxTries; n++) {
58
+ if (leadingZeroBits(createHash("sha256").update(`${challenge}:${n}`).digest()) >= difficulty) return n;
59
+ }
60
+ throw exhausted(difficulty, maxTries);
61
+ }
62
+
63
+ // The worker's own source: CommonJS, evaluated by worker_threads, so no file
64
+ // path has to resolve inside a bundle.
65
+ const WORKER_SOURCE = `
66
+ const { parentPort, workerData } = require("node:worker_threads");
67
+ const { createHash } = require("node:crypto");
68
+ const { challenge, difficulty, maxTries } = workerData;
69
+ const lzb = (buf) => { let n = 0; for (const b of buf) { if (b === 0) { n += 8; continue; } n += Math.clz32(b) - 24; break; } return n; };
70
+ let found = -1;
71
+ for (let n = 0; n < maxTries; n++) {
72
+ if (lzb(createHash("sha256").update(challenge + ":" + n).digest()) >= difficulty) { found = n; break; }
73
+ }
74
+ parentPort.postMessage(found);
75
+ `;
76
+
77
+ let workerCtor; // undefined = not looked up yet, null = unavailable
78
+ async function loadWorker() {
79
+ if (workerCtor !== undefined) return workerCtor;
80
+ try { workerCtor = (await import("node:worker_threads")).Worker || null; } catch { workerCtor = null; }
81
+ return workerCtor;
82
+ }
83
+
84
+ async function solveInSlices({ challenge, difficulty, maxTries }) {
85
+ for (let n = 0; n < maxTries;) {
86
+ const end = Math.min(n + SLICE, maxTries);
87
+ for (; n < end; n++) {
88
+ if (leadingZeroBits(createHash("sha256").update(`${challenge}:${n}`).digest()) >= difficulty) return n;
89
+ }
90
+ await new Promise((resolve) => setImmediate(resolve));
91
+ }
92
+ throw exhausted(difficulty, maxTries);
93
+ }
94
+
95
+ /** Solve off the event loop. Resolves to the nonce. `useWorker: false` forces
96
+ * the sliced main-thread search (tests use it). */
97
+ export async function solvePowAsync(pow, { useWorker = true } = {}) {
98
+ const checked = checkPowChallenge(pow);
99
+ const Worker = useWorker ? await loadWorker() : null;
100
+ if (!Worker) return solveInSlices(checked);
101
+ return new Promise((resolve, reject) => {
102
+ let worker;
103
+ try { worker = new Worker(WORKER_SOURCE, { eval: true, workerData: checked }); } catch { solveInSlices(checked).then(resolve, reject); return; }
104
+ let settled = false;
105
+ worker.once("message", (n) => {
106
+ settled = true;
107
+ worker.terminate().catch(() => {});
108
+ if (Number.isInteger(n) && n >= 0) resolve(n);
109
+ else reject(exhausted(checked.difficulty, checked.maxTries));
110
+ });
111
+ worker.once("error", (e) => { if (!settled) { settled = true; reject(e); } });
112
+ worker.once("exit", (code) => { if (!settled) { settled = true; reject(new Error(`proof-of-work worker exited (code ${code}) before answering`)); } });
113
+ });
114
+ }