findata-x402-mcp 0.1.0 → 0.3.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 +144 -21
- package/dist/balance.js +14 -0
- package/dist/cache.js +50 -0
- package/dist/client.js +122 -41
- package/dist/config.js +79 -24
- package/dist/index.js +41 -8
- package/dist/ledger.js +81 -0
- package/dist/openapi.snapshot.json +4234 -32
- package/dist/policy.js +87 -17
- package/dist/server.js +95 -20
- package/dist/tools.js +195 -95
- package/dist/version.js +4 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,11 +1,97 @@
|
|
|
1
1
|
# findata-x402-mcp
|
|
2
2
|
|
|
3
3
|
MCP server for **SEC EDGAR fundamentals of the S&P 500** — one-line verdicts, financials (annual, quarterly, TTM),
|
|
4
|
-
health score, Piotroski / Altman Z'' / accruals signals, peers, anomalies, classified SEC events, screening
|
|
4
|
+
health score, Piotroski / Altman Z'' / accruals signals, peers, anomalies, classified SEC events, screening,
|
|
5
|
+
crypto holdings (BTC, ETH) disclosed by US issuers —
|
|
5
6
|
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
|
|
7
|
+
[x402](https://x402.org), from a wallet you configure, **with your approval** and within spending caps. Free tools
|
|
8
|
+
need no wallet.
|
|
7
9
|
|
|
8
|
-
|
|
10
|
+
Use a **dedicated wallet** that only ever holds a few USDC on Base — never your main wallet. Its key is the only
|
|
11
|
+
secret; the blocks below keep it out of the configuration file wherever the client allows it.
|
|
12
|
+
|
|
13
|
+
## Configure
|
|
14
|
+
|
|
15
|
+
### Claude Code
|
|
16
|
+
|
|
17
|
+
Keep the key in your shell environment, and let Claude Code expand it from a project `.mcp.json`
|
|
18
|
+
(`${VAR}` is expanded in `command`, `args` and `env`):
|
|
19
|
+
|
|
20
|
+
```json
|
|
21
|
+
{
|
|
22
|
+
"mcpServers": {
|
|
23
|
+
"findata": {
|
|
24
|
+
"command": "npx",
|
|
25
|
+
"args": ["-y", "findata-x402-mcp"],
|
|
26
|
+
"env": { "FINDATA_WALLET_PRIVATE_KEY": "${FINDATA_WALLET_PRIVATE_KEY}" }
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Or for all your projects (the key is then written in `~/.claude.json`; `read -rs` keeps it out of your shell history):
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
read -rs FINDATA_WALLET_PRIVATE_KEY
|
|
36
|
+
claude mcp add --scope user --env FINDATA_WALLET_PRIVATE_KEY="$FINDATA_WALLET_PRIVATE_KEY" --transport stdio findata -- npx -y findata-x402-mcp
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Cursor
|
|
40
|
+
|
|
41
|
+
`~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` (one project); `${env:NAME}` reads your environment:
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"mcpServers": {
|
|
46
|
+
"findata": {
|
|
47
|
+
"command": "npx",
|
|
48
|
+
"args": ["-y", "findata-x402-mcp"],
|
|
49
|
+
"env": { "FINDATA_WALLET_PRIVATE_KEY": "${env:FINDATA_WALLET_PRIVATE_KEY}" }
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### VS Code (GitHub Copilot)
|
|
56
|
+
|
|
57
|
+
`.mcp.json` at the workspace root, or `~/.copilot/mcp-config.json`; `${NAME}` reads your environment:
|
|
58
|
+
|
|
59
|
+
```json
|
|
60
|
+
{
|
|
61
|
+
"mcpServers": {
|
|
62
|
+
"findata": {
|
|
63
|
+
"command": "npx",
|
|
64
|
+
"args": ["-y", "findata-x402-mcp"],
|
|
65
|
+
"env": { "FINDATA_WALLET_PRIVATE_KEY": "${FINDATA_WALLET_PRIVATE_KEY}" }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
(The older `.vscode/mcp.json` format, deprecated, can instead prompt for the key: an `inputs` entry of type
|
|
72
|
+
`promptString` with `"password": true`, referenced as `${input:<id>}`.)
|
|
73
|
+
|
|
74
|
+
### Windsurf
|
|
75
|
+
|
|
76
|
+
`~/.codeium/windsurf/mcp_config.json`; `${env:NAME}` reads your environment:
|
|
77
|
+
|
|
78
|
+
```json
|
|
79
|
+
{
|
|
80
|
+
"mcpServers": {
|
|
81
|
+
"findata": {
|
|
82
|
+
"command": "npx",
|
|
83
|
+
"args": ["-y", "findata-x402-mcp"],
|
|
84
|
+
"env": { "FINDATA_WALLET_PRIVATE_KEY": "${env:FINDATA_WALLET_PRIVATE_KEY}" }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Claude Desktop
|
|
91
|
+
|
|
92
|
+
`claude_desktop_config.json` (Settings → Developer → Edit Config; macOS
|
|
93
|
+
`~/Library/Application Support/Claude/`, Windows `%APPDATA%\Claude\`). Claude Desktop documents no variable
|
|
94
|
+
expansion: **the key is written in clear in this file — treat the file as a secret.**
|
|
9
95
|
|
|
10
96
|
```json
|
|
11
97
|
{
|
|
@@ -13,41 +99,78 @@ from the [findata API](https://api.findata-x402.com). Paid tools pay **per call
|
|
|
13
99
|
"findata": {
|
|
14
100
|
"command": "npx",
|
|
15
101
|
"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
|
-
}
|
|
102
|
+
"env": { "FINDATA_WALLET_PRIVATE_KEY": "0x… (dedicated wallet)" }
|
|
21
103
|
}
|
|
22
104
|
}
|
|
23
105
|
}
|
|
24
106
|
```
|
|
25
107
|
|
|
26
|
-
|
|
108
|
+
### Approval prompts
|
|
109
|
+
|
|
110
|
+
Each payment waits for your approval in the client, through MCP *elicitation*. Claude Code, VS Code (Copilot) and
|
|
111
|
+
Cursor document it; we could not confirm it for Claude Desktop and Windsurf. A client that cannot show the prompt
|
|
112
|
+
gets a refusal explaining this — never a silent payment. Then use a client that can, or set
|
|
113
|
+
`FINDATA_PAYMENT_APPROVAL=auto` in `env`: the server pays within your caps without asking.
|
|
27
114
|
|
|
28
115
|
| Variable | Default | |
|
|
29
116
|
|---|---|---|
|
|
30
|
-
| `FINDATA_WALLET_PRIVATE_KEY` | unset (free tools only) | payer key;
|
|
117
|
+
| `FINDATA_WALLET_PRIVATE_KEY` | unset (free tools only) | payer key; a dedicated wallet with a small balance |
|
|
118
|
+
| `FINDATA_PAYMENT_APPROVAL` | `ask` | `ask`: each payment waits for your approval; `auto`: pays within the caps without asking (autonomous agents) |
|
|
31
119
|
| `FINDATA_MAX_USD_PER_CALL` | `0.05` | no payment above this |
|
|
32
120
|
| `FINDATA_MAX_USD_PER_SESSION` | `1.00` | total paid since the server started |
|
|
33
|
-
| `
|
|
121
|
+
| `FINDATA_MAX_USD_PER_DAY` | `2.00` | total paid per UTC day, across restarts and all findata servers of this computer |
|
|
122
|
+
| `FINDATA_MAX_BRIEFS_PER_10_MIN` | `5` | distinct companies `detail=brief` is bought for within 10 minutes |
|
|
123
|
+
| `FINDATA_STATE_DIR` | `~/.findata-x402-mcp` | where the daily spending record (`spending.json`) is kept |
|
|
124
|
+
| `FINDATA_BASE_RPC_URL` | `https://mainnet.base.org` | Base node the wallet balance is read from (`findata_wallet_status` only) |
|
|
125
|
+
| `FINDATA_API_URL` | `https://api.findata-x402.com` | https only (http for localhost) |
|
|
34
126
|
| `FINDATA_NETWORK` | `eip155:8453` (Base) | `eip155:84532` for Base Sepolia tests |
|
|
35
127
|
| `FINDATA_EXPECTED_PAYTO` | findata's receiving address (mainnet) | payments to any other address are refused |
|
|
36
128
|
|
|
129
|
+
## Tools
|
|
130
|
+
|
|
131
|
+
| Tool | Price | |
|
|
132
|
+
|---|---|---|
|
|
133
|
+
| `findata_resolve_company` | free | ticker / CIK → canonical id, name, country, sector, data available: check before paying |
|
|
134
|
+
| `findata_catalog` | free | every option with its price and HTTP route, coverage, data freshness |
|
|
135
|
+
| `findata_company_report` | $0.001 – $0.025 | one company; `detail` = `verdict` (start here), `snapshot`, `financials` (`period_type`), `health`, `anomalies`, `signals`, `brief` (everything) |
|
|
136
|
+
| `findata_compare` | from $0.008 | `mode` = `compare` (2 to 10 companies), `peers`, `sector_ranking` |
|
|
137
|
+
| `findata_screen` | $0.02 | companies matching financial criteria, in one call |
|
|
138
|
+
| `findata_events` | $0.005 / $0.01 | classified SEC events of one company (`id`) or of all covered companies |
|
|
139
|
+
| `findata_crypto_treasuries` | free / $0.02 | `view` = `universe` (issuers covered, open assets; free), `treasuries` (issuers of one asset, BTC or ETH, ranked by units held, with cost, fair value and source filing) |
|
|
140
|
+
| `findata_wallet_status` | free, local | wallet address, USDC balance, what was paid, caps and what remains |
|
|
141
|
+
|
|
142
|
+
The tools and their prices come from the API's `/openapi.json` at startup (a bundled copy is used if the API is
|
|
143
|
+
unreachable): new options appear without updating this package. Each description starts with its prices; paid tools
|
|
144
|
+
are annotated `destructiveHint` (they spend your money).
|
|
145
|
+
|
|
37
146
|
## Safety
|
|
38
147
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
148
|
+
- **Your approval for each payment** (see above): amount, receiving address and request shown before anything is signed.
|
|
149
|
+
- **Caps the model cannot raise**: per call, per session, per UTC day. They are read from the environment only; no
|
|
150
|
+
tool argument touches them. The day's total is kept on disk, so restarting the server does not reset it.
|
|
151
|
+
- **Pinned destination.** Before signing: `exact` scheme, Circle's USDC on the configured network, receiving
|
|
152
|
+
address = findata's. A 402 naming another address, network or token is refused, nothing is signed. What was
|
|
153
|
+
signed is checked again before it is sent. The API URL must be https.
|
|
154
|
+
- **Never paid twice for the same data**: the same call within the hour is answered from the session cache.
|
|
155
|
+
- **Protection against your own agent**: `detail=brief` for more than 5 companies within 10 minutes is refused with a
|
|
156
|
+
suggestion to use `findata_screen` or `findata_compare`, far cheaper than one brief per company.
|
|
157
|
+
- **Auditable answers**: every paid answer ends with the request made, the amount paid, the transaction, and the
|
|
158
|
+
session and day totals. An unknown company or a bad argument is answered for free by the API, before any payment.
|
|
159
|
+
- The key is read from the environment only: never a tool argument, never logged, never returned.
|
|
43
160
|
|
|
44
|
-
##
|
|
161
|
+
## Already have an x402 wallet tool?
|
|
162
|
+
|
|
163
|
+
Start the server with `--no-wallet` (`"args": ["-y", "findata-x402-mcp", "--no-wallet"]`): it does not pay, and does
|
|
164
|
+
not even read a key. A paid tool then answers with the exact request to make, its price and the address it must pay,
|
|
165
|
+
for your wallet tool to execute. The free tools work as usual.
|
|
166
|
+
|
|
167
|
+
## What is sent where
|
|
45
168
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
169
|
+
- To the findata API: your tool calls, with the `User-Agent` `findata-x402-mcp/<version>` and an `x-findata-session`
|
|
170
|
+
header — a random id drawn at each start of the server and never stored, so findata can count sessions (how many
|
|
171
|
+
go from a free call to a paid one) without knowing who you are. The API keeps no IP address.
|
|
172
|
+
- To a Base node, only when you call `findata_wallet_status`: your wallet address, to read its USDC balance. The node
|
|
173
|
+
sees that address and your IP; set `FINDATA_BASE_RPC_URL` to use your own.
|
|
51
174
|
|
|
52
175
|
## Source & license
|
|
53
176
|
|
package/dist/balance.js
ADDED
|
@@ -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),
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
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 = {
|
|
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:
|
|
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
|
|
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 } :
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
191
|
+
return fail(`Payment rejected (nothing was charged): ${reason}`);
|
|
132
192
|
}
|
|
133
|
-
return
|
|
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
|
-
|
|
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
|
-
//
|
|
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
|
|
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
|
|
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
|
+
}
|