@priors/mcp 0.2.0 → 0.2.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.
Files changed (2) hide show
  1. package/package.json +2 -2
  2. package/src/server.mjs +54 -13
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@priors/mcp",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
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.0",
45
+ "@priors/x402": "0.2.1",
46
46
  "ethers": "^6.13.4",
47
47
  "undici": "6.29.0",
48
48
  "zod": "^4.6.5"
package/src/server.mjs CHANGED
@@ -71,19 +71,30 @@ function v6Bytes(s) {
71
71
  if (groups.length !== 8) return null;
72
72
  return groups.flatMap((g) => { const v = parseInt(g || "0", 16); return [v >> 8, v & 255]; });
73
73
  }
74
- /** Loopback, private, link-local, CGNAT, unspecified, multicast and IPv4-mapped forms of those. */
74
+ /**
75
+ * Loopback, private, link-local, CGNAT, unspecified, multicast, reserved and documentation blocks, and the IPv6 forms
76
+ * that carry an IPv4 address (IPv4-mapped, NAT64, 6to4) judged by that address; Teredo and site-local are refused.
77
+ */
75
78
  export function isPrivateAddress(ip) {
76
79
  const kind = isIP(ip.replace(/^\[|\]$/g, "").split("%")[0]);
77
80
  if (kind === 4) {
78
- const [a, b] = ip.split(".").map(Number);
79
- return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 198 && (b === 18 || b === 19));
81
+ const [a, b, c] = ip.split(".").map(Number);
82
+ return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 198 && (b === 18 || b === 19))
83
+ || (a === 192 && b === 0 && (c === 0 || c === 2)) || (a === 198 && b === 51 && c === 100) || (a === 203 && b === 0 && c === 113); // 192.0.0.0/24, TEST-NETs
80
84
  }
81
85
  if (kind !== 6) return true; // not an address: refuse rather than guess
82
86
  const x = v6Bytes(ip);
83
87
  if (!x) return true;
84
- if (x.slice(0, 10).every((v) => v === 0) && x[10] === 255 && x[11] === 255) return isPrivateAddress(x.slice(12).join(".")); // ::ffff:a.b.c.d
88
+ const v4at = (i) => isPrivateAddress(x.slice(i, i + 4).join("."));
89
+ if (x.slice(0, 10).every((v) => v === 0) && x[10] === 255 && x[11] === 255) return v4at(12); // ::ffff:a.b.c.d
85
90
  if (x.slice(0, 12).every((v) => v === 0)) return true; // ::, ::1 and the deprecated IPv4-compatible forms
86
- return (x[0] & 0xfe) === 0xfc || (x[0] === 0xfe && (x[1] & 0xc0) === 0x80) || x[0] === 0xff; // fc00::/7, fe80::/10, ff00::/8
91
+ if (x[0] === 0 && x[1] === 0x64 && x[2] === 0xff && x[3] === 0x9b) { // NAT64
92
+ if (x[4] === 0 && x[5] === 1) return true; // 64:ff9b:1::/48, local-use: it can translate to anything
93
+ if (x.slice(4, 12).every((v) => v === 0)) return v4at(12); // 64:ff9b::/96, the well-known prefix
94
+ }
95
+ if (x[0] === 0x20 && x[1] === 0x02) return v4at(2); // 2002::/16, 6to4
96
+ if (x[0] === 0x20 && x[1] === 0x01 && x[2] === 0 && x[3] === 0) return true; // 2001::/32, Teredo
97
+ return (x[0] & 0xfe) === 0xfc || (x[0] === 0xfe && (x[1] & 0xc0) === 0x80) || (x[0] === 0xfe && (x[1] & 0xc0) === 0xc0) || x[0] === 0xff; // fc00::/7, fe80::/10, fec0::/10, ff00::/8
87
98
  }
88
99
 
89
100
  /**
@@ -202,11 +213,28 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
202
213
  };
203
214
  const addresses = { ...ADDRESSES, ...(env.PRIORS_STOCK_VAULT ? { stockVault: env.PRIORS_STOCK_VAULT } : {}), ...(deps.addresses || {}) };
204
215
 
205
- // Everything returned passes through here: the key (with or without 0x, any case) and a private RPC URL are cut.
216
+ // Everything returned passes through here. The key is cut with or without 0x, in any case, and with separators between
217
+ // its digits (spaced, split over lines, dashed, JSON-quoted chunks). A private RPC URL is cut whole and by its parts
218
+ // (the host, long path segments, query values, credentials), in any case, each also when percent-encoded.
206
219
  const secrets = [];
207
- if (rawKey) { const h = rawKey.replace(/^0x/i, ""); if (h.length >= 16) secrets.push(new RegExp(`(0x)?${h.replace(/[^0-9a-zA-Z]/g, "")}`, "gi")); }
208
- if (env.PRIORS_RPC && env.PRIORS_RPC !== X.robinhood.rpcUrl) secrets.push(new RegExp(env.PRIORS_RPC.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"));
209
- const redact = (s) => secrets.reduce((acc, re) => acc.replace(re, (m) => (m.startsWith("http") ? "<rpc>" : "<redacted>")), String(s));
220
+ if (rawKey) {
221
+ const h = rawKey.replace(/^0x/i, "").replace(/[^0-9a-zA-Z]/g, "");
222
+ if (h.length >= 16) secrets.push(new RegExp(`(0x)?${[...h].join("[\\s\"'+,\\-]{0,3}")}`, "gi"));
223
+ }
224
+ if (env.PRIORS_RPC && env.PRIORS_RPC !== X.robinhood.rpcUrl) {
225
+ const parts = [env.PRIORS_RPC];
226
+ try {
227
+ const u = new URL(env.PRIORS_RPC);
228
+ parts.push(u.href, u.host, u.username, u.password);
229
+ for (const seg of u.pathname.split("/")) if (seg.length >= 8) parts.push(seg, decodeURIComponent(seg));
230
+ for (const v of u.searchParams.values()) if (v.length >= 8) parts.push(v);
231
+ } catch (_) { /* not a URL: the literal is still cut */ }
232
+ // each character that is not a letter or a digit may also appear percent-encoded
233
+ const pattern = (p) => [...p].map((ch) => (/[0-9a-z]/i.test(ch) ? ch : `(?:${ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}|%${ch.charCodeAt(0).toString(16).padStart(2, "0")})`)).join("");
234
+ const uniq = [...new Set(parts.filter((p) => p && p.length >= 6))].sort((a, b) => b.length - a.length);
235
+ if (uniq.length) secrets.push(new RegExp(uniq.map(pattern).join("|"), "gi"));
236
+ }
237
+ const redact = (s) => secrets.reduce((acc, re) => acc.replace(re, (m) => (/^http/i.test(m) ? "<rpc>" : "<redacted>")), String(s));
210
238
 
211
239
  // One call per request: ethers batches parallel reads up to 100 calls, and the public node (the default PRIORS_RPC)
212
240
  // answers a batch that size with HTTP 429, which ethers retries until its 5-minute timeout (stock_assets' ~140 reads).
@@ -310,7 +338,9 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
310
338
  let json = false; try { JSON.parse(body); json = true; } catch (_) { /* text */ }
311
339
  init.body = body; init.headers = { "content-type": json ? "application/json" : "text/plain; charset=utf-8" };
312
340
  }
313
- const purchase = `${method} ${u.href}`;
341
+ const target = new URL(u.href);
342
+ target.hash = ""; // a fragment never reaches the merchant: url#a and url#b are the same purchase
343
+ const purchase = `${method} ${target.href}`;
314
344
  const now = Math.floor(Date.now() / 1000);
315
345
  for (const [k, v] of outstanding) if (v.validBefore <= now) outstanding.delete(k);
316
346
  const lines = [];
@@ -328,7 +358,18 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
328
358
  if (maxBorrow > 0n) { agentId = await resolveAgent(); await needController(agentId); }
329
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 } : {}) });
330
360
  try { r = await payer.pay(url, init); } catch (e) {
331
- if (e?.name === "TimeoutError" || e?.name === "AbortError") throw new ToolError(`${method} ${u.href} did not answer in time. Nothing was signed or paid.`);
361
+ // What the error carries was done: a loan taken and a payment signed are counted, whatever failed after.
362
+ if (e?.borrowed > 0n) session.borrowed += e.borrowed;
363
+ 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);
368
+ 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
+ }
370
+ 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.` : "";
371
+ if (e?.name === "TimeoutError" || e?.name === "AbortError") throw new ToolError(`${method} ${u.href} did not answer in time. Nothing was signed or paid.${loan}`);
372
+ if (loan) throw new ToolError(`${explain(e)}.${loan}`);
332
373
  throw e;
333
374
  }
334
375
  if (r.signed) {
@@ -339,7 +380,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
339
380
  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.`); }
340
381
  else if (r.requirement) lines.push("Nothing was borrowed.");
341
382
  }
342
- const status = r.timedOut ? "no answer in time" : `HTTP ${r.response.status}`;
383
+ const status = r.timedOut ? "no answer in time" : r.transportError ? "the connection was lost" : `HTTP ${r.response.status}`;
343
384
  if (!r.requirement) lines.unshift(`No payment was asked for: ${method} ${u.href} answered ${status}. Nothing was paid.`);
344
385
  else if (r.paid > 0n) {
345
386
  outstanding.delete(purchase);
@@ -542,7 +583,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
542
583
  if (hits.length === 0) return q ? `No registered service matches "${clean(q, 100)}" (${list.length} registered in all).` : "No services are registered with the facilitator yet.";
543
584
  const vol = (v) => (/^\d+$/.test(String(v ?? "")) ? usd(BigInt(v)) : clean(v ?? "0", 30));
544
585
  const httpsUrl = (v) => { try { const x = new URL(String(v)); return x.protocol === "https:" ? oneLine(x.href, 200) : "no https url"; } catch (_) { return "no url"; } };
545
- const rows = hits.slice(0, 25).map((m) => `- ${oneLine(m.name || "(unnamed)", 60)} — ${httpsUrl(m.url)}\n ${oneLine(m.description || "", 280)}\n pays to ${ethers.isAddress(String(m.payTo ?? "")) ? ethers.getAddress(m.payTo) : "?"}; ${Number.isFinite(Number(m.settled?.count)) ? Number(m.settled.count) : 0} payments settled, ${oneLine(vol(m.settled?.volume), 40)}`);
586
+ const rows = hits.slice(0, 25).map((m) => `- ${oneLine(m.name || "(unnamed)", 60)} — ${httpsUrl(m.url)}\n ${oneLine(m.description || "", 280)}\n pays to ${ethers.isAddress(String(m.payTo ?? "")) ? ethers.getAddress(m.payTo) : "?"}; ${Number.isFinite(Number(m.settled?.count)) ? Number(m.settled.count) : 0} payments settled, ${oneLine(vol(m.settled?.volume), 40)}; ${m.approved === true ? "approved by Priors" : "self-registered, not reviewed by Priors"}`);
546
587
  return `${hits.length} service${hits.length === 1 ? "" : "s"}${q ? ` matching "${oneLine(q, 100)}"` : ""}${hits.length > 25 ? " (first 25 shown)" : ""}. Names, links and descriptions are the merchants' own words:\n${fenced(rows.join("\n"), "merchant listings")}\nPay one with pay_url.`;
547
588
  });
548
589