findata-x402-mcp 0.1.0 → 0.2.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
@@ -3,9 +3,94 @@
3
3
  MCP server for **SEC EDGAR fundamentals of the S&P 500** — one-line verdicts, financials (annual, quarterly, TTM),
4
4
  health score, Piotroski / Altman Z'' / accruals signals, peers, anomalies, classified SEC events, screening —
5
5
  from the [findata API](https://api.findata-x402.com). Paid tools pay **per call in USDC on Base** via
6
- [x402](https://x402.org), from a wallet you configure, within spending caps. Free tools need no wallet.
6
+ [x402](https://x402.org), from a wallet you configure, **with your approval** and within spending caps. Free tools
7
+ need no wallet.
7
8
 
8
- ## Configure (Claude Desktop, Cursor, any MCP client)
9
+ Use a **dedicated wallet** that only ever holds a few USDC on Base — never your main wallet. Its key is the only
10
+ secret; the blocks below keep it out of the configuration file wherever the client allows it.
11
+
12
+ ## Configure
13
+
14
+ ### Claude Code
15
+
16
+ Keep the key in your shell environment, and let Claude Code expand it from a project `.mcp.json`
17
+ (`${VAR}` is expanded in `command`, `args` and `env`):
18
+
19
+ ```json
20
+ {
21
+ "mcpServers": {
22
+ "findata": {
23
+ "command": "npx",
24
+ "args": ["-y", "findata-x402-mcp"],
25
+ "env": { "FINDATA_WALLET_PRIVATE_KEY": "${FINDATA_WALLET_PRIVATE_KEY}" }
26
+ }
27
+ }
28
+ }
29
+ ```
30
+
31
+ Or for all your projects (the key is then written in `~/.claude.json`; `read -rs` keeps it out of your shell history):
32
+
33
+ ```sh
34
+ read -rs FINDATA_WALLET_PRIVATE_KEY
35
+ claude mcp add --scope user --env FINDATA_WALLET_PRIVATE_KEY="$FINDATA_WALLET_PRIVATE_KEY" --transport stdio findata -- npx -y findata-x402-mcp
36
+ ```
37
+
38
+ ### Cursor
39
+
40
+ `~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` (one project); `${env:NAME}` reads your environment:
41
+
42
+ ```json
43
+ {
44
+ "mcpServers": {
45
+ "findata": {
46
+ "command": "npx",
47
+ "args": ["-y", "findata-x402-mcp"],
48
+ "env": { "FINDATA_WALLET_PRIVATE_KEY": "${env:FINDATA_WALLET_PRIVATE_KEY}" }
49
+ }
50
+ }
51
+ }
52
+ ```
53
+
54
+ ### VS Code (GitHub Copilot)
55
+
56
+ `.mcp.json` at the workspace root, or `~/.copilot/mcp-config.json`; `${NAME}` reads your environment:
57
+
58
+ ```json
59
+ {
60
+ "mcpServers": {
61
+ "findata": {
62
+ "command": "npx",
63
+ "args": ["-y", "findata-x402-mcp"],
64
+ "env": { "FINDATA_WALLET_PRIVATE_KEY": "${FINDATA_WALLET_PRIVATE_KEY}" }
65
+ }
66
+ }
67
+ }
68
+ ```
69
+
70
+ (The older `.vscode/mcp.json` format, deprecated, can instead prompt for the key: an `inputs` entry of type
71
+ `promptString` with `"password": true`, referenced as `${input:<id>}`.)
72
+
73
+ ### Windsurf
74
+
75
+ `~/.codeium/windsurf/mcp_config.json`; `${env:NAME}` reads your environment:
76
+
77
+ ```json
78
+ {
79
+ "mcpServers": {
80
+ "findata": {
81
+ "command": "npx",
82
+ "args": ["-y", "findata-x402-mcp"],
83
+ "env": { "FINDATA_WALLET_PRIVATE_KEY": "${env:FINDATA_WALLET_PRIVATE_KEY}" }
84
+ }
85
+ }
86
+ }
87
+ ```
88
+
89
+ ### Claude Desktop
90
+
91
+ `claude_desktop_config.json` (Settings → Developer → Edit Config; macOS
92
+ `~/Library/Application Support/Claude/`, Windows `%APPDATA%\Claude\`). Claude Desktop documents no variable
93
+ expansion: **the key is written in clear in this file — treat the file as a secret.**
9
94
 
10
95
  ```json
11
96
  {
@@ -13,41 +98,77 @@ from the [findata API](https://api.findata-x402.com). Paid tools pay **per call
13
98
  "findata": {
14
99
  "command": "npx",
15
100
  "args": ["-y", "findata-x402-mcp"],
16
- "env": {
17
- "FINDATA_WALLET_PRIVATE_KEY": "0x… (a DEDICATED wallet holding a few USDC on Base)",
18
- "FINDATA_MAX_USD_PER_CALL": "0.05",
19
- "FINDATA_MAX_USD_PER_SESSION": "1.00"
20
- }
101
+ "env": { "FINDATA_WALLET_PRIVATE_KEY": "0x… (dedicated wallet)" }
21
102
  }
22
103
  }
23
104
  }
24
105
  ```
25
106
 
26
- Claude Code: `claude mcp add findata -e FINDATA_WALLET_PRIVATE_KEY=0x… -- npx -y findata-x402-mcp`
107
+ ### Approval prompts
108
+
109
+ Each payment waits for your approval in the client, through MCP *elicitation*. Claude Code, VS Code (Copilot) and
110
+ Cursor document it; we could not confirm it for Claude Desktop and Windsurf. A client that cannot show the prompt
111
+ gets a refusal explaining this — never a silent payment. Then use a client that can, or set
112
+ `FINDATA_PAYMENT_APPROVAL=auto` in `env`: the server pays within your caps without asking.
27
113
 
28
114
  | Variable | Default | |
29
115
  |---|---|---|
30
- | `FINDATA_WALLET_PRIVATE_KEY` | unset (free tools only) | payer key; use a dedicated wallet with a small balance |
116
+ | `FINDATA_WALLET_PRIVATE_KEY` | unset (free tools only) | payer key; a dedicated wallet with a small balance |
117
+ | `FINDATA_PAYMENT_APPROVAL` | `ask` | `ask`: each payment waits for your approval; `auto`: pays within the caps without asking (autonomous agents) |
31
118
  | `FINDATA_MAX_USD_PER_CALL` | `0.05` | no payment above this |
32
119
  | `FINDATA_MAX_USD_PER_SESSION` | `1.00` | total paid since the server started |
33
- | `FINDATA_API_URL` | `https://api.findata-x402.com` | |
120
+ | `FINDATA_MAX_USD_PER_DAY` | `2.00` | total paid per UTC day, across restarts and all findata servers of this computer |
121
+ | `FINDATA_MAX_BRIEFS_PER_10_MIN` | `5` | distinct companies `detail=brief` is bought for within 10 minutes |
122
+ | `FINDATA_STATE_DIR` | `~/.findata-x402-mcp` | where the daily spending record (`spending.json`) is kept |
123
+ | `FINDATA_BASE_RPC_URL` | `https://mainnet.base.org` | Base node the wallet balance is read from (`findata_wallet_status` only) |
124
+ | `FINDATA_API_URL` | `https://api.findata-x402.com` | https only (http for localhost) |
34
125
  | `FINDATA_NETWORK` | `eip155:8453` (Base) | `eip155:84532` for Base Sepolia tests |
35
126
  | `FINDATA_EXPECTED_PAYTO` | findata's receiving address (mainnet) | payments to any other address are refused |
36
127
 
128
+ ## Tools
129
+
130
+ | Tool | Price | |
131
+ |---|---|---|
132
+ | `findata_resolve_company` | free | ticker / CIK → canonical id, name, country, sector, data available: check before paying |
133
+ | `findata_catalog` | free | every option with its price and HTTP route, coverage, data freshness |
134
+ | `findata_company_report` | $0.001 – $0.025 | one company; `detail` = `verdict` (start here), `snapshot`, `financials` (`period_type`), `health`, `anomalies`, `signals`, `brief` (everything) |
135
+ | `findata_compare` | from $0.008 | `mode` = `compare` (2 to 10 companies), `peers`, `sector_ranking` |
136
+ | `findata_screen` | $0.02 | companies matching financial criteria, in one call |
137
+ | `findata_events` | $0.005 / $0.01 | classified SEC events of one company (`id`) or of all covered companies |
138
+ | `findata_wallet_status` | free, local | wallet address, USDC balance, what was paid, caps and what remains |
139
+
140
+ The tools and their prices come from the API's `/openapi.json` at startup (a bundled copy is used if the API is
141
+ unreachable): new options appear without updating this package. Each description starts with its prices; paid tools
142
+ are annotated `destructiveHint` (they spend your money).
143
+
37
144
  ## Safety
38
145
 
39
- Before signing, every payment is checked: `exact` scheme, USDC on the configured network, price under the per-call cap,
40
- session total under the session cap, receiving address = findata's. What was signed is checked again. An unknown company
41
- or a bad argument is answered for free by the API, before any payment. `findata_session_spending` (free, local) lists
42
- what the session paid.
146
+ - **Your approval for each payment** (see above): amount, receiving address and request shown before anything is signed.
147
+ - **Caps the model cannot raise**: per call, per session, per UTC day. They are read from the environment only; no
148
+ tool argument touches them. The day's total is kept on disk, so restarting the server does not reset it.
149
+ - **Pinned destination.** Before signing: `exact` scheme, Circle's USDC on the configured network, receiving
150
+ address = findata's. A 402 naming another address, network or token is refused, nothing is signed. What was
151
+ signed is checked again before it is sent. The API URL must be https.
152
+ - **Never paid twice for the same data**: the same call within the hour is answered from the session cache.
153
+ - **Protection against your own agent**: `detail=brief` for more than 5 companies within 10 minutes is refused with a
154
+ suggestion to use `findata_screen` or `findata_compare`, far cheaper than one brief per company.
155
+ - **Auditable answers**: every paid answer ends with the request made, the amount paid, the transaction, and the
156
+ session and day totals. An unknown company or a bad argument is answered for free by the API, before any payment.
157
+ - The key is read from the environment only: never a tool argument, never logged, never returned.
43
158
 
44
- ## Tools
159
+ ## Already have an x402 wallet tool?
160
+
161
+ Start the server with `--no-wallet` (`"args": ["-y", "findata-x402-mcp", "--no-wallet"]`): it does not pay, and does
162
+ not even read a key. A paid tool then answers with the exact request to make, its price and the address it must pay,
163
+ for your wallet tool to execute. The free tools work as usual.
164
+
165
+ ## What is sent where
45
166
 
46
- Generated at startup from the API's `/openapi.json` (a bundled copy is used if the API is unreachable): `get_coverage`,
47
- `preview_company` (free); `get_company_verdict` ($0.001, start here), `get_company_snapshot`, `get_company_financials`,
48
- `get_company_health`, `get_company_peers`, `get_company_anomalies`, `get_company_signals`, `get_company_brief`,
49
- `compare_companies`, `get_company_events`, `get_events_feed`, `get_sector_ranking`, `screen_companies`.
50
- Each description starts with its price.
167
+ - To the findata API: your tool calls, with the `User-Agent` `findata-x402-mcp/<version>` and an `x-findata-session`
168
+ header — a random id drawn at each start of the server and never stored, so findata can count sessions (how many
169
+ go from a free call to a paid one) without knowing who you are. The API keeps no IP address.
170
+ - To a Base node, only when you call `findata_wallet_status`: your wallet address, to read its USDC balance. The node
171
+ sees that address and your IP; set `FINDATA_BASE_RPC_URL` to use your own.
51
172
 
52
173
  ## Source & license
53
174
 
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The paying wallet's USDC balance, read from a Base node (eth_call
3
+ * balanceOf on Circle's USDC contract) — only when findata_wallet_status is
4
+ * called, never at startup or before a payment. The node sees the wallet
5
+ * address and the caller's IP: FINDATA_BASE_RPC_URL lets the user pick it.
6
+ */
7
+ import { createPublicClient, erc20Abi, http } from "viem";
8
+ import { USDC } from "./policy.js";
9
+ export const BALANCE_TIMEOUT_MS = 5_000;
10
+ export function makeBalanceReader(cfg) {
11
+ const client = createPublicClient({ transport: http(cfg.rpcUrl, { timeout: BALANCE_TIMEOUT_MS, retryCount: 0 }) });
12
+ const token = USDC[cfg.network];
13
+ return (address) => client.readContract({ address: token, abi: erc20Abi, functionName: "balanceOf", args: [address] });
14
+ }
package/dist/cache.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Session cache: the same call (same route, same arguments) is paid once.
3
+ *
4
+ * A model calls a tool again when it loses track of what it already has;
5
+ * without this, the user would pay twice for the same data. A paid answer is
6
+ * kept for an hour (the data is refreshed daily, the SEC events hourly), and
7
+ * an identical call made while the first one is still running waits for it
8
+ * instead of paying in parallel. Errors and free answers are not kept.
9
+ */
10
+ export const CACHE_TTL_MS = 60 * 60_000;
11
+ export class SessionCache {
12
+ ttlMs;
13
+ now;
14
+ entries = new Map();
15
+ constructor(ttlMs = CACHE_TTL_MS, now = () => Date.now()) {
16
+ this.ttlMs = ttlMs;
17
+ this.now = now;
18
+ }
19
+ /**
20
+ * The outcome of `produce` for this key, or the one already obtained.
21
+ *
22
+ * @returns shared = the outcome was produced by an earlier (or a concurrent) call.
23
+ */
24
+ async run(key, produce) {
25
+ const t = this.now();
26
+ for (const [k, e] of this.entries)
27
+ if (t - e.at >= this.ttlMs)
28
+ this.entries.delete(k);
29
+ const existing = this.entries.get(key);
30
+ if (existing)
31
+ return { outcome: await existing.outcome, shared: true };
32
+ const outcome = produce();
33
+ const entry = { at: t, outcome };
34
+ this.entries.set(key, entry);
35
+ let result;
36
+ try {
37
+ result = await outcome;
38
+ }
39
+ catch (err) {
40
+ this.entries.delete(key);
41
+ throw err;
42
+ }
43
+ if (!result.paid || result.isError)
44
+ this.entries.delete(key);
45
+ return { outcome: result, shared: false };
46
+ }
47
+ get size() {
48
+ return this.entries.size;
49
+ }
50
+ }
package/dist/client.js CHANGED
@@ -2,19 +2,29 @@
2
2
  * Calling the findata API for a tool — and paying it when it answers 402.
3
3
  *
4
4
  * A free route answers directly. A paid route answers 402 with its payment
5
- * requirements; the server then checks them (policy.ts), reserves the amount
6
- * in the session budget, signs an EIP-3009 USDC authorization with the user's
7
- * key, checks what was signed, and repeats the request with the payment. The
8
- * API settles it only when its answer succeeds: an error (unknown company,
9
- * bad argument) is never charged, and the reservation is then released.
5
+ * requirements; the server then checks them (policy.ts), applies the
6
+ * anti-burst guard, reserves the amount in the session and daily budgets,
7
+ * asks the user's approval (unless configured to pay automatically), signs an
8
+ * EIP-3009 USDC authorization with the user's key, checks what was signed,
9
+ * and repeats the request with the payment. The API settles it only when its
10
+ * answer succeeds: an error (unknown company, bad argument) is never charged,
11
+ * and the reservation is then released. The same call again within the hour
12
+ * is served from the session cache, without paying twice.
10
13
  */
11
14
  import { privateKeyToAccount } from "viem/accounts";
12
15
  import { x402Client, x402HTTPClient } from "@x402/core/client";
13
16
  import { registerExactEvmScheme } from "@x402/evm/exact/client";
14
- import { formatUsd } from "./config.js";
17
+ import { formatUsd, NETWORK_NAMES } from "./config.js";
15
18
  import { requirementProblems, signedProblems } from "./policy.js";
16
- import { buildRequest } from "./tools.js";
19
+ import { buildRequest, callName } from "./tools.js";
20
+ import { USER_AGENT } from "./version.js";
21
+ /** Pays within the caps without asking (FINDATA_PAYMENT_APPROVAL=auto). */
22
+ export const AUTO_APPROVE = async () => ({ approved: true });
17
23
  const TIMEOUT_MS = 30_000;
24
+ /** The route of detail=brief, guarded against bursts. */
25
+ export const BRIEF_PATH = "/company/{id}/brief";
26
+ /** Reads 402s when this server has no wallet (to tell the exact price and address). */
27
+ const decoder = new x402HTTPClient(new x402Client());
18
28
  /** The x402 client signing with the configured key, on the configured network only. */
19
29
  export function makePayer(cfg) {
20
30
  if (!cfg.privateKey)
@@ -34,9 +44,15 @@ async function bodyText(res) {
34
44
  return raw;
35
45
  }
36
46
  }
47
+ const utcTime = (d) => `${d.toISOString().slice(11, 19)} UTC`;
48
+ /** "session total $0.026 of $1; today $0.3 of $2 (UTC)" */
49
+ function budgetLine(budget) {
50
+ const today = budget.spentToday();
51
+ return (`session total $${formatUsd(budget.spent)} of $${formatUsd(budget.sessionCapAtomic)}; ` +
52
+ `today ${today === null ? "unknown (record unreadable)" : `$${formatUsd(today)}`} of $${formatUsd(budget.dailyCapAtomic)} (UTC)`);
53
+ }
37
54
  /** Run one tool call against the API. Never throws: errors come back as isError results. */
38
55
  export async function callTool(tool, args, ctx) {
39
- const doFetch = ctx.fetch ?? fetch;
40
56
  let request;
41
57
  try {
42
58
  request = buildRequest(tool, args);
@@ -44,12 +60,37 @@ export async function callTool(tool, args, ctx) {
44
60
  catch (err) {
45
61
  return { text: `Invalid arguments for ${tool.name}: ${err.message}`, isError: true };
46
62
  }
63
+ const route = `${request.op.method} ${request.pathAndQuery}`;
64
+ let outcome;
65
+ let shared;
66
+ try {
67
+ ({ outcome, shared } = await ctx.cache.run(`${route} ${request.body ?? ""}`, () => fetchAndPay(tool, args ?? {}, request, route, ctx)));
68
+ }
69
+ catch (err) {
70
+ return { text: `findata MCP server error, nothing was charged: ${err.message}`, isError: true };
71
+ }
72
+ if (!outcome.paid || outcome.isError)
73
+ return { text: outcome.text, isError: outcome.isError };
74
+ const { atomic, transaction, at } = outcome.paid;
75
+ const what = shared
76
+ ? `served from this session's cache, already paid $${formatUsd(atomic)} at ${utcTime(at)}: not charged again`
77
+ : `paid $${formatUsd(atomic)} for this call${transaction ? ` (tx ${transaction})` : ""}`;
78
+ return { text: `${outcome.text}\n\n[findata: ${outcome.route} — ${what}; ${budgetLine(ctx.budget)}]`, isError: false };
79
+ }
80
+ async function fetchAndPay(tool, args, request, route, ctx) {
81
+ const op = request.op;
82
+ const fail = (text) => ({ text, isError: true, route });
83
+ const doFetch = ctx.fetch ?? fetch;
47
84
  const url = `${ctx.cfg.apiUrl}${request.pathAndQuery}`;
48
- const baseHeaders = { accept: "application/json" };
85
+ const baseHeaders = {
86
+ accept: "application/json",
87
+ "user-agent": USER_AGENT,
88
+ "x-findata-session": ctx.sessionId,
89
+ };
49
90
  if (request.body !== undefined)
50
91
  baseHeaders["content-type"] = "application/json";
51
92
  const send = (extra = {}) => doFetch(url, {
52
- method: tool.method,
93
+ method: op.method,
53
94
  headers: { ...baseHeaders, ...extra },
54
95
  body: request.body,
55
96
  signal: AbortSignal.timeout(TIMEOUT_MS),
@@ -59,54 +100,73 @@ export async function callTool(tool, args, ctx) {
59
100
  first = await send();
60
101
  }
61
102
  catch (err) {
62
- return { text: `findata API unreachable (${url}): ${err.message}`, isError: true };
103
+ return fail(`findata API unreachable (${url}): ${err.message}`);
63
104
  }
64
105
  if (first.status !== 402) {
65
106
  const text = await bodyText(first);
66
- return first.ok ? { text, isError: false } : { text: `findata API error ${first.status} (nothing was charged): ${text}`, isError: true };
107
+ return first.ok ? { text, isError: false, route } : fail(`findata API error ${first.status} (nothing was charged): ${text}`);
67
108
  }
68
109
  // ── Paid route ─────────────────────────────────────────────────────────
69
- if (!ctx.payer) {
70
- return {
71
- text: `${tool.name} is a paid call (${tool.price ?? "see description"}, USDC on Base via x402) and this server has no wallet. ` +
72
- "Set FINDATA_WALLET_PRIVATE_KEY in the MCP server's env (a dedicated wallet holding a few USDC on Base). " +
73
- "Free tools: get_coverage, preview_company.",
74
- isError: true,
75
- };
76
- }
77
- const { http } = ctx.payer;
110
+ const http = ctx.payer?.http ?? decoder;
78
111
  let paymentRequired;
79
112
  try {
80
113
  paymentRequired = http.getPaymentRequiredResponse((h) => first.headers.get(h));
81
114
  }
82
115
  catch (err) {
83
- return { text: `unreadable payment request from the API: ${err.message}`, isError: true };
116
+ return fail(`unreadable payment request from the API, nothing was paid: ${err.message}`);
84
117
  }
85
118
  const accepts = (paymentRequired.accepts ?? []);
119
+ if (!ctx.payer)
120
+ return fail(noWalletText(tool, request, url, accepts, ctx.cfg));
86
121
  const reasons = [];
87
122
  const req = accepts.find((a) => {
88
123
  const problems = requirementProblems(a, ctx.cfg);
89
124
  reasons.push(...problems);
90
125
  return problems.length === 0;
91
126
  });
92
- if (!req) {
93
- return { text: `Payment refused by this server's safety rules, nothing was signed: ${reasons.join("; ") || "no payment option"}`, isError: true };
94
- }
127
+ if (!req)
128
+ return fail(`Payment refused by this server's safety rules, nothing was signed: ${reasons.join("; ") || "no payment option"}`);
95
129
  const amount = BigInt(req.amount);
130
+ // Anti-burst, then budgets, then the user: each refusal undoes what was taken before it.
131
+ let releaseBurst = () => { };
132
+ if (op.path === BRIEF_PATH) {
133
+ const company = String(args.id).trim().toUpperCase();
134
+ const admitted = ctx.burst.admit(company);
135
+ if (!admitted.ok) {
136
+ return fail(`Payment refused, nothing was paid: ${callName(tool, op)} was already bought for ` +
137
+ `${admitted.companies.length} companies in the last 10 minutes (${admitted.companies.join(", ")}; ` +
138
+ `FINDATA_MAX_BRIEFS_PER_10_MIN=${ctx.burst.limit}). For many companies, one findata_screen call (criteria, $0.02) ` +
139
+ `or findata_compare mode=compare (2 to 10 companies at once) costs far less than one brief per company ` +
140
+ `($${formatUsd(amount)} each). The same company again is not refused.`);
141
+ }
142
+ releaseBurst = admitted.release;
143
+ }
96
144
  try {
97
145
  ctx.budget.reserve(amount);
98
146
  }
99
147
  catch (err) {
100
- return { text: `Payment refused, nothing was signed: ${err.message}`, isError: true };
148
+ releaseBurst();
149
+ return fail(`Payment refused, nothing was signed: ${err.message}`);
101
150
  }
102
151
  let settled = false;
103
152
  let sent = false;
104
153
  try {
154
+ const today = ctx.budget.spentToday();
155
+ const decision = await ctx.approve({
156
+ tool: tool.name,
157
+ route,
158
+ atomic: amount,
159
+ payTo: req.payTo,
160
+ message: `Pay $${formatUsd(amount)} in USDC on ${NETWORK_NAMES[ctx.cfg.network]} to findata (${req.payTo}) ` +
161
+ `for ${route} (${callName(tool, op)})? Spent so far: $${formatUsd(ctx.budget.spent)} of $${formatUsd(ctx.budget.sessionCapAtomic)} ` +
162
+ `this session, ${today === null ? "unknown" : `$${formatUsd(today)}`} of $${formatUsd(ctx.budget.dailyCapAtomic)} today (UTC).`,
163
+ });
164
+ if (!decision.approved)
165
+ return fail(`Payment not approved, nothing was paid: ${decision.reason}`);
105
166
  const payload = await http.createPaymentPayload({ ...paymentRequired, accepts: [req] });
106
167
  const problems = signedProblems(payload, req);
107
- if (problems.length) {
108
- return { text: `Payment refused after signing, nothing was sent: ${problems.join("; ")}`, isError: true };
109
- }
168
+ if (problems.length)
169
+ return fail(`Payment refused after signing, nothing was sent: ${problems.join("; ")}`);
110
170
  sent = true;
111
171
  const paid = await send(http.encodePaymentSignatureHeader(payload));
112
172
  let settlement;
@@ -128,35 +188,56 @@ export async function callTool(tool, args, ctx) {
128
188
  catch {
129
189
  /* keep the body */
130
190
  }
131
- return { text: `Payment rejected (nothing was charged): ${reason}`, isError: true };
191
+ return fail(`Payment rejected (nothing was charged): ${reason}`);
132
192
  }
133
- return { text: `findata API error ${paid.status} (nothing was charged): ${text}`, isError: true };
193
+ return fail(`findata API error ${paid.status} (nothing was charged): ${text}`);
134
194
  }
135
195
  // A success answer means the payment was settled (or is about to be): count it.
136
196
  settled = true;
137
197
  ctx.budget.commit(amount, tool.name, settlement?.transaction);
138
- const tx = settlement?.transaction ? `, tx ${settlement.transaction}` : "";
139
- return {
140
- text: `${text}\n\n[findata: paid $${formatUsd(amount)} for this call${tx}; ` +
141
- `session total $${formatUsd(ctx.budget.spent)} of $${formatUsd(ctx.budget.capAtomic)}]`,
142
- isError: false,
143
- };
198
+ return { text, isError: false, route, paid: { atomic: amount, transaction: settlement?.transaction, at: new Date() } };
144
199
  }
145
200
  catch (err) {
146
201
  if (sent) {
147
202
  // The signed payment left: it may have been settled. Count it, so the
148
- // session budget can only overestimate what was spent.
203
+ // budgets can only overestimate what was spent.
149
204
  settled = true;
150
205
  ctx.budget.commit(amount, tool.name);
151
206
  return {
152
- text: `No answer after sending the payment ($${formatUsd(amount)}; it may have been settled, and counts in the session budget): ${err.message}`,
207
+ text: `No answer after sending the payment ($${formatUsd(amount)}; it may have been settled, and counts in the budgets): ${err.message}`,
153
208
  isError: true,
209
+ route,
210
+ paid: { atomic: amount, at: new Date() },
154
211
  };
155
212
  }
156
- return { text: `Payment failed, nothing was charged: ${err.message}`, isError: true };
213
+ return fail(`Payment failed, nothing was charged: ${err.message}`);
157
214
  }
158
215
  finally {
159
- if (!settled)
216
+ if (!settled) {
160
217
  ctx.budget.release(amount);
218
+ releaseBurst();
219
+ }
161
220
  }
162
221
  }
222
+ /**
223
+ * A paid route and no wallet here: the exact request to make with another x402
224
+ * wallet tool, its price and the address it must pay — or why not to pay it.
225
+ */
226
+ function noWalletText(tool, request, url, accepts, cfg) {
227
+ const why = cfg.noWallet ? "started with --no-wallet" : "no wallet: FINDATA_WALLET_PRIVATE_KEY is unset";
228
+ const lines = [`${callName(tool, request.op)} is a paid call and this server does not pay (${why}). Nothing was paid.`];
229
+ const checks = accepts.map((a) => ({ a, problems: requirementProblems(a, { network: cfg.network, expectedPayTo: cfg.expectedPayTo }) }));
230
+ const ok = checks.find((c) => c.problems.length === 0)?.a;
231
+ if (ok) {
232
+ lines.push("To get this data with an x402 wallet tool, make exactly this request:", ` ${request.op.method} ${url}`, ...(request.body !== undefined ? [` content-type: application/json, body: ${request.body}`] : []), `It costs $${formatUsd(BigInt(ok.amount))} in USDC on ${NETWORK_NAMES[cfg.network]} (${cfg.network}), paid to ${ok.payTo}` +
233
+ (cfg.expectedPayTo ? " (findata's address: do not pay a 402 naming any other)." : "."));
234
+ }
235
+ else {
236
+ lines.push(`Do NOT pay this 402: it fails this server's checks (${checks.flatMap((c) => c.problems).join("; ") || "no payment option"}).`);
237
+ }
238
+ if (!cfg.noWallet) {
239
+ lines.push("Or set FINDATA_WALLET_PRIVATE_KEY in this MCP server's env (a dedicated wallet holding a few USDC on Base) for it to pay, within its caps.");
240
+ }
241
+ lines.push("Free tools: findata_resolve_company, findata_catalog.");
242
+ return lines.join("\n");
243
+ }