@paywithtender/mcp 0.1.1 → 0.1.2

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
@@ -56,7 +56,8 @@ It costs $0.01 plus gas, in whatever token you set as `TENDER_PAY_WITH`.
56
56
  | `TENDER_PAY_WITH` | USDG | Token to pay with. Any token with a Uniswap route to USDG works. |
57
57
  | `TENDER_MAX_PER_CALL_USD` | `1` | Refuse any API priced above this. |
58
58
  | `TENDER_MAX_FEE_USD` | `0.10` | Refuse if Tender's fee plus gas is above this. |
59
- | `TENDER_DAILY_LIMIT_USD` | `10` | Total the agent may spend per UTC day (resets when the server restarts). |
59
+ | `TENDER_DAILY_LIMIT_USD` | `10` | Total the agent may spend per UTC day. The running total is saved to disk, so restarting the server or the AI app doesn't reset it. |
60
+ | `TENDER_STATE_FILE` | `~/.tender/spend.json` | Where today's spending is kept, per wallet. Set to `none` to keep it in memory only (resets on restart). |
60
61
  | `TENDER_RPC_URL` | Robinhood Chain public RPC | |
61
62
  | `TENDER_FACILITATOR` | `https://facilitator.paywithtender.com` | |
62
63
 
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { type Address, type Hex } from "viem";
3
- export declare const VERSION = "0.1.1";
3
+ export declare const VERSION = "0.1.2";
4
4
  export interface TenderMcpConfig {
5
5
  /** Agent wallet key. Without it, only the read-only tools work. */
6
6
  privateKey?: Hex;
@@ -15,6 +15,8 @@ export interface TenderMcpConfig {
15
15
  maxPerCall: bigint;
16
16
  maxFeePerCall: bigint;
17
17
  dailyLimit: bigint;
18
+ /** File that keeps today's spending per wallet, so restarts don't reset the daily limit. Unset = memory only. */
19
+ stateFile?: string;
18
20
  /** Allow paying plain-http URLs (local testing only). */
19
21
  allowHttp: boolean;
20
22
  explorer?: string;
package/dist/server.js CHANGED
@@ -1,9 +1,12 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
1
4
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
5
  import { z } from "zod";
3
6
  import { createPublicClient, createWalletClient, defineChain, erc20Abi, formatUnits, getAddress, http, isAddress, } from "viem";
4
7
  import { privateKeyToAccount } from "viem/accounts";
5
8
  import { HEADER_PAYMENT, HEADER_REQUIRED, HEADER_RESPONSE, ROBINHOOD, SCHEME_SWAP, buildPayment, decodeHeader, encodeHeader, ensurePermit2Approval, } from "@paywithtender/sdk";
6
- export const VERSION = "0.1.1";
9
+ export const VERSION = "0.1.2";
7
10
  const USD = 1000000n;
8
11
  function usdUnits(v, fallback) {
9
12
  const s = (v ?? fallback).replace("$", "").trim();
@@ -32,6 +35,7 @@ export function configFromEnv(env = process.env) {
32
35
  maxFeePerCall: usdUnits(env.TENDER_MAX_FEE_USD, "0.10"),
33
36
  dailyLimit: usdUnits(env.TENDER_DAILY_LIMIT_USD, "10"),
34
37
  allowHttp: env.TENDER_ALLOW_HTTP === "true",
38
+ stateFile: env.TENDER_STATE_FILE === "none" ? undefined : env.TENDER_STATE_FILE || path.join(os.homedir(), ".tender", "spend.json"),
35
39
  explorer: chainId === ROBINHOOD.chainId ? "https://robinhoodchain.blockscout.com" : undefined,
36
40
  };
37
41
  }
@@ -65,15 +69,49 @@ export function createTenderMcp(cfg) {
65
69
  const pc = createPublicClient({ chain, transport: http(cfg.rpcUrl) });
66
70
  const account = cfg.privateKey ? privateKeyToAccount(cfg.privateKey) : undefined;
67
71
  const wallet = account ? createWalletClient({ chain, transport: http(cfg.rpcUrl), account }) : undefined;
68
- // Spending this process has done in the current UTC day.
69
- let day = new Date().toISOString().slice(0, 10);
70
- let spentToday = 0n;
72
+ // Today's spending, per wallet and UTC day. Kept in cfg.stateFile so restarting the server (or the AI app)
73
+ // can't hand the agent a fresh day's budget, and several server processes share one running total.
74
+ const today = () => new Date().toISOString().slice(0, 10);
75
+ const ledgerKey = account ? `${cfg.chainId}:${account.address.toLowerCase()}` : "";
76
+ let memDay = today();
77
+ let memSpent = 0n;
78
+ function readLedger() {
79
+ try {
80
+ return JSON.parse(fs.readFileSync(cfg.stateFile, "utf8"));
81
+ }
82
+ catch (e) {
83
+ if (e.code === "ENOENT")
84
+ return {};
85
+ throw new Error(`can't read the spending record at ${cfg.stateFile}: ${e.message}`);
86
+ }
87
+ }
71
88
  const spent = () => {
72
- const d = new Date().toISOString().slice(0, 10);
73
- if (d !== day)
74
- [day, spentToday] = [d, 0n];
75
- return spentToday;
89
+ const d = today();
90
+ if (!cfg.stateFile) {
91
+ if (d !== memDay)
92
+ [memDay, memSpent] = [d, 0n];
93
+ return memSpent;
94
+ }
95
+ const e = readLedger()[ledgerKey];
96
+ return e && e.day === d ? BigInt(e.spent) : 0n;
76
97
  };
98
+ function addSpent(delta) {
99
+ const d = today();
100
+ if (!cfg.stateFile) {
101
+ if (d !== memDay)
102
+ [memDay, memSpent] = [d, 0n];
103
+ memSpent = memSpent + delta < 0n ? 0n : memSpent + delta;
104
+ return;
105
+ }
106
+ const all = readLedger();
107
+ const cur = all[ledgerKey]?.day === d ? BigInt(all[ledgerKey].spent) : 0n;
108
+ const next = cur + delta < 0n ? 0n : cur + delta;
109
+ all[ledgerKey] = { day: d, spent: next.toString() };
110
+ fs.mkdirSync(path.dirname(cfg.stateFile), { recursive: true, mode: 0o700 });
111
+ const tmp = `${cfg.stateFile}.${process.pid}.tmp`;
112
+ fs.writeFileSync(tmp, JSON.stringify(all, null, 2), { mode: 0o600 });
113
+ fs.renameSync(tmp, cfg.stateFile);
114
+ }
77
115
  const tokenCache = new Map();
78
116
  async function token(addr) {
79
117
  const k = addr.toLowerCase();
@@ -282,8 +320,15 @@ export function createTenderMcp(cfg) {
282
320
  const price = BigInt(opt.amount);
283
321
  if (price > cap)
284
322
  return fail(`The API wants ${money(price)}, above this agent's limit of ${money(cap)} per call. Nothing was paid.`);
285
- if (spent() + price > cfg.dailyLimit) {
286
- return fail(`Paying ${money(price)} would pass today's limit (${money(spent())} of ${money(cfg.dailyLimit)} used). Nothing was paid.`);
323
+ let used;
324
+ try {
325
+ used = spent();
326
+ }
327
+ catch (e) {
328
+ return fail(`Couldn't check today's spending: ${e.message}. Nothing was paid.`);
329
+ }
330
+ if (used + price > cfg.dailyLimit) {
331
+ return fail(`Paying ${money(price)} would pass today's limit (${money(used)} of ${money(cfg.dailyLimit)} used). Nothing was paid.`);
287
332
  }
288
333
  const tokenIn = payWith ?? cfg.usdg;
289
334
  const extra = (opt.extra ?? {});
@@ -308,11 +353,24 @@ export function createTenderMcp(cfg) {
308
353
  }
309
354
  const h = new Headers(init.headers);
310
355
  h.set(HEADER_PAYMENT, encodeHeader(payload));
311
- const paid = await fetch(target, { ...init, headers: h });
356
+ // count the payment before sending it, so parallel calls and crashes can't overspend; give it back only if it clearly failed
357
+ try {
358
+ addSpent(price);
359
+ }
360
+ catch (e) {
361
+ return fail(`Couldn't record today's spending: ${e.message}. Nothing was paid.`);
362
+ }
363
+ let paid;
364
+ try {
365
+ paid = await fetch(target, { ...init, headers: h });
366
+ }
367
+ catch (e) {
368
+ return fail(`The API couldn't be reached after signing (${e.message}). The payment may or may not have settled, so ${money(price)} stays counted toward today's limit.`);
369
+ }
312
370
  const settleHeader = paid.headers.get(HEADER_RESPONSE);
313
371
  const settle = settleHeader ? decodeHeader(settleHeader) : null;
314
- if (settle?.success)
315
- spentToday = spent() + price;
372
+ if ((settle && !settle.success) || (!settle && paid.status === 402))
373
+ addSpent(-price);
316
374
  return respond(paid, settle ? { ...settle, price, tokenIn } : null);
317
375
  });
318
376
  async function respond(res, payment) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paywithtender/mcp",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "mcpName": "io.github.paywithtender/tender",
5
5
  "description": "MCP server that lets any AI agent pay x402 APIs with any token on Robinhood Chain, through Tender.",
6
6
  "license": "MIT",