@paywithtender/mcp 0.0.0-stage → 0.1.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
@@ -1,3 +1,68 @@
1
- # Temporary Holding Version
1
+ # @paywithtender/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An MCP server that lets any AI agent pay x402 APIs on Robinhood Chain with whatever token it holds. Tender swaps the token to USDG on Uniswap inside the payment, so the API always receives the exact price, in one transaction.
4
+
5
+ Works with Claude Desktop, Claude Code, Cursor, and any other MCP client.
6
+
7
+ ## Tools
8
+
9
+ | Tool | What it does |
10
+ | --- | --- |
11
+ | `check_coin` | Whether a token is spendable on Tender, and what paying $1.00 costs in it |
12
+ | `quote` | The cost and fees of paying a given dollar amount in a given token |
13
+ | `wallet` | The agent's address, balances, and the spending limits left today |
14
+ | `pay` | Calls an API. If it answers `402 Payment Required`, pays with the agent's token and returns the response |
15
+
16
+ `pay` only spends when an API asks for payment, and never above your limits.
17
+
18
+ ## Setup
19
+
20
+ Add this to your MCP client's config (for Claude Desktop, `claude_desktop_config.json`):
21
+
22
+ ```json
23
+ {
24
+ "mcpServers": {
25
+ "tender": {
26
+ "command": "npx",
27
+ "args": ["-y", "@paywithtender/mcp"],
28
+ "env": {
29
+ "TENDER_PRIVATE_KEY": "0xYOUR_AGENT_WALLET_KEY",
30
+ "TENDER_PAY_WITH": "0xTOKEN_THE_AGENT_HOLDS",
31
+ "TENDER_MAX_PER_CALL_USD": "0.50",
32
+ "TENDER_DAILY_LIMIT_USD": "5"
33
+ }
34
+ }
35
+ }
36
+ }
37
+ ```
38
+
39
+ Use a dedicated agent wallet holding only what you're happy for the agent to spend. The key stays on your machine: payments are signed locally and only the signature is sent.
40
+
41
+ Leave out `TENDER_PRIVATE_KEY` to run read-only (`check_coin` and `quote` only).
42
+
43
+ ## Settings
44
+
45
+ | Variable | Default | |
46
+ | --- | --- | --- |
47
+ | `TENDER_PRIVATE_KEY` | none | Agent wallet key. Without it the server is read-only. |
48
+ | `TENDER_PAY_WITH` | USDG | Token to pay with. Any token with a Uniswap route to USDG works. |
49
+ | `TENDER_MAX_PER_CALL_USD` | `1` | Refuse any API priced above this. |
50
+ | `TENDER_MAX_FEE_USD` | `0.10` | Refuse if Tender's fee plus gas is above this. |
51
+ | `TENDER_DAILY_LIMIT_USD` | `10` | Total the agent may spend per UTC day (resets when the server restarts). |
52
+ | `TENDER_RPC_URL` | Robinhood Chain public RPC | |
53
+ | `TENDER_FACILITATOR` | `https://facilitator.paywithtender.com` | |
54
+
55
+ ## Fees
56
+
57
+ - Paying in USDG: network gas only
58
+ - Paying in any other token: 0.5% + gas
59
+ - Paying in $TENDER: gas only
60
+
61
+ The first payment with a new token needs a one-time Permit2 approval. If the agent wallet has no ETH, Tender covers the gas for it.
62
+
63
+ ## Links
64
+
65
+ - Website: https://paywithtender.com
66
+ - Is your coin spendable? https://paywithtender.com/check
67
+ - Source: https://github.com/paywithtender/tender
68
+ - SDK for APIs and agents: [`@paywithtender/sdk`](https://www.npmjs.com/package/@paywithtender/sdk)
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { configFromEnv, createTenderMcp, VERSION } from "./server.js";
4
+ const { server, account } = createTenderMcp(configFromEnv());
5
+ await server.connect(new StdioServerTransport());
6
+ // stdout carries the protocol, so status goes to stderr
7
+ console.error(`tender-mcp ${VERSION} ready${account ? ` (agent wallet ${account.address})` : " (read-only: no TENDER_PRIVATE_KEY set)"}`);
@@ -0,0 +1,43 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { type Address, type Hex } from "viem";
3
+ export declare const VERSION = "0.1.0";
4
+ export interface TenderMcpConfig {
5
+ /** Agent wallet key. Without it, only the read-only tools work. */
6
+ privateKey?: Hex;
7
+ /** Default token to pay with. Omit to pay in USDG. */
8
+ payWith?: Address;
9
+ chainId: number;
10
+ rpcUrl: string;
11
+ facilitator: string;
12
+ usdg: Address;
13
+ permit2: Address;
14
+ /** Spending limits, in USDG atomic units (6 decimals). */
15
+ maxPerCall: bigint;
16
+ maxFeePerCall: bigint;
17
+ dailyLimit: bigint;
18
+ /** Allow paying plain-http URLs (local testing only). */
19
+ allowHttp: boolean;
20
+ explorer?: string;
21
+ }
22
+ export declare function configFromEnv(env?: NodeJS.ProcessEnv): TenderMcpConfig;
23
+ export declare function createTenderMcp(cfg: TenderMcpConfig): {
24
+ server: McpServer;
25
+ account: {
26
+ address: Address;
27
+ nonceManager?: import("viem").NonceManager | undefined;
28
+ sign: (parameters: {
29
+ hash: import("viem").Hash;
30
+ }) => Promise<Hex>;
31
+ signAuthorization: (parameters: import("viem").AuthorizationRequest) => Promise<import("viem/accounts").SignAuthorizationReturnType>;
32
+ signMessage: ({ message }: {
33
+ message: import("viem").SignableMessage;
34
+ }) => Promise<Hex>;
35
+ signTransaction: <serializer extends import("viem").SerializeTransactionFn<import("viem").TransactionSerializable> = import("viem").SerializeTransactionFn<import("viem").TransactionSerializable>, transaction extends Parameters<serializer>[0] = Parameters<serializer>[0]>(transaction: transaction, options?: {
36
+ serializer?: serializer | undefined;
37
+ } | undefined) => Promise<Hex>;
38
+ signTypedData: <const typedData extends import("viem").TypedData | Record<string, unknown>, primaryType extends keyof typedData | "EIP712Domain" = keyof typedData>(parameters: import("viem").TypedDataDefinition<typedData, primaryType>) => Promise<Hex>;
39
+ publicKey: Hex;
40
+ source: "privateKey";
41
+ type: "local";
42
+ } | undefined;
43
+ };
package/dist/server.js ADDED
@@ -0,0 +1,342 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import { createPublicClient, createWalletClient, defineChain, erc20Abi, formatUnits, getAddress, http, isAddress, } from "viem";
4
+ import { privateKeyToAccount } from "viem/accounts";
5
+ import { HEADER_PAYMENT, HEADER_REQUIRED, HEADER_RESPONSE, ROBINHOOD, SCHEME_SWAP, buildPayment, decodeHeader, encodeHeader, ensurePermit2Approval, } from "@paywithtender/sdk";
6
+ export const VERSION = "0.1.0";
7
+ const USD = 1000000n;
8
+ function usdUnits(v, fallback) {
9
+ const s = (v ?? fallback).replace("$", "").trim();
10
+ if (!/^\d+(\.\d+)?$/.test(s))
11
+ throw new Error(`not a dollar amount: ${v}`);
12
+ const [w, f = ""] = s.split(".");
13
+ return BigInt(w) * USD + BigInt((f + "000000").slice(0, 6));
14
+ }
15
+ export function configFromEnv(env = process.env) {
16
+ const key = env.TENDER_PRIVATE_KEY?.trim();
17
+ if (key && !/^0x[0-9a-fA-F]{64}$/.test(key))
18
+ throw new Error("TENDER_PRIVATE_KEY must be a 0x-prefixed 32-byte hex key");
19
+ const payWith = env.TENDER_PAY_WITH?.trim();
20
+ if (payWith && !isAddress(payWith))
21
+ throw new Error("TENDER_PAY_WITH must be a token address");
22
+ const chainId = Number(env.TENDER_CHAIN_ID ?? ROBINHOOD.chainId);
23
+ return {
24
+ privateKey: key,
25
+ payWith: payWith ? getAddress(payWith) : undefined,
26
+ chainId,
27
+ rpcUrl: env.TENDER_RPC_URL ?? "https://rpc.mainnet.chain.robinhood.com",
28
+ facilitator: (env.TENDER_FACILITATOR ?? "https://facilitator.paywithtender.com").replace(/\/$/, ""),
29
+ usdg: getAddress(env.TENDER_USDG ?? ROBINHOOD.usdg),
30
+ permit2: getAddress(env.TENDER_PERMIT2 ?? ROBINHOOD.permit2),
31
+ maxPerCall: usdUnits(env.TENDER_MAX_PER_CALL_USD, "1"),
32
+ maxFeePerCall: usdUnits(env.TENDER_MAX_FEE_USD, "0.10"),
33
+ dailyLimit: usdUnits(env.TENDER_DAILY_LIMIT_USD, "10"),
34
+ allowHttp: env.TENDER_ALLOW_HTTP === "true",
35
+ explorer: chainId === ROBINHOOD.chainId ? "https://robinhoodchain.blockscout.com" : undefined,
36
+ };
37
+ }
38
+ /** Human-friendly amount: whole numbers for big values, a few significant digits for small ones. */
39
+ function amt(raw, decimals) {
40
+ const n = Number(formatUnits(raw, decimals));
41
+ if (n === 0)
42
+ return "0";
43
+ if (n >= 1000)
44
+ return Math.round(n).toLocaleString("en-US");
45
+ if (n >= 1)
46
+ return n.toLocaleString("en-US", { maximumFractionDigits: 4 });
47
+ return Number(n.toPrecision(4)).toString();
48
+ }
49
+ const money = (units) => {
50
+ const n = Number(formatUnits(units, 6));
51
+ return "$" + (n >= 1 ? n.toFixed(2) : Number(n.toPrecision(3)).toString());
52
+ };
53
+ const text = (t, structured) => ({
54
+ content: [{ type: "text", text: t }],
55
+ ...(structured ? { structuredContent: structured } : {}),
56
+ });
57
+ const fail = (t) => ({ content: [{ type: "text", text: t }], isError: true });
58
+ export function createTenderMcp(cfg) {
59
+ const chain = defineChain({
60
+ id: cfg.chainId,
61
+ name: cfg.chainId === ROBINHOOD.chainId ? "Robinhood Chain" : `chain ${cfg.chainId}`,
62
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
63
+ rpcUrls: { default: { http: [cfg.rpcUrl] } },
64
+ });
65
+ const pc = createPublicClient({ chain, transport: http(cfg.rpcUrl) });
66
+ const account = cfg.privateKey ? privateKeyToAccount(cfg.privateKey) : undefined;
67
+ 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;
71
+ const spent = () => {
72
+ const d = new Date().toISOString().slice(0, 10);
73
+ if (d !== day)
74
+ [day, spentToday] = [d, 0n];
75
+ return spentToday;
76
+ };
77
+ const tokenCache = new Map();
78
+ async function token(addr) {
79
+ const k = addr.toLowerCase();
80
+ if (tokenCache.has(k))
81
+ return tokenCache.get(k);
82
+ const code = await pc.getCode({ address: addr });
83
+ if (!code || code === "0x")
84
+ throw new Error(`no token contract at ${addr}`);
85
+ const [symbol, name, decimals] = await Promise.all([
86
+ pc.readContract({ address: addr, abi: erc20Abi, functionName: "symbol" }).catch(() => "?"),
87
+ pc.readContract({ address: addr, abi: erc20Abi, functionName: "name" }).catch(() => "Unknown token"),
88
+ pc.readContract({ address: addr, abi: erc20Abi, functionName: "decimals" }),
89
+ ]);
90
+ const info = { symbol, name, decimals: Number(decimals) };
91
+ tokenCache.set(k, info);
92
+ return info;
93
+ }
94
+ async function quote(tokenIn, amount) {
95
+ const r = await fetch(`${cfg.facilitator}/quote`, {
96
+ method: "POST",
97
+ headers: { "content-type": "application/json" },
98
+ body: JSON.stringify({ tokenIn, amount: amount.toString() }),
99
+ });
100
+ const j = (await r.json());
101
+ return r.ok ? { ok: true, q: j } : { ok: false, reason: j.error ?? `HTTP ${r.status}` };
102
+ }
103
+ const noRoute = (reason) => /noroute|no route|liquidity/i.test(reason);
104
+ const server = new McpServer({ name: "tender", version: VERSION }, {
105
+ instructions: "Tender lets you pay x402 APIs on Robinhood Chain with any token the wallet holds; the API always receives exact USDG. " +
106
+ "Use check_coin to see if a token is spendable, quote to price a payment, wallet to see balances and limits, and pay to call a paid API. " +
107
+ "pay only spends when the API answers 402 Payment Required, and never above the configured limits.",
108
+ });
109
+ // ------------------------------------------------------------------ check_coin
110
+ server.registerTool("check_coin", {
111
+ title: "Check if a coin is spendable",
112
+ description: "Checks whether a Robinhood Chain token can be used to pay on Tender (it needs a Uniswap route to USDG), and what paying $1.00 costs in it.",
113
+ inputSchema: { token: z.string().describe("Token contract address (0x…)") },
114
+ annotations: { readOnlyHint: true, openWorldHint: true },
115
+ }, async ({ token: t }) => {
116
+ if (!isAddress(t))
117
+ return fail("That isn't a token address.");
118
+ const addr = getAddress(t);
119
+ let info;
120
+ try {
121
+ info = await token(addr);
122
+ }
123
+ catch (e) {
124
+ return fail(e.message);
125
+ }
126
+ const r = await quote(addr, USD);
127
+ if (!r.ok) {
128
+ if (noRoute(r.reason)) {
129
+ return text(`${info.symbol} (${info.name}) is not spendable on Tender yet: there is no Uniswap pool deep enough to swap it into USDG. Pons coins become spendable automatically when they graduate.`, { token: addr, symbol: info.symbol, spendable: false, reason: "no_route" });
130
+ }
131
+ return fail(`Couldn't get a quote: ${r.reason}`);
132
+ }
133
+ const q = r.q;
134
+ const amountIn = formatUnits(BigInt(q.estimatedAmountIn), info.decimals);
135
+ const shown = amt(BigInt(q.estimatedAmountIn), info.decimals);
136
+ const protocol = BigInt(q.feeBreakdown.protocol);
137
+ const gas = BigInt(q.feeBreakdown.gas);
138
+ return text(`${info.symbol} (${info.name}) is spendable on Tender. Paying a $1.00 API costs about ${shown} ${info.symbol}: ` +
139
+ `Tender fee ${protocol === 0n ? "none" : money(protocol)}, network gas ${money(gas)}` +
140
+ (q.priceImpact ? `, swap price impact ${(q.priceImpact * 100).toFixed(2)}%` : "") +
141
+ ". The API receives exactly $1.00 USDG.", {
142
+ token: addr,
143
+ symbol: info.symbol,
144
+ spendable: true,
145
+ costFor1Usd: amountIn,
146
+ tenderFeeUsd: formatUnits(protocol, 6),
147
+ gasFeeUsd: formatUnits(gas, 6),
148
+ priceImpact: q.priceImpact ?? 0,
149
+ });
150
+ });
151
+ // ------------------------------------------------------------------ quote
152
+ server.registerTool("quote", {
153
+ title: "Quote a payment",
154
+ description: "Prices a payment of a given USD amount in a given token (default: the configured pay-with token, or USDG).",
155
+ inputSchema: {
156
+ usd: z.string().describe('Amount the API should receive, in dollars, e.g. "0.05"'),
157
+ token: z.string().optional().describe("Token to pay with (0x…). Omit for the default."),
158
+ },
159
+ annotations: { readOnlyHint: true, openWorldHint: true },
160
+ }, async ({ usd, token: t }) => {
161
+ let amount;
162
+ try {
163
+ amount = usdUnits(usd, "0");
164
+ }
165
+ catch (e) {
166
+ return fail(e.message);
167
+ }
168
+ if (amount === 0n)
169
+ return fail("Amount must be above zero.");
170
+ const addr = t ? (isAddress(t) ? getAddress(t) : null) : (cfg.payWith ?? cfg.usdg);
171
+ if (!addr)
172
+ return fail("That isn't a token address.");
173
+ let info;
174
+ try {
175
+ info = await token(addr);
176
+ }
177
+ catch (e) {
178
+ return fail(e.message);
179
+ }
180
+ const r = await quote(addr, amount);
181
+ if (!r.ok)
182
+ return fail(noRoute(r.reason) ? `${info.symbol} isn't spendable on Tender yet (no Uniswap route to USDG).` : `Couldn't get a quote: ${r.reason}`);
183
+ const q = r.q;
184
+ return text(`To pay ${money(amount)} in ${info.symbol}: about ${amt(BigInt(q.estimatedAmountIn), info.decimals)} ${info.symbol} ` +
185
+ `(at most ${amt(BigInt(q.maxAmountIn), info.decimals)} with slippage). Fees: Tender ${money(BigInt(q.feeBreakdown.protocol))}, gas ${money(BigInt(q.feeBreakdown.gas))}.`, {
186
+ token: addr,
187
+ symbol: info.symbol,
188
+ usd: formatUnits(amount, 6),
189
+ estimatedAmountIn: formatUnits(BigInt(q.estimatedAmountIn), info.decimals),
190
+ maxAmountIn: formatUnits(BigInt(q.maxAmountIn), info.decimals),
191
+ tenderFeeUsd: formatUnits(BigInt(q.feeBreakdown.protocol), 6),
192
+ gasFeeUsd: formatUnits(BigInt(q.feeBreakdown.gas), 6),
193
+ });
194
+ });
195
+ // ------------------------------------------------------------------ wallet
196
+ server.registerTool("wallet", {
197
+ title: "Agent wallet and limits",
198
+ description: "Shows the agent wallet address, its ETH, USDG and pay-with token balances, and the spending limits left today.",
199
+ inputSchema: {},
200
+ annotations: { readOnlyHint: true },
201
+ }, async () => {
202
+ if (!account)
203
+ return fail("No wallet configured. Set TENDER_PRIVATE_KEY to let this agent pay.");
204
+ const [eth, usdgBal] = await Promise.all([
205
+ pc.getBalance({ address: account.address }),
206
+ pc.readContract({ address: cfg.usdg, abi: erc20Abi, functionName: "balanceOf", args: [account.address] }),
207
+ ]);
208
+ const lines = [`Address: ${account.address}`, `ETH: ${amt(eth, 18)}`, `USDG: ${amt(usdgBal, 6)}`];
209
+ const structured = { address: account.address, eth: formatUnits(eth, 18), usdg: formatUnits(usdgBal, 6) };
210
+ if (cfg.payWith && cfg.payWith.toLowerCase() !== cfg.usdg.toLowerCase()) {
211
+ const info = await token(cfg.payWith);
212
+ const [bal, allowance] = await Promise.all([
213
+ pc.readContract({ address: cfg.payWith, abi: erc20Abi, functionName: "balanceOf", args: [account.address] }),
214
+ pc.readContract({ address: cfg.payWith, abi: erc20Abi, functionName: "allowance", args: [account.address, cfg.permit2] }),
215
+ ]);
216
+ lines.push(`Pays with ${info.symbol}: ${amt(bal, info.decimals)} (${allowance > 0n ? "ready" : "one-time approval happens on first payment"})`);
217
+ Object.assign(structured, { payWith: info.symbol, payWithBalance: formatUnits(bal, info.decimals) });
218
+ }
219
+ else {
220
+ lines.push("Pays with: USDG");
221
+ }
222
+ const left = cfg.dailyLimit - spent();
223
+ lines.push(`Limits: ${money(cfg.maxPerCall)} per call, ${money(cfg.maxFeePerCall)} max fee, ${money(left < 0n ? 0n : left)} of ${money(cfg.dailyLimit)} left today`);
224
+ Object.assign(structured, { spentTodayUsd: formatUnits(spent(), 6), dailyLimitUsd: formatUnits(cfg.dailyLimit, 6) });
225
+ return text(lines.join("\n"), structured);
226
+ });
227
+ // ------------------------------------------------------------------ pay
228
+ server.registerTool("pay", {
229
+ title: "Call a paid API",
230
+ description: "Calls an x402 API. If it answers 402 Payment Required with a Tender option, pays with the agent's token (swapped to USDG on Uniswap in the same transaction) and returns the API's response. " +
231
+ "Free endpoints are just fetched. Refuses anything above the configured per-call, fee or daily limits.",
232
+ inputSchema: {
233
+ url: z.string().describe("Full URL of the API endpoint"),
234
+ method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).optional().describe("HTTP method, default GET"),
235
+ body: z.string().optional().describe("Request body (sent as-is; set content-type in headers if needed)"),
236
+ headers: z.record(z.string(), z.string()).optional().describe("Extra request headers"),
237
+ pay_with: z.string().optional().describe("Token to pay with for this call (0x…). Omit for the default."),
238
+ max_usd: z.string().optional().describe("Refuse if the API's price is above this many dollars (lower than the configured limit)"),
239
+ },
240
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
241
+ }, async ({ url, method, body, headers, pay_with, max_usd }) => {
242
+ let target;
243
+ try {
244
+ target = new URL(url);
245
+ }
246
+ catch {
247
+ return fail("That isn't a valid URL.");
248
+ }
249
+ if (target.protocol !== "https:" && !(cfg.allowHttp && target.protocol === "http:"))
250
+ return fail("Only https URLs can be paid.");
251
+ if (!account || !wallet)
252
+ return fail("No wallet configured. Set TENDER_PRIVATE_KEY to let this agent pay.");
253
+ const payWith = pay_with ? (isAddress(pay_with) ? getAddress(pay_with) : null) : cfg.payWith;
254
+ if (payWith === null)
255
+ return fail("pay_with isn't a token address.");
256
+ let cap = cfg.maxPerCall;
257
+ if (max_usd) {
258
+ try {
259
+ const m = usdUnits(max_usd, "0");
260
+ if (m < cap)
261
+ cap = m;
262
+ }
263
+ catch (e) {
264
+ return fail(e.message);
265
+ }
266
+ }
267
+ const init = { method: method ?? "GET", headers: headers ?? {}, body };
268
+ const first = await fetch(target, init);
269
+ if (first.status !== 402)
270
+ return respond(first, null);
271
+ let required;
272
+ try {
273
+ const h = first.headers.get(HEADER_REQUIRED);
274
+ required = h ? decodeHeader(h) : (await first.json());
275
+ }
276
+ catch {
277
+ return fail("The API asked for payment but its payment details couldn't be read.");
278
+ }
279
+ const opt = required.accepts?.find((a) => a.scheme === SCHEME_SWAP && a.network === `eip155:${cfg.chainId}`);
280
+ if (!opt)
281
+ return fail("This API doesn't accept Tender payments on this chain.");
282
+ const price = BigInt(opt.amount);
283
+ if (price > cap)
284
+ 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.`);
287
+ }
288
+ const tokenIn = payWith ?? cfg.usdg;
289
+ const extra = (opt.extra ?? {});
290
+ try {
291
+ await ensurePermit2Approval({
292
+ wallet,
293
+ publicClient: pc,
294
+ token: tokenIn,
295
+ permit2: extra.permit2 ?? cfg.permit2,
296
+ facilitator: extra.facilitator ?? cfg.facilitator,
297
+ });
298
+ }
299
+ catch (e) {
300
+ return fail(`One-time token approval failed: ${e.shortMessage ?? e.message}. Nothing was paid.`);
301
+ }
302
+ let payload;
303
+ try {
304
+ payload = await buildPayment(pc, { account, chain, rpcUrl: cfg.rpcUrl, payWith: payWith ?? undefined, maxUsdgPerCall: cap, maxFeePerCall: cfg.maxFeePerCall }, required, cap);
305
+ }
306
+ catch (e) {
307
+ return fail(`Couldn't prepare the payment: ${e.message}. Nothing was paid.`);
308
+ }
309
+ const h = new Headers(init.headers);
310
+ h.set(HEADER_PAYMENT, encodeHeader(payload));
311
+ const paid = await fetch(target, { ...init, headers: h });
312
+ const settleHeader = paid.headers.get(HEADER_RESPONSE);
313
+ const settle = settleHeader ? decodeHeader(settleHeader) : null;
314
+ if (settle?.success)
315
+ spentToday = spent() + price;
316
+ return respond(paid, settle ? { ...settle, price, tokenIn } : null);
317
+ });
318
+ async function respond(res, payment) {
319
+ const raw = await res.text();
320
+ const shown = raw.length > 8000 ? raw.slice(0, 8000) + `\n… (${raw.length - 8000} more characters)` : raw;
321
+ const lines = [`HTTP ${res.status}`];
322
+ const structured = { status: res.status };
323
+ if (payment?.success) {
324
+ const sym = (await token(payment.tokenIn).catch(() => null))?.symbol ?? payment.tokenIn;
325
+ const link = cfg.explorer && payment.transaction ? `${cfg.explorer}/tx/${payment.transaction}` : payment.transaction;
326
+ lines.push(`Paid ${money(payment.price)} in ${sym} via Tender. Transaction: ${link}`);
327
+ Object.assign(structured, { paid: true, priceUsd: formatUnits(payment.price, 6), paidWith: sym, transaction: payment.transaction });
328
+ }
329
+ else if (payment) {
330
+ lines.push(`Payment did not settle: ${payment.errorReason ?? "unknown reason"}`);
331
+ structured.paid = false;
332
+ }
333
+ else if (res.status === 402) {
334
+ lines.push("The API still asks for payment; it was refused.");
335
+ structured.paid = false;
336
+ }
337
+ lines.push("", shown);
338
+ structured.body = shown;
339
+ return { content: [{ type: "text", text: lines.join("\n") }], structuredContent: structured, isError: res.status >= 400 };
340
+ }
341
+ return { server, account };
342
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@paywithtender/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "MCP server that lets any AI agent pay x402 APIs with any token on Robinhood Chain, through Tender.",
5
+ "license": "MIT",
6
+ "homepage": "https://paywithtender.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/paywithtender/tender.git",
10
+ "directory": "packages/mcp"
11
+ },
12
+ "keywords": [
13
+ "mcp",
14
+ "model-context-protocol",
15
+ "x402",
16
+ "robinhood-chain",
17
+ "payments",
18
+ "usdg",
19
+ "ai-agents",
20
+ "tender"
21
+ ],
22
+ "type": "module",
23
+ "main": "./dist/server.js",
24
+ "types": "./dist/server.d.ts",
25
+ "bin": {
26
+ "tender-mcp": "./dist/cli.js"
27
+ },
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/server.d.ts",
31
+ "import": "./dist/server.js",
32
+ "default": "./dist/server.js"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md"
38
+ ],
39
+ "engines": {
40
+ "node": ">=20"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc -p tsconfig.json"
44
+ },
45
+ "dependencies": {
46
+ "@modelcontextprotocol/sdk": "^1.32.2",
47
+ "@paywithtender/sdk": "^0.1.1",
48
+ "viem": "^2.21.0",
49
+ "zod": "^4.1.0"
50
+ },
51
+ "devDependencies": {
52
+ "typescript": "^5.6.0",
53
+ "@types/node": "^22.0.0"
54
+ }
55
+ }