@priors/mcp 0.2.2 → 0.2.3

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
@@ -21,7 +21,7 @@ repaying.
21
21
 
22
22
  | tool | what it does | needs the key |
23
23
  |---|---|---|
24
- | `pay_url(url, method?, body?, max_price_usd?, max_borrow_usd?)` | fetch an https URL, pay its x402 402 in USDG if the price is ≤ `max_price_usd` (default **$0.10**); borrows the gap only if `max_borrow_usd` is given. Refuses private and local addresses, never follows a redirect, answers within 45 s, and never signs a second payment for a purchase that is still pending (a new call resends the same one) | yes |
24
+ | `pay_url(url, method?, body?, max_price_usd?, max_borrow_usd?)` | fetch an https URL, pay its x402 402 in USDG if the price is ≤ `max_price_usd` (default **$0.10**); borrows the gap only if `max_borrow_usd` is given. Refuses private and local addresses, never follows a redirect, answers within 45 s, and never signs a second payment for a purchase that is still pending, until its validBefore plus 60 s (a new call resends the same one, also after a restart, in a new session or from another session of the same wallet: see `PRIORS_STATE_DIR`) | yes |
25
25
  | `wallet_balance(address?)` | USDG and gas ETH of the wallet (or any address) | no (with `address`) |
26
26
  | `credit_status(agent_id?)` | line, drawn, available, backer, record, score, open loans and due dates; on a stock line, the stock tokens behind it, and `available` capped by what the stock vault lets it draw | no (with `agent_id`) |
27
27
  | `stock_assets(symbol?)` | the stock tokens the Priors stock vault accepts: live Chainlink price, whether it lends against each now (or why not: a sharp price move, a multiplier change, a paused or blocked token), loan-to-value | no |
@@ -54,6 +54,7 @@ dedicated agent wallet holding only what the agent may spend.
54
54
  | `PRIORS_ALLOW_LOCAL` | off | `1` lets `pay_url` reach `http://localhost` and private addresses (local testing only) |
55
55
  | `PRIORS_SCORE_V2` | `https://priors.trade/api/score-v2` | where `score_of` reads Priors Score v2; `off` shows the on-chain score only |
56
56
  | `PRIORS_STOCK_VAULT` | the bundled deployments file's `stockVault` | the stock vault the stock tools and `credit_status` read |
57
+ | `PRIORS_STATE_DIR` | `~/.local/state/priors-mcp` | where the payments signed and not yet settled are kept (one owner-only file per wallet, never the key, with a short-lived `.lock` beside it while it is written), so a restart, a new session or another session of the same wallet resends them instead of signing again; `off` keeps them in memory only |
57
58
 
58
59
  Contract addresses (pool, lens, registry, USDG) come from `deployments/4663.v2.json`, bundled in the package, and the
59
60
  accepted stock tokens from `deployments/stock-assets.4663.json`. The stock vault's address (live since 2026-09-28)
@@ -68,7 +69,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
68
69
  "mcpServers": {
69
70
  "priors": {
70
71
  "command": "npx",
71
- "args": ["-y", "@priors/mcp@0.2.2"],
72
+ "args": ["-y", "@priors/mcp@0.2.3"],
72
73
  "env": {
73
74
  "PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
74
75
  "PRIORS_AGENT_ID": "1234"
@@ -90,7 +91,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
90
91
  "mcpServers": {
91
92
  "priors": {
92
93
  "command": "npx",
93
- "args": ["-y", "@priors/mcp@0.2.2"],
94
+ "args": ["-y", "@priors/mcp@0.2.3"],
94
95
  "env": {
95
96
  "PRIORS_KEY": "${PRIORS_KEY}",
96
97
  "PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
@@ -100,7 +101,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
100
101
  }
101
102
  ```
102
103
 
103
- or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.2.2`
104
+ or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.2.3`
104
105
  (the key is expanded by your shell from the environment; do not paste it on the command line).
105
106
 
106
107
  ## Try it
@@ -9,7 +9,7 @@ if (argv.some((a) => /(^|[^0-9a-fA-F])(0x)?[0-9a-fA-F]{64}($|[^0-9a-fA-F])/.test
9
9
  process.exit(2);
10
10
  }
11
11
  if (argv.includes("--help") || argv.includes("-h")) {
12
- process.stderr.write("priors-mcp: MCP server (stdio) for Priors on Robinhood Chain.\nenv: PRIORS_KEY (wallet key, optional), PRIORS_RPC, PRIORS_AGENT_ID, PRIORS_FACILITATOR, PRIORS_MAX_PRICE_USD, PRIORS_MAX_BORROW_USD, PRIORS_MAX_SPEND_USD, PRIORS_MAX_BORROW_TOTAL_USD, PRIORS_ALLOW_LOCAL, PRIORS_STOCK_VAULT, PRIORS_SCORE_V2\nSee the README for the Claude Desktop / Claude Code config.\n");
12
+ process.stderr.write("priors-mcp: MCP server (stdio) for Priors on Robinhood Chain.\nenv: PRIORS_KEY (wallet key, optional), PRIORS_RPC, PRIORS_AGENT_ID, PRIORS_FACILITATOR, PRIORS_MAX_PRICE_USD, PRIORS_MAX_BORROW_USD, PRIORS_MAX_SPEND_USD, PRIORS_MAX_BORROW_TOTAL_USD, PRIORS_ALLOW_LOCAL, PRIORS_STOCK_VAULT, PRIORS_SCORE_V2, PRIORS_STATE_DIR\nSee the README for the Claude Desktop / Claude Code config.\n");
13
13
  process.exit(0);
14
14
  }
15
15
  if (argv.length > 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@priors/mcp",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "private": false,
5
5
  "description": "MCP server for Priors on Robinhood Chain: pay x402 URLs in USDG, read balances, credit lines and scores, borrow and repay. Key from PRIORS_KEY only.",
6
6
  "type": "module",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@modelcontextprotocol/sdk": "^1.30.1",
45
- "@priors/x402": "0.2.2",
45
+ "@priors/x402": "0.2.3",
46
46
  "ethers": "^6.13.4",
47
47
  "undici": "6.29.0",
48
48
  "zod": "^4.6.5"
package/src/server.mjs CHANGED
@@ -18,7 +18,11 @@
18
18
  // PRIORS_ALLOW_LOCAL "1": pay_url may reach http://localhost and private addresses (testing only)
19
19
  // PRIORS_SCORE_V2 where score_of reads Priors Score v2 (default https://priors.trade/api/score-v2; "off": v1 only)
20
20
  // PRIORS_STOCK_VAULT the stock vault's address (default: deployments/4663.v2.json `stockVault`)
21
- import { readFileSync } from "node:fs";
21
+ // PRIORS_STATE_DIR where signed, unsettled payments are kept across restarts and shared by every session of the
22
+ // wallet (default ~/.local/state/priors-mcp; "off": memory only)
23
+ import { readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, statSync, rmSync } from "node:fs";
24
+ import { homedir } from "node:os";
25
+ import { join } from "node:path";
22
26
  import { randomBytes } from "node:crypto";
23
27
  import { lookup as dnsLookup } from "node:dns/promises";
24
28
  import { isIP } from "node:net";
@@ -240,6 +244,70 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
240
244
  // answers a batch that size with HTTP 429, which ethers retries until its 5-minute timeout (stock_assets' ~140 reads).
241
245
  const provider = deps.provider || new ethers.JsonRpcProvider(rpc, ethers.Network.from(X.robinhood.chainId), { staticNetwork: true, cacheTimeout: -1, batchMaxCount: 1 });
242
246
  const wallet = key ? new ethers.Wallet(key, provider) : null;
247
+ // The payments this wallet signed and has not seen settle outlive the process (a restart, or the client closing its
248
+ // session, starts a new one): one file per wallet under PRIORS_STATE_DIR (default ~/.local/state/priors-mcp; "off"
249
+ // disables it), owner-only. It holds signed authorizations, each payable only to the merchant it was sent to, never the key.
250
+ const stateRaw = String(env.PRIORS_STATE_DIR ?? "").trim();
251
+ const stateDir = /^(off|none|false|0)$/i.test(stateRaw) ? null : stateRaw || join(homedir(), ".local", "state", "priors-mcp");
252
+ const stateFile = wallet && stateDir ? join(stateDir, `outstanding-${wallet.address.toLowerCase()}.json`) : null;
253
+ // An entry is { paymentHeaders, validBefore, price (bigint), payTo }: only what this server wrote, never the merchant's
254
+ // own requirement object (its fields are the merchant's to choose). On disk the price is a decimal string; each entry
255
+ // is checked on its own, so one bad entry never costs the others. No reviver.
256
+ const live = (e, nowS) => e.validBefore + X.SKEW_SECONDS > nowS;
257
+ function entryFrom(v) {
258
+ if (!v || typeof v !== "object" || !v.paymentHeaders || typeof v.paymentHeaders !== "object") return null;
259
+ const headers = {};
260
+ for (const [k, x] of Object.entries(v.paymentHeaders)) { if (!/^(payment-signature|x-payment)$/i.test(k) || typeof x !== "string") return null; headers[k] = x; }
261
+ const validBefore = Number(v.validBefore);
262
+ if (Object.keys(headers).length === 0 || !Number.isSafeInteger(validBefore) || !/^\d{1,30}$/.test(String(v.price)) || !ethers.isAddress(String(v.payTo))) return null;
263
+ return { paymentHeaders: headers, validBefore, price: BigInt(v.price), payTo: String(v.payTo) };
264
+ }
265
+ function readState() {
266
+ const m = new Map();
267
+ try {
268
+ const obj = JSON.parse(readFileSync(stateFile, "utf8"));
269
+ const nowS = Math.floor(Date.now() / 1000);
270
+ for (const [k, v] of Object.entries(obj && typeof obj === "object" ? obj : {})) { const e = entryFrom(v); if (e && live(e, nowS)) m.set(k, e); }
271
+ } catch (_) { /* no file yet, or unreadable */ }
272
+ return m;
273
+ }
274
+ function writeState(m) {
275
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
276
+ const tmp = `${stateFile}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
277
+ writeFileSync(tmp, JSON.stringify(Object.fromEntries([...m].map(([k, e]) => [k, { paymentHeaders: e.paymentHeaders, validBefore: e.validBefore, price: String(e.price), payTo: e.payTo }]))), { mode: 0o600 });
278
+ renameSync(tmp, stateFile);
279
+ }
280
+ // Several servers can share one wallet (two sessions, Claude Desktop and Claude Code): every change is a read-modify-write
281
+ // of the file under an exclusive lock file, so no server rewrites the file from its own map and erases another's entries.
282
+ // Best effort: a lock older than 10 s is stale, and after 2 s the write goes ahead without it. Waiting for it delays
283
+ // this call only (an async wait, never a blocking one): the server keeps answering meanwhile. Inside one process the
284
+ // lock is held only across synchronous code, so two calls of this server never contend.
285
+ async function locked(fn) {
286
+ const lock = `${stateFile}.lock`;
287
+ const giveUp = Date.now() + 2000;
288
+ let held = false;
289
+ for (;;) {
290
+ try { closeSync(openSync(lock, "wx", 0o600)); held = true; break; } catch (e) {
291
+ if (e?.code === "ENOENT") { try { mkdirSync(stateDir, { recursive: true, mode: 0o700 }); continue; } catch (_) { break; } }
292
+ if (e?.code !== "EEXIST") break;
293
+ try { if (Date.now() - statSync(lock).mtimeMs > 10_000) { rmSync(lock, { force: true }); continue; } } catch (_) { continue; }
294
+ if (Date.now() > giveUp) break; // never block a payment on the lock
295
+ await new Promise((res) => setTimeout(res, 10));
296
+ }
297
+ }
298
+ try { return fn(); } finally { if (held) rmSync(lock, { force: true }); }
299
+ }
300
+ /** Entries another server wrote since: merged in before any decision to sign. */
301
+ function refresh() { if (stateFile) for (const [k, e] of readState()) if (!outstanding.has(k)) outstanding.set(k, e); }
302
+ async function record(key, e) {
303
+ outstanding.set(key, e);
304
+ if (stateFile) { try { await locked(() => { const m = readState(); m.set(key, e); writeState(m); }); } catch (_) { /* best effort: memory still holds it */ } }
305
+ }
306
+ async function forget(key) {
307
+ outstanding.delete(key);
308
+ if (stateFile) { try { await locked(() => { const m = readState(); if (m.delete(key)) writeState(m); }); } catch (_) { /* best effort */ } }
309
+ }
310
+ refresh();
243
311
  const contracts = C.creditContracts({ runner: provider, addresses: { pool: addresses.pool, lens: addresses.lens, usdg: addresses.usdg, registry: addresses.registry, stockVault: addresses.stockVault || null } });
244
312
 
245
313
  // The chain, behind one facade (tests replace it).
@@ -342,29 +410,39 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
342
410
  target.hash = ""; // a fragment never reaches the merchant: url#a and url#b are the same purchase
343
411
  const purchase = `${method} ${target.href}`;
344
412
  const now = Math.floor(Date.now() / 1000);
345
- for (const [k, v] of outstanding) if (v.validBefore <= now) outstanding.delete(k);
413
+ // Kept for the payer's clock-skew margin past validBefore: the chain's clock may be behind this machine's.
414
+ for (const [k, v] of outstanding) if (!live(v, now)) outstanding.delete(k); // the file drops them on its next write
415
+ refresh(); // a payment another server of this wallet (another session) signed for this purchase is resent, not signed again
416
+ // SHORTCUT: two sessions of one wallet paying the same URL in the same instant (between this read and the other's
417
+ // onSigned, about one 402 round trip) can still both sign: onSigned records a payment, it cannot veto one. Ceiling:
418
+ // one extra payment of at most max_price_usd to the merchant the user chose, counted in each session's cap (the
419
+ // P-15 class, Low). Upgrade trigger: a report of it, or agents running pay_url concurrently on one wallet: reserve
420
+ // the purchase in the file under the lock before the 402 request, or derive the EIP-3009 nonce per purchase.
346
421
  const lines = [];
347
422
  const prior = outstanding.get(purchase);
348
423
  let r;
424
+ let signedPrice = null; // what the payer checked and signed, never a merchant field read again here
349
425
  if (prior) {
350
426
  // A payment for this purchase is already out and still cashable: send that same one, never a second.
351
427
  r = await X.createPayer({ signer, fetchImpl: payFetch, pendingRetries: 2, maxSleepMs: 10_000, timeoutMs: requestTimeoutMs, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), ...(sleep ? { sleep } : {}) }).resend(url, prior.paymentHeaders, init);
352
- r = { ...r, requirement: prior.requirement, paid: r.response.ok ? prior.price : 0n, borrowed: 0n, signed: prior, resent: true, ...(r.response.ok ? { settlement: settlementOf(r.response) } : {}) };
428
+ r = { ...r, requirement: { payTo: prior.payTo }, paid: r.response.ok ? prior.price : 0n, borrowed: 0n, signed: prior, resent: true, ...(r.response.ok ? { settlement: settlementOf(r.response) } : {}) };
429
+ signedPrice = prior.price;
353
430
  lines.push("No new payment was signed: the same signed payment was sent again.");
354
431
  } else {
355
432
  if (session.spent + maxPrice > spendCap) throw new ToolError(`this would bring what pay_url may sign in this session to ${usd(session.spent + maxPrice)}, above ${usd(spendCap)} (PRIORS_MAX_SPEND_USD). ${usd(session.spent)} was signed so far; the user can raise the limit and restart the server.`);
356
433
  if (maxBorrow > 0n && session.borrowed + maxBorrow > borrowTotalCap) throw new ToolError(`this could bring what is borrowed in this session to ${usd(session.borrowed + maxBorrow)}, above ${usd(borrowTotalCap)} (PRIORS_MAX_BORROW_TOTAL_USD).`);
357
434
  let agentId;
358
435
  if (maxBorrow > 0n) { agentId = await resolveAgent(); await needController(agentId); }
359
- const payer = X.createPayer({ signer, maxPrice, maxBorrow, fetchImpl: payFetch, pendingRetries: 2, maxSleepMs: 10_000, timeoutMs: requestTimeoutMs, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), ...(sleep ? { sleep } : {}), ...(maxBorrow > 0n ? { pool: addresses.pool, agentId } : {}) });
436
+ const payer = X.createPayer({ signer, maxPrice, maxBorrow, fetchImpl: payFetch, pendingRetries: 2, maxSleepMs: 10_000, timeoutMs: requestTimeoutMs, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), ...(sleep ? { sleep } : {}), ...(maxBorrow > 0n ? { pool: addresses.pool, agentId } : {}),
437
+ // Counted when signed, at the price the payer checked and signed (a v1 requirement's `amount` is the merchant's text).
438
+ onSigned: async (s) => { signedPrice = s.price; session.spent += s.price; await record(purchase, { paymentHeaders: s.paymentHeaders, validBefore: s.validBefore, price: s.price, payTo: s.requirement.payTo }); } });
360
439
  try { r = await payer.pay(url, init); } catch (e) {
361
440
  // What the error carries was done: a loan taken and a payment signed are counted, whatever failed after.
362
441
  if (e?.borrowed > 0n) session.borrowed += e.borrowed;
363
442
  if (e?.signed) {
364
- const price = BigInt(e.requirement.amount ?? e.requirement.maxAmountRequired);
365
- session.spent += price;
366
- outstanding.set(purchase, { ...e.signed, requirement: e.requirement, price });
367
- const until = when(e.signed.validBefore);
443
+ if (signedPrice === null) { signedPrice = maxPrice; session.spent += maxPrice; await record(purchase, { ...e.signed, price: maxPrice, payTo: e.requirement.payTo }); } // not reached: onSigned ran
444
+ const price = signedPrice;
445
+ const until = when(e.signed.validBefore + X.SKEW_SECONDS);
368
446
  throw new ToolError(`A payment of ${usd(price)} to ${e.requirement.payTo} was signed, then the request failed (${explain(e)}). The merchant may still settle it until ${until}, so do NOT call pay_url again for this URL before ${until}; check wallet_balance.${e.borrowed > 0n ? ` Borrowed ${usd(e.borrowed)}${e.loanId !== null ? ` as loan #${e.loanId}` : ""}: repay it with the repay tool.` : ""}`);
369
447
  }
370
448
  const loan = e?.borrowed > 0n ? ` ${usd(e.borrowed)} was borrowed${e.loanId !== null ? ` as loan #${e.loanId}` : ""} before it failed: repay it with the repay tool.` : "";
@@ -372,10 +450,9 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
372
450
  if (loan) throw new ToolError(`${explain(e)}.${loan}`);
373
451
  throw e;
374
452
  }
375
- if (r.signed) {
376
- const price = BigInt(r.requirement.amount ?? r.requirement.maxAmountRequired);
377
- session.spent += price; // counted when signed: the merchant can cash it whether or not it says so
378
- if (r.paid === 0n) outstanding.set(purchase, { ...r.signed, requirement: r.requirement, price });
453
+ if (r.signed && signedPrice === null) { // not reached: onSigned counted and recorded it
454
+ signedPrice = maxPrice; session.spent += maxPrice;
455
+ if (r.paid === 0n) await record(purchase, { ...r.signed, price: maxPrice, payTo: r.requirement.payTo });
379
456
  }
380
457
  if (r.borrowed > 0n) { session.borrowed += r.borrowed; lines.push(`Borrowed ${usd(r.borrowed)} from the Priors line for agent #${agentId}${r.loanId !== null ? ` as loan #${r.loanId}` : ""}${r.dueAt ? `, due ${when(r.dueAt)}` : ""}. Repay it with the repay tool before then.`); }
381
458
  else if (r.requirement) lines.push("Nothing was borrowed.");
@@ -383,12 +460,12 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
383
460
  const status = r.timedOut ? "no answer in time" : r.transportError ? "the connection was lost" : `HTTP ${r.response.status}`;
384
461
  if (!r.requirement) lines.unshift(`No payment was asked for: ${method} ${u.href} answered ${status}. Nothing was paid.`);
385
462
  else if (r.paid > 0n) {
386
- outstanding.delete(purchase);
463
+ await forget(purchase);
387
464
  const tx = r.settlement?.transaction;
388
465
  lines.unshift(`Paid ${usd(r.paid)}${r.x402Version ? ` (x402 v${r.x402Version})` : ""} to ${r.requirement.payTo} for ${method} ${u.href}: ${status}.${tx ? (TX_RE.test(String(tx)) ? ` Settlement tx ${tx}.` : " (The merchant's settlement id is not a transaction hash; not shown.)") : ""}`);
389
466
  } else {
390
- const until = when(r.signed.validBefore);
391
- lines.unshift(`A payment of ${usd(BigInt(r.requirement.amount ?? r.requirement.maxAmountRequired))} to ${r.requirement.payTo} was signed and sent (${status}), and the merchant may still settle it until ${until}, so do NOT call pay_url again for this URL before ${until}; check wallet_balance. A later call for this URL only resends this same payment.`);
467
+ const until = when(r.signed.validBefore + X.SKEW_SECONDS);
468
+ lines.unshift(`A payment of ${usd(signedPrice)} to ${r.requirement.payTo} was signed and sent (${status}), and the merchant may still settle it until ${until}, so do NOT call pay_url again for this URL before ${until}; check wallet_balance. A later call for this URL only resends this same payment.`);
392
469
  }
393
470
  const loc = r.response.status >= 300 && r.response.status < 400 ? r.response.headers.get("location") : null;
394
471
  if (loc) lines.push(`The server redirected (not followed): ${fenced(oneLine(loc, 500), "redirect target")}`);