agent402-mcp 0.13.32 → 0.14.1
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 +22 -14
- package/index.d.ts +126 -0
- package/index.js +147 -80
- package/output-schemas.js +26 -10
- package/package.json +14 -5
- package/pow-solver.js +114 -0
package/README.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# agent402-mcp
|
|
2
2
|
|
|
3
|
-
MCP server for [Agent402](https://agent402.tools), the applied layer of Agentic Finance. Agent402 is
|
|
3
|
+
MCP server for [Agent402](https://agent402.tools), the applied layer of Agentic Finance. Agent402 is the payment and trust layer for agent commerce: agents find, pay for and verify every paid call to Agent402, across x402 and MPP, with a signed receipt for each one. 500+ ready tools on the same rails. 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
|
+
|
|
5
|
+

|
|
4
6
|
|
|
5
7
|
## Quick start
|
|
6
8
|
|
|
@@ -9,7 +11,7 @@ Pick one setup. Both run locally through `npx`.
|
|
|
9
11
|
**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
12
|
|
|
11
13
|
```
|
|
12
|
-
claude mcp add agent402 -s user -- npx -y agent402-mcp@0.
|
|
14
|
+
claude mcp add agent402 -s user -- npx -y agent402-mcp@0.14.1
|
|
13
15
|
```
|
|
14
16
|
|
|
15
17
|
**2. Paid, with a wallet.** Paid tools are settled in USDC on each call.
|
|
@@ -19,7 +21,7 @@ claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.32
|
|
|
19
21
|
"mcpServers": {
|
|
20
22
|
"agent402": {
|
|
21
23
|
"command": "npx",
|
|
22
|
-
"args": ["-y", "agent402-mcp@0.
|
|
24
|
+
"args": ["-y", "agent402-mcp@0.14.1"],
|
|
23
25
|
"env": { "AGENT_KEY": "0xYOUR_PRIVATE_KEY" }
|
|
24
26
|
}
|
|
25
27
|
}
|
|
@@ -28,9 +30,9 @@ claude mcp add agent402 -s user -- npx -y agent402-mcp@0.13.32
|
|
|
28
30
|
|
|
29
31
|
> Use a new wallet holding only a few dollars of USDC. Never use your main wallet.
|
|
30
32
|
|
|
31
|
-
Use `SOLANA_AGENT_KEY` instead for USDC on Solana. Each call is capped at $
|
|
33
|
+
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
34
|
|
|
33
|
-
Claude Code with a wallet: `claude mcp add agent402 -s user -e AGENT_KEY=0xYOUR_PRIVATE_KEY -- npx -y agent402-mcp@0.
|
|
35
|
+
Claude Code with a wallet: `claude mcp add agent402 -s user -e AGENT_KEY=0xYOUR_PRIVATE_KEY -- npx -y agent402-mcp@0.14.1`
|
|
34
36
|
(use a new wallet holding only a few dollars of USDC; never your main wallet).
|
|
35
37
|
|
|
36
38
|
Advanced setup (chains, MPP, error codes, the hosted connector) is in [Advanced](#advanced).
|
|
@@ -46,8 +48,8 @@ Every variable the server reads (all optional):
|
|
|
46
48
|
| `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
49
|
| `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
50
|
| `AGENT402_TOOLS` | curated set | Comma-separated slugs to expose as first-class tools. |
|
|
49
|
-
| `AGENT402_MAX_PER_CALL` | `
|
|
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. |
|
|
51
|
+
| `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. |
|
|
52
|
+
| `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
53
|
| `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
54
|
| `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
55
|
| `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 +63,17 @@ per-call cap or what is left of the budget, so the 402 the wallet signs is held
|
|
|
61
63
|
to the caps, and a wallet call sends no unpaid preflight first. Each option is priced from the
|
|
62
64
|
known decimals of its asset (USDC on each rail, USDG on Robinhood Chain), never
|
|
63
65
|
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`
|
|
65
|
-
$
|
|
66
|
+
signed. A value that is not a USD amount, `0` or `off` (text, a negative number, an
|
|
67
|
+
empty string) keeps the default, the $5 per-call cap and no session budget, and the
|
|
68
|
+
server names the variable on stderr. Set `AGENT402_BUDGET` to cap the session total.
|
|
66
69
|
`payment.info` reports the caps, what's been spent, and what remains. With no wallet key and no credits key,
|
|
67
70
|
the server runs in proof-of-work mode (pure-CPU tools stay free). Use dedicated
|
|
68
71
|
low-value wallets for `AGENT_KEY` / `SOLANA_AGENT_KEY`, funded only with what
|
|
69
72
|
you intend to spend. Most tools cost $0.001 to $0.02. The routing tiers top out
|
|
70
|
-
at $3.30 (`route-execute-pro`); multi-tool skill packs run $0.
|
|
73
|
+
at $3.30 (`route-execute-pro`); multi-tool skill packs run $0.001 to $0.093; and the
|
|
71
74
|
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 $
|
|
73
|
-
tighter ceiling.
|
|
75
|
+
so the default per-call cap of $5 covers every tool; set `AGENT402_MAX_PER_CALL` lower for a
|
|
76
|
+
tighter ceiling, or `off` for none.
|
|
74
77
|
|
|
75
78
|
**Held payments.** `payment.info` reports `heldThisSessionUsd`: money a wallet
|
|
76
79
|
call sent a signed payment for without a confirmed answer (an error status, a
|
|
@@ -102,12 +105,17 @@ its variable name, not its value.
|
|
|
102
105
|
## How it works
|
|
103
106
|
|
|
104
107
|
- On startup the server reads the live catalog from `https://agent402.tools/api/pricing` + `/openapi.json`.
|
|
105
|
-
- **Flagship tools** are exposed as first-class MCP tools under dotted names - `web.search`, `web.answer`, `web.news`, `browser.render`, `
|
|
108
|
+
- **Flagship tools** are exposed as first-class MCP tools under dotted names - `web.search`, `web.answer`, `web.news`, `browser.render`, `audio.transcribe`, `memory.read`, `memory.write` - search/answer is the front door. Override the set with `AGENT402_TOOLS` (slugs; a non-flagship slug is listed as its snake_case name).
|
|
106
109
|
- **Decide** (`decide.plan`, `decide.execute`, `decide.feedback`): describe a job and get a call-ready plan over the catalog and outside x402 sellers (tools in order, fallbacks, validated params, chained steps), then run it yourself or through Agent402. Listed when the server offers Decide; see https://agent402.tools/decide.
|
|
107
110
|
- 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
111
|
- 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
112
|
- 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`.
|
|
113
|
+
- **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.
|
|
114
|
+
- 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).
|
|
115
|
+
- `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).
|
|
116
|
+
- 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`.
|
|
117
|
+
- At start, a wallet key that does not parse is named in the log (never printed) instead of being reported as a configured wallet.
|
|
118
|
+
- 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
119
|
- `payment.info` tells the model which mode it's in and what a wallet or a credits key would unlock.
|
|
112
120
|
- `server.describe` returns orientation (flagship-first tools, install one-liners, free vs paid, discovery URLs). Call it first.
|
|
113
121
|
- `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/index.d.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
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 can list in tools/list; a flagship is listed only when
|
|
33
|
+
* the server's catalog serves its tool (market.quote, decide.plan and
|
|
34
|
+
* decide.execute are absent on a server without them). */
|
|
35
|
+
export type Agent402McpToolName =
|
|
36
|
+
| "catalog.search" | "catalog.find" | "catalog.call"
|
|
37
|
+
| "payment.info" | "server.describe" | "sellers.list" | "router.execute"
|
|
38
|
+
| "web.search" | "web.answer" | "web.news" | "browser.render"
|
|
39
|
+
| "audio.transcribe" | "memory.read" | "memory.write" | "decide.plan" | "decide.execute"
|
|
40
|
+
| "market.quote";
|
|
41
|
+
|
|
42
|
+
/** catalog.search arguments. `limit` is clamped to 1..25 (default 10). */
|
|
43
|
+
export interface CatalogSearchArgs { query: string; limit?: number }
|
|
44
|
+
export interface CatalogSearchHit {
|
|
45
|
+
slug: string;
|
|
46
|
+
method: string;
|
|
47
|
+
path: string;
|
|
48
|
+
price: string;
|
|
49
|
+
payment: string;
|
|
50
|
+
description: string;
|
|
51
|
+
inputSchema: Record<string, unknown>;
|
|
52
|
+
}
|
|
53
|
+
export interface CatalogSearchResult {
|
|
54
|
+
results: CatalogSearchHit[];
|
|
55
|
+
workflows?: Array<{ slug: string; title?: string; tagline?: string; toolCount: number; promptName: string; score: number }>;
|
|
56
|
+
workflowsUsage?: string;
|
|
57
|
+
usage?: string;
|
|
58
|
+
message?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** catalog.find arguments. `limit` is clamped to 1..25 (default 5). */
|
|
62
|
+
export interface CatalogFindArgs { task: string; limit?: number }
|
|
63
|
+
export interface CatalogFindMatch {
|
|
64
|
+
slug: string;
|
|
65
|
+
name?: string;
|
|
66
|
+
price?: string;
|
|
67
|
+
description?: string;
|
|
68
|
+
example?: unknown;
|
|
69
|
+
required?: string[];
|
|
70
|
+
inputSchema?: Record<string, unknown>;
|
|
71
|
+
callWith: { name: "catalog.call"; arguments: { slug: string; params: Record<string, unknown> } };
|
|
72
|
+
}
|
|
73
|
+
export interface CatalogFindResult {
|
|
74
|
+
task: string;
|
|
75
|
+
matches: CatalogFindMatch[];
|
|
76
|
+
results: CatalogFindMatch[];
|
|
77
|
+
workflows?: unknown[];
|
|
78
|
+
usage: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** catalog.call arguments: `params` is an object, or a JSON string of one. */
|
|
82
|
+
export interface CatalogCallArgs { slug: string; params?: Record<string, unknown> | string }
|
|
83
|
+
export interface CatalogCallResult<T = unknown> { slug: string; result: T }
|
|
84
|
+
|
|
85
|
+
/** router.execute arguments. */
|
|
86
|
+
export interface RouterExecuteArgs { task: string; params?: Record<string, unknown> | string; maxUsd?: number }
|
|
87
|
+
|
|
88
|
+
export interface SpendControls {
|
|
89
|
+
maxPerCallUsd: number | "unlimited";
|
|
90
|
+
sessionBudgetUsd: number | "unlimited";
|
|
91
|
+
spentThisSessionUsd: number;
|
|
92
|
+
heldThisSessionUsd: number;
|
|
93
|
+
remainingUsd: number | "unlimited";
|
|
94
|
+
}
|
|
95
|
+
export interface PaymentInfoResult {
|
|
96
|
+
service: string;
|
|
97
|
+
mode: "usdc" | "credits" | "proof-of-work";
|
|
98
|
+
wallet: string | null;
|
|
99
|
+
solanaWallet: string | null;
|
|
100
|
+
network: string;
|
|
101
|
+
networks?: unknown;
|
|
102
|
+
tools: number;
|
|
103
|
+
payableWithCompute: number;
|
|
104
|
+
walletOnly: number;
|
|
105
|
+
workflows: number;
|
|
106
|
+
credits: Record<string, unknown>;
|
|
107
|
+
spendControls: SpendControls | string;
|
|
108
|
+
note: string;
|
|
109
|
+
install: Record<string, unknown>;
|
|
110
|
+
positioning: string;
|
|
111
|
+
ecosystem: string;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface SellersListArgs { limit?: number; sort?: "usd" | "calls"; include?: "external" | "all"; wire?: "x402" | "mpp" }
|
|
115
|
+
export interface SellersListResult {
|
|
116
|
+
window: string | null;
|
|
117
|
+
asOf: string | null;
|
|
118
|
+
sort: string;
|
|
119
|
+
include: string;
|
|
120
|
+
totalSellers: number;
|
|
121
|
+
results: Array<Record<string, unknown> & { untrustedContent?: true }>;
|
|
122
|
+
containsUntrustedContent?: true;
|
|
123
|
+
note?: string;
|
|
124
|
+
source: string;
|
|
125
|
+
wire?: "mpp";
|
|
126
|
+
}
|
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
|
|
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 {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
|
161
|
-
//
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
//
|
|
165
|
-
//
|
|
166
|
-
|
|
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
|
-
|
|
170
|
-
|
|
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}=${
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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}).
|
|
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
|
-
|
|
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,12 @@ 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
|
-
|
|
768
|
+
// This server lists no demand.request, so its instructions do not name it;
|
|
769
|
+
// market.quote is named only while it is listed (the catalog lists
|
|
770
|
+
// stock-quote and it is first-class here), so the text is rebuilt after each
|
|
771
|
+
// catalog read (syncInstructions) and before the first initialize.
|
|
772
|
+
const instructionsFor = (stock) => mcpInitializeInstructions(BASE, { ...hostedConnectorWiresFor(BASE), demand: false, stock });
|
|
773
|
+
const INIT_INSTRUCTIONS = instructionsFor(false);
|
|
745
774
|
|
|
746
775
|
const server = new Server(
|
|
747
776
|
{
|
|
@@ -753,12 +782,16 @@ const server = new Server(
|
|
|
753
782
|
},
|
|
754
783
|
{ capabilities: { tools: {}, prompts: {} }, instructions: INIT_INSTRUCTIONS },
|
|
755
784
|
);
|
|
785
|
+
/** Point the initialize instructions at what tools/list lists now. */
|
|
786
|
+
function syncInstructions() {
|
|
787
|
+
server._instructions = instructionsFor(curated.some((t) => t.slug === "stock-quote"));
|
|
788
|
+
}
|
|
756
789
|
|
|
757
790
|
// Skill packs are exposed as MCP prompts, discoverable in slash menus on any
|
|
758
791
|
// MCP-aware client. The list is fetched once at boot in loadCatalog(); the
|
|
759
792
|
// per-prompt rendering is delegated to the hosted service so the npm package
|
|
760
793
|
// stays thin and prompt text stays canonical with the website at /skills.
|
|
761
|
-
server.setRequestHandler(
|
|
794
|
+
server.setRequestHandler("prompts/list", redacted(async () => ({
|
|
762
795
|
prompts: skillPacks.map((p) => ({
|
|
763
796
|
name: p.slug,
|
|
764
797
|
title: p.title,
|
|
@@ -770,7 +803,7 @@ server.setRequestHandler(ListPromptsRequestSchema, redacted(async () => ({
|
|
|
770
803
|
})),
|
|
771
804
|
})),
|
|
772
805
|
})));
|
|
773
|
-
server.setRequestHandler(
|
|
806
|
+
server.setRequestHandler("prompts/get", redacted(async (req) => {
|
|
774
807
|
const { name, arguments: args = {} } = req.params;
|
|
775
808
|
const pack = skillPacks.find((p) => p.slug === name);
|
|
776
809
|
if (!pack) throw new Error(`Unknown prompt "${name}". List available with prompts/list.`);
|
|
@@ -809,6 +842,7 @@ async function ensureCatalog() {
|
|
|
809
842
|
try {
|
|
810
843
|
pricingInfo = await loadCatalog();
|
|
811
844
|
curated = requested.map((slug) => catalog.get(slug)).filter(Boolean);
|
|
845
|
+
syncInstructions();
|
|
812
846
|
log(`catalog: ${catalog.size} tools from ${BASE} on a later read; ${curated.length} first-class`);
|
|
813
847
|
} catch (err) {
|
|
814
848
|
log(`Could not load the catalog from ${BASE}: ${err.message}: next read in ${CATALOG_RETRY_MS / 1000}s`);
|
|
@@ -816,16 +850,24 @@ async function ensureCatalog() {
|
|
|
816
850
|
}
|
|
817
851
|
const withCatalog = (handler) => async (req, extra) => { await ensureCatalog(); return handler(req, extra); };
|
|
818
852
|
|
|
819
|
-
server.setRequestHandler(
|
|
820
|
-
//
|
|
821
|
-
//
|
|
822
|
-
//
|
|
853
|
+
server.setRequestHandler("tools/list", redacted(withCatalog(async () => {
|
|
854
|
+
// The same hints as the hosted connector (src/mcp-http.js). A host may run
|
|
855
|
+
// a read-only tool without asking its user, so readOnlyHint is true only for
|
|
856
|
+
// a tool that never charges and never writes: the local catalog search,
|
|
857
|
+
// describe and payment info (closed-world), and the free lookups that read
|
|
858
|
+
// the service (catalog.find, sellers.list: open-world). Every tool that can
|
|
859
|
+
// charge is not read-only; catalog.call and router.execute can run a tool
|
|
860
|
+
// that writes, deletes or buys, so they are marked destructive, and
|
|
861
|
+
// memory.write replaces the value a key held.
|
|
823
862
|
const SAFE = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
863
|
+
const OPEN = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
|
|
824
864
|
const NET = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
|
|
865
|
+
const CALL_PAID = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true };
|
|
866
|
+
const OVERWRITE = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true };
|
|
825
867
|
const tools = curated.map((t) => {
|
|
826
868
|
// verb_noun exposed names (match hosted /mcp). CallTool accepts kebab + plain snake too.
|
|
827
869
|
const name = FLAGSHIP_MCP_NAMES[t.slug] || t.slug.replace(/-/g, "_");
|
|
828
|
-
const ann = NET;
|
|
870
|
+
const ann = t.slug === "memory-write" ? OVERWRITE : NET;
|
|
829
871
|
return {
|
|
830
872
|
name,
|
|
831
873
|
title: t.slug,
|
|
@@ -839,14 +881,14 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
|
|
|
839
881
|
{
|
|
840
882
|
name: META_MCP_NAMES.search_tools,
|
|
841
883
|
title: "Search the Agent402 tool catalog",
|
|
842
|
-
annotations: { title: "Search the Agent402 tool catalog", ...
|
|
884
|
+
annotations: { title: "Search the Agent402 tool catalog", ...SAFE },
|
|
843
885
|
description:
|
|
844
886
|
`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
887
|
inputSchema: {
|
|
846
888
|
type: "object",
|
|
847
889
|
properties: {
|
|
848
890
|
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:
|
|
891
|
+
limit: { type: "number", minimum: 1, maximum: MAX_SEARCH_RESULTS, description: `Max results (default 10, at most ${MAX_SEARCH_RESULTS})` },
|
|
850
892
|
},
|
|
851
893
|
required: ["query"],
|
|
852
894
|
},
|
|
@@ -855,7 +897,7 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
|
|
|
855
897
|
{
|
|
856
898
|
name: META_MCP_NAMES.find_tool,
|
|
857
899
|
title: "Resolve a task to the one best Agent402 tool",
|
|
858
|
-
annotations: { title: "Resolve a task to the one best Agent402 tool", ...
|
|
900
|
+
annotations: { title: "Resolve a task to the one best Agent402 tool", ...OPEN },
|
|
859
901
|
description:
|
|
860
902
|
"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
903
|
inputSchema: {
|
|
@@ -871,14 +913,14 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
|
|
|
871
913
|
{
|
|
872
914
|
name: META_MCP_NAMES.call_tool,
|
|
873
915
|
title: "Run an Agent402 tool",
|
|
874
|
-
annotations: { title: "Run an Agent402 tool", ...
|
|
916
|
+
annotations: { title: "Run an Agent402 tool", ...CALL_PAID },
|
|
875
917
|
description:
|
|
876
|
-
"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,
|
|
918
|
+
"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, render, transcribe, memory, and the /v1 LLM gateway tiers.",
|
|
877
919
|
inputSchema: {
|
|
878
920
|
type: "object",
|
|
879
921
|
properties: {
|
|
880
922
|
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" },
|
|
923
|
+
params: { type: ["object", "string"], description: "Tool input parameters, matching the tool's inputSchema (an object, or a JSON string of one)" },
|
|
882
924
|
},
|
|
883
925
|
required: ["slug"],
|
|
884
926
|
},
|
|
@@ -909,7 +951,7 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
|
|
|
909
951
|
// Pure verb_noun (Smithery Naming). list_x402_sellers / top_x402_sellers stay aliases.
|
|
910
952
|
name: META_MCP_NAMES.list_top_sellers,
|
|
911
953
|
title: "List top x402 sellers",
|
|
912
|
-
annotations: { title: "List top x402 sellers", ...
|
|
954
|
+
annotations: { title: "List top x402 sellers", ...OPEN },
|
|
913
955
|
description:
|
|
914
956
|
"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
957
|
inputSchema: {
|
|
@@ -927,14 +969,14 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
|
|
|
927
969
|
// Dotted like every other listed tool; route_and_execute stays a CallTool alias.
|
|
928
970
|
name: "router.execute",
|
|
929
971
|
title: "Route and execute an external x402 tool",
|
|
930
|
-
annotations: { title: "Route and execute an external x402 tool", ...
|
|
972
|
+
annotations: { title: "Route and execute an external x402 tool", ...CALL_PAID },
|
|
931
973
|
description:
|
|
932
974
|
`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
975
|
inputSchema: {
|
|
934
976
|
type: "object",
|
|
935
977
|
properties: {
|
|
936
978
|
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)." },
|
|
979
|
+
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
980
|
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
981
|
},
|
|
940
982
|
required: ["task"],
|
|
@@ -949,7 +991,7 @@ server.setRequestHandler(ListToolsRequestSchema, redacted(withCatalog(async () =
|
|
|
949
991
|
return { tools: listed };
|
|
950
992
|
})));
|
|
951
993
|
|
|
952
|
-
server.setRequestHandler(
|
|
994
|
+
server.setRequestHandler("tools/call", redacted(withCatalog(async (req, extra) => {
|
|
953
995
|
const { name: rawName, arguments: args = {} } = req.params;
|
|
954
996
|
const name = resolveListedName(rawName);
|
|
955
997
|
const overBound = toolInputBoundRefusal(rawName, args);
|
|
@@ -957,7 +999,7 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
|
|
|
957
999
|
try {
|
|
958
1000
|
if (name === "catalog.search") {
|
|
959
1001
|
const q = String(args.query ?? "").trim();
|
|
960
|
-
const results = searchTools(q, args.limit
|
|
1002
|
+
const results = searchTools(q, searchLimit(args.limit));
|
|
961
1003
|
const workflows = rankWorkflows(q, 2);
|
|
962
1004
|
if (!results.length && !workflows.length) {
|
|
963
1005
|
// A caller that passed no query is told which argument to pass, not
|
|
@@ -1051,10 +1093,10 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
|
|
|
1051
1093
|
claudeCodeHosted: `claude mcp add --transport http agent402 ${BASE}/mcp`,
|
|
1052
1094
|
claudeCodeNpm: `claude mcp add agent402 -s user -- npx -y agent402-mcp@${AGENT402_MCP_VERSION}`,
|
|
1053
1095
|
cursorHosted: { mcpServers: { agent402: { url: `${BASE}/mcp` } } },
|
|
1054
|
-
npm: "npx -y agent402-mcp@0.
|
|
1096
|
+
npm: "npx -y agent402-mcp@0.14.1",
|
|
1055
1097
|
maintainer: "Havok Holdings LLC",
|
|
1056
1098
|
},
|
|
1057
|
-
positioning: `Agent402 is
|
|
1099
|
+
positioning: `Agent402 is the payment and trust layer for agent commerce: agents find, pay for and verify every paid call to Agent402, across x402 and MPP, with a signed receipt for each one. 500+ ready tools on the same rails. Flagship search/answer first, the long tail 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
1100
|
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
1101
|
});
|
|
1060
1102
|
}
|
|
@@ -1063,7 +1105,7 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
|
|
|
1063
1105
|
service: BASE,
|
|
1064
1106
|
connector: "stdio npm package (agent402-mcp)",
|
|
1065
1107
|
maintainer: "Havok Holdings LLC",
|
|
1066
|
-
positioning: `Agent402 is
|
|
1108
|
+
positioning: `Agent402 is the payment and trust layer for agent commerce: agents find, pay for and verify every paid call to Agent402, across x402 and MPP, with a signed receipt for each one. 500+ ready tools on the same rails. 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
1109
|
startHere: {
|
|
1068
1110
|
firstJob: "Search the web and answer questions. Call web.search or web.answer directly, or catalog.find with your task.",
|
|
1069
1111
|
mode: HAS_WALLET ? "usdc" : HAS_CREDITS ? "credits" : "proof-of-work",
|
|
@@ -1071,7 +1113,7 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
|
|
|
1071
1113
|
install: {
|
|
1072
1114
|
claudeCodeHosted: `claude mcp add --transport http agent402 ${BASE}/mcp`,
|
|
1073
1115
|
claudeCodeNpm: `claude mcp add agent402 -s user -- npx -y agent402-mcp@${AGENT402_MCP_VERSION}`,
|
|
1074
|
-
npm: "npx -y agent402-mcp@0.
|
|
1116
|
+
npm: "npx -y agent402-mcp@0.14.1",
|
|
1075
1117
|
maintainer: "Havok Holdings LLC",
|
|
1076
1118
|
},
|
|
1077
1119
|
tools: catalog.size,
|
|
@@ -1186,7 +1228,9 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
|
|
|
1186
1228
|
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
1229
|
// Body matches the route-execute input schema; include:"external" is what
|
|
1188
1230
|
// pays an OUTSIDE seller (vs this host's catalog). Paid via callEndpoint.
|
|
1189
|
-
|
|
1231
|
+
const routed = paramsObject(args.params, "router.execute");
|
|
1232
|
+
if (!routed.ok) return { content: [{ type: "text", text: routed.text }], isError: true };
|
|
1233
|
+
return await callEndpoint(tool, { task, include: "external", maxUsd, ...(Object.keys(routed.value).length ? { params: routed.value } : {}) }, { onProgress: progressNotifier(req, extra) });
|
|
1190
1234
|
}
|
|
1191
1235
|
// Curated tools are exposed verb_noun for tools/list consistency, but the
|
|
1192
1236
|
// real slug is kebab, accept exposed name, plain snake, or raw slug.
|
|
@@ -1199,7 +1243,13 @@ server.setRequestHandler(CallToolRequestSchema, redacted(withCatalog(async (req,
|
|
|
1199
1243
|
if (!tool) {
|
|
1200
1244
|
return { content: [{ type: "text", text: `Unknown tool slug "${wanted}". Use catalog.search to find the right slug.` }], isError: true };
|
|
1201
1245
|
}
|
|
1202
|
-
|
|
1246
|
+
let input = args;
|
|
1247
|
+
if (name === "catalog.call") {
|
|
1248
|
+
const p = paramsObject(args.params, "catalog.call");
|
|
1249
|
+
if (!p.ok) return { content: [{ type: "text", text: p.text }], isError: true };
|
|
1250
|
+
input = p.value;
|
|
1251
|
+
}
|
|
1252
|
+
const out = await callEndpoint(tool, input, { onProgress: progressNotifier(req, extra) });
|
|
1203
1253
|
// call_tool: wrap structuredContent in {slug, result} to match META_OUTPUT_SCHEMAS["catalog.call"]
|
|
1204
1254
|
// while keeping content text as the native tool JSON.
|
|
1205
1255
|
if (name === "catalog.call" && !out.isError && out.structuredContent) {
|
|
@@ -1229,11 +1279,28 @@ try {
|
|
|
1229
1279
|
const requested = (process.env.AGENT402_TOOLS || DEFAULT_CURATED.join(","))
|
|
1230
1280
|
.split(",").map((s) => s.trim()).filter(Boolean);
|
|
1231
1281
|
curated = requested.map((slug) => catalog.get(slug)).filter(Boolean);
|
|
1282
|
+
syncInstructions();
|
|
1232
1283
|
log(`catalog: ${catalog.size} tools from ${BASE}; ${curated.length} first-class, rest via catalog.search/catalog.call`);
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1284
|
+
// A key is reported configured only once it parses: a key that does not
|
|
1285
|
+
// parse is named (never printed) so the operator sees it before the first
|
|
1286
|
+
// paid call fails on it.
|
|
1287
|
+
{
|
|
1288
|
+
const parsed = [], broken = [];
|
|
1289
|
+
if (AGENT_KEY) {
|
|
1290
|
+
try { const { privateKeyToAccount } = await import("viem/accounts"); evmAccount(privateKeyToAccount); parsed.push("EVM"); } catch { broken.push("AGENT_KEY"); }
|
|
1291
|
+
}
|
|
1292
|
+
if (SOLANA_AGENT_KEY) {
|
|
1293
|
+
try { await solanaSigner(); parsed.push("Solana"); } catch { broken.push("SOLANA_AGENT_KEY"); }
|
|
1294
|
+
}
|
|
1295
|
+
const caps = `max/call ${MAX_PER_CALL === Infinity ? "unlimited" : `$${MAX_PER_CALL}`}, session budget ${BUDGET === Infinity ? "unlimited" : `$${BUDGET}`}`;
|
|
1296
|
+
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`);
|
|
1297
|
+
log(parsed.length
|
|
1298
|
+
? `payment: USDC via x402 (${parsed.join(" + ")} wallet configured; ${caps})`
|
|
1299
|
+
: HAS_WALLET
|
|
1300
|
+
? "payment: no usable wallet key"
|
|
1301
|
+
: HAS_CREDITS
|
|
1302
|
+
? `payment: credits key configured (${caps})`
|
|
1303
|
+
: "payment: proof-of-work on eligible tools (no AGENT_KEY / SOLANA_AGENT_KEY)");
|
|
1304
|
+
}
|
|
1238
1305
|
|
|
1239
1306
|
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 is
|
|
122
|
+
"Agent402 is the payment and trust layer for agent commerce: agents find, pay for and verify every paid call to Agent402, across x402 and MPP, with a signed receipt for each one. 500+ ready tools on the same rails. 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";
|
|
@@ -449,7 +449,7 @@ export const FLAGSHIP_OUTPUT_SCHEMAS = {
|
|
|
449
449
|
key: { type: "string" },
|
|
450
450
|
bytes: { type: "integer" },
|
|
451
451
|
updated: { type: "number" },
|
|
452
|
-
expiresAt: { type: "number" },
|
|
452
|
+
expiresAt: { type: ["number", "null"], description: "Expiry in unix seconds; null when the key does not expire" },
|
|
453
453
|
owner: { type: "string" },
|
|
454
454
|
persistent: { type: "boolean" },
|
|
455
455
|
deleted: { type: "boolean" },
|
|
@@ -494,7 +494,7 @@ export function mcpJsonResult(obj) {
|
|
|
494
494
|
* Hosted URL is parameterized; npm / Claude Code / Cursor notes
|
|
495
495
|
* match docs/ecosystem-listings.md + wiki/MCP-Connector.md.
|
|
496
496
|
*/
|
|
497
|
-
export const AGENT402_MCP_VERSION = "0.
|
|
497
|
+
export const AGENT402_MCP_VERSION = "0.14.1";
|
|
498
498
|
|
|
499
499
|
/** A listed MCP tool description, at most `max` characters. Hosts truncate or
|
|
500
500
|
* skip long descriptions, so the listing keeps the first whole sentences; the
|
|
@@ -526,12 +526,12 @@ export function mcpInstallHints(baseUrl) {
|
|
|
526
526
|
mcpServers: {
|
|
527
527
|
agent402: {
|
|
528
528
|
command: "npx",
|
|
529
|
-
args: ["-y", "agent402-mcp@0.
|
|
529
|
+
args: ["-y", "agent402-mcp@0.14.1"],
|
|
530
530
|
env: { AGENT_KEY: "0xYOUR_PRIVATE_KEY" },
|
|
531
531
|
},
|
|
532
532
|
},
|
|
533
533
|
},
|
|
534
|
-
npm: "npx -y agent402-mcp@0.
|
|
534
|
+
npm: "npx -y agent402-mcp@0.14.1",
|
|
535
535
|
maintainer: "Havok Holdings LLC",
|
|
536
536
|
};
|
|
537
537
|
}
|
|
@@ -541,19 +541,35 @@ export function mcpInstallHints(baseUrl) {
|
|
|
541
541
|
* server.describe. Keep tool names listed-only (dotted Smithery form) (self-consistency) and lead
|
|
542
542
|
* with search/answer as the front door.
|
|
543
543
|
*/
|
|
544
|
-
|
|
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, stock = false } = {}) {
|
|
545
559
|
const install = mcpInstallHints(baseUrl);
|
|
546
560
|
const hosted = install.hostedUrl;
|
|
547
561
|
return [
|
|
548
|
-
"Agent402 is
|
|
549
|
-
|
|
562
|
+
"Agent402 is the payment and trust layer for agent commerce: agents find, pay for and verify every paid call to Agent402, across x402 and MPP, with a signed receipt for each one. 500+ ready tools on the same rails. 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.",
|
|
563
|
+
// market.quote only where the server lists a stock quote (it is listed then).
|
|
564
|
+
`Flagship tools: web.search (live web search), web.answer (answers with citations), web.news, browser.render, ${stock ? "market.quote, " : ""}audio.transcribe, memory.read, memory.write.`,
|
|
550
565
|
"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.",
|
|
551
566
|
// Only where the decide tools are listed: an instruction must never name a
|
|
552
567
|
// tool the connector does not advertise.
|
|
553
568
|
...(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."] : []),
|
|
554
|
-
|
|
569
|
+
// demand.request is named only where it is listed (the hosted connector).
|
|
570
|
+
`Also: server.describe (connector details), payment.info (wallet and payment setup)${demand ? ", demand.request (report a missing tool)" : ""}.`,
|
|
555
571
|
`Install (npm package, pinned): ${install.claudeCodeNpm}`,
|
|
556
|
-
|
|
572
|
+
`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}`,
|
|
557
573
|
`Cursor mcp.json: { "mcpServers": { "agent402": { "url": "${hosted}" } } }`,
|
|
558
574
|
`Docs: ${baseUrl}/llms.txt · status ${baseUrl}/status`,
|
|
559
575
|
].join("\n");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent402-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.1",
|
|
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. Agent402 is
|
|
12
|
+
"description": "Agent402 MCP server. Agent402 is the payment and trust layer for agent commerce: agents find, pay for and verify every paid call to Agent402, across x402 and MPP, with a signed receipt for each one. The applied layer of Agentic Finance. 500+ ready tools on the same rails: 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/
|
|
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",
|
|
@@ -93,8 +95,15 @@
|
|
|
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/
|
|
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
|
+
}
|