autonomo-mcp 0.1.2 → 0.1.4

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 (4) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +114 -91
  3. package/index.mjs +446 -304
  4. package/package.json +46 -45
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Autonomo
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Autonomo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,91 +1,114 @@
1
- # Autonomo MCP server
2
-
3
- Give Claude, Codex, Cursor or any MCP client access to Autonomo's paid APIs. The agent finds an API, checks the
4
- price and pays per call with x402, in USDG or $AUTONOMO on Robinhood Chain. No API keys and no account: just a wallet.
5
-
6
- The server runs on your own computer. Your wallet key stays there and is only used to sign payments.
7
-
8
- ## Tools
9
-
10
- | Tool | What it does | Costs |
11
- | --- | --- | --- |
12
- | `find_apis` | Search Autonomo's APIs (token prices, launches, rug risk, wallets, transactions, page reader). Optionally also the directory of 4K+ x402 projects. | Free |
13
- | `get_price` | Call an API without paying and show its price. | Free |
14
- | `call_api` | Pay for one call and return the answer, with the payment link on Blockscout. | Usually 0.01 USDG or 100 $AUTONOMO |
15
-
16
- ## Setup
17
-
18
- 1. Make a **new wallet just for your agent**, and send it a little USDG (1 USDG is 100 calls) or $AUTONOMO on
19
- Robinhood Chain. Paying in $AUTONOMO needs a little ETH once, for the Permit2 approval.
20
- 2. Add the server to your client (below), with that wallet's private key as `AUTONOMO_WALLET_KEY`.
21
- 3. Ask: "Is token 0x… safe? Use Autonomo."
22
-
23
- Without a key, `find_apis` and `get_price` still work.
24
-
25
- ### Claude Code
26
-
27
- ```bash
28
- claude mcp add autonomo -e AUTONOMO_WALLET_KEY=0xYOUR_AGENT_WALLET_KEY -- npx -y autonomo-mcp
29
- ```
30
-
31
- On Windows, start `npx` through `cmd /c`. In PowerShell, quote the `--`:
32
-
33
- ```powershell
34
- claude mcp add autonomo -e AUTONOMO_WALLET_KEY=0xYOUR_AGENT_WALLET_KEY '--' cmd /c npx -y autonomo-mcp
35
- ```
36
-
37
- ### Claude Desktop, Cursor and others
38
-
39
- Add this to the client's MCP config (`claude_desktop_config.json`, `.cursor/mcp.json`, …):
40
-
41
- ```json
42
- {
43
- "mcpServers": {
44
- "autonomo": {
45
- "command": "npx",
46
- "args": ["-y", "autonomo-mcp"],
47
- "env": { "AUTONOMO_WALLET_KEY": "0xYOUR_AGENT_WALLET_KEY" }
48
- }
49
- }
50
- }
51
- ```
52
-
53
- If the client can't find `npx` on Windows, use `"command": "cmd"` and `"args": ["/c", "npx", "-y", "autonomo-mcp"]`.
54
-
55
- ### Codex
56
-
57
- In `~/.codex/config.toml`:
58
-
59
- ```toml
60
- [mcp_servers.autonomo]
61
- command = "npx"
62
- args = ["-y", "autonomo-mcp"]
63
- env = { AUTONOMO_WALLET_KEY = "0xYOUR_AGENT_WALLET_KEY" }
64
- ```
65
-
66
- ## Settings
67
-
68
- | Env var | Default | Meaning |
69
- | --- | --- | --- |
70
- | `AUTONOMO_WALLET_KEY` | none | Private key of the agent's wallet. Needed only for `call_api`. |
71
- | `AUTONOMO_PAY_WITH` | `usdg` | `usdg` or `autonomo`, the token used when the agent doesn't say. |
72
- | `AUTONOMO_DAILY_USDG` | `1` | Most USDG the server will spend per UTC day. |
73
- | `AUTONOMO_DAILY_AUTONOMO` | `10000` | Most $AUTONOMO the server will spend per UTC day. |
74
- | `AUTONOMO_BASE_URL` | `https://autonomo.fun` | Only for testing against a local copy of the site. |
75
-
76
- ## Safety
77
-
78
- - It only pays Autonomo gateways (`autonomo.fun/x/...`), and only in USDG or $AUTONOMO on Robinhood Chain.
79
- - Each call is capped at 0.05 USDG or 5,000 $AUTONOMO, whatever the API asks.
80
- - The daily budget is tracked in `~/.autonomo-mcp/spend.json`.
81
- - Your MCP client asks before each tool call, so you approve every payment unless you choose to allow it always.
82
- - Use a dedicated wallet with a small balance, never your main wallet.
83
-
84
- ## Develop
85
-
86
- ```bash
87
- npm install
88
- npm run inspect
89
- ```
90
-
91
- `npm run inspect` opens the MCP Inspector so you can try the tools by hand.
1
+ # Autonomo MCP server
2
+
3
+ Give Claude, Codex, Cursor or any MCP client access to Autonomo's paid APIs. The agent finds an API, checks the
4
+ price and pays per call with x402, in USDG or $AUTONOMO on Robinhood Chain, or USDC on Base. No API keys and no
5
+ account: just a wallet.
6
+
7
+ The server runs on your own computer. Your wallet key stays there and is only used to sign payments.
8
+
9
+ ## Tools
10
+
11
+ | Tool | What it does | Costs |
12
+ | --- | --- | --- |
13
+ | `find_apis` | Search Autonomo's APIs (token prices, launches, rug risk, wallets, transactions, page reader). Optionally also the directory of 4K+ x402 projects. | Free |
14
+ | `get_price` | Call an API without paying and show its price. | Free |
15
+ | `wallet_status` | What the wallet holds on both chains, what it has spent today and its limits. Signs nothing. | Free |
16
+ | `call_api` | Pay for one call and return the answer, with the payment link on Blockscout or Basescan. | Usually 0.01 USDG or USDC, or 20% less in $AUTONOMO |
17
+
18
+ ## Setup
19
+
20
+ 1. Make a **new wallet just for your agent**, and send it a little USDG (1 USDG is 100 calls) or $AUTONOMO on
21
+ Robinhood Chain, or USDC on Base. The same wallet works on both chains. Paying in $AUTONOMO needs a little ETH
22
+ once, for the Permit2 approval; USDG and USDC need no ETH.
23
+ 2. Add the server to your client (below), with that wallet's private key as `AUTONOMO_WALLET_KEY`.
24
+ 3. Ask: "Is token 0x… safe? Use Autonomo."
25
+
26
+ Without a key, `find_apis` and `get_price` still work.
27
+
28
+ ### Claude Code
29
+
30
+ ```bash
31
+ claude mcp add autonomo -e AUTONOMO_WALLET_KEY=0xYOUR_AGENT_WALLET_KEY -- npx -y autonomo-mcp
32
+ ```
33
+
34
+ On Windows, start `npx` through `cmd /c`. In PowerShell, quote the `--`:
35
+
36
+ ```powershell
37
+ claude mcp add autonomo -e AUTONOMO_WALLET_KEY=0xYOUR_AGENT_WALLET_KEY '--' cmd /c npx -y autonomo-mcp
38
+ ```
39
+
40
+ ### Cursor
41
+
42
+ **[Add to Cursor](https://cursor.com/install-mcp?name=autonomo&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImF1dG9ub21vLW1jcCJdfQ==)**
43
+
44
+ The link opens Cursor, which asks before it installs anything. It carries no wallet key, so `find_apis` and
45
+ `get_price` work right away. To pay for calls, add the key to the server's entry in `~/.cursor/mcp.json`, as in the
46
+ block below. Keep the key in that file in your home folder, not in a project's `.cursor/mcp.json`, so it can't end
47
+ up in git.
48
+
49
+ ### Cursor by hand, Claude Desktop and others
50
+
51
+ Add this to the client's MCP config (`~/.cursor/mcp.json`, `claude_desktop_config.json`, …):
52
+
53
+ ```json
54
+ {
55
+ "mcpServers": {
56
+ "autonomo": {
57
+ "command": "npx",
58
+ "args": ["-y", "autonomo-mcp"],
59
+ "env": { "AUTONOMO_WALLET_KEY": "0xYOUR_AGENT_WALLET_KEY" }
60
+ }
61
+ }
62
+ }
63
+ ```
64
+
65
+ If the client can't find `npx` on Windows, use `"command": "cmd"` and `"args": ["/c", "npx", "-y", "autonomo-mcp"]`.
66
+
67
+ ### Codex
68
+
69
+ ```bash
70
+ codex mcp add autonomo --env AUTONOMO_WALLET_KEY=0xYOUR_AGENT_WALLET_KEY -- npx -y autonomo-mcp
71
+ ```
72
+
73
+ Or by hand, in `~/.codex/config.toml`:
74
+
75
+ ```toml
76
+ [mcp_servers.autonomo]
77
+ command = "npx"
78
+ args = ["-y", "autonomo-mcp"]
79
+ env = { AUTONOMO_WALLET_KEY = "0xYOUR_AGENT_WALLET_KEY" }
80
+ ```
81
+
82
+ ## Settings
83
+
84
+ | Env var | Default | Meaning |
85
+ | --- | --- | --- |
86
+ | `AUTONOMO_WALLET_KEY` | none | Private key of the agent's wallet. Needed only for `call_api`. |
87
+ | `AUTONOMO_PAY_WITH` | `auto` | The token used when the agent doesn't say. `auto` pays with the first the wallet can afford: USDG, then $AUTONOMO, then USDC on Base. Or name one: `usdg`, `autonomo`, or `usdc` for Base. |
88
+ | `AUTONOMO_MAX_USDG_PER_CALL` | `0.5` | Most one call may cost in USDG or USDC. |
89
+ | `AUTONOMO_MAX_AUTONOMO_PER_CALL` | `5000` | Most one call may cost in $AUTONOMO. |
90
+ | `AUTONOMO_DAILY_USDG` | `5` | Most dollars the server will spend per UTC day, in USDG and USDC on Base together. |
91
+ | `AUTONOMO_DAILY_AUTONOMO` | `10000` | Most $AUTONOMO the server will spend per UTC day. |
92
+ | `AUTONOMO_RPC_URL` | Robinhood Chain's public RPC | Another Robinhood Chain RPC. |
93
+ | `AUTONOMO_BASE_RPC_URL` | `https://mainnet.base.org` | Another Base RPC, for USDC balances. |
94
+ | `AUTONOMO_BASE_URL` | `https://autonomo.fun` | Only for testing against a local copy of the site. |
95
+
96
+ ## Safety
97
+
98
+ - It only pays Autonomo gateways (`autonomo.fun/x/...`), and only in USDG or $AUTONOMO on Robinhood Chain, or USDC on Base.
99
+ - Each call is capped at 0.5 USDG or USDC, or 5,000 $AUTONOMO, whatever the API asks, unless you change the caps
100
+ above. USDG and USDC share one daily dollar budget.
101
+ - It signs only what it checked: the same token, amount and payee as in the price it read. If the API's price or
102
+ payee changes in between, nothing is signed.
103
+ - The daily budget is tracked in `~/.autonomo-mcp/spend.json`.
104
+ - Your MCP client asks before each tool call, so you approve every payment unless you choose to allow it always.
105
+ - Use a dedicated wallet with a small balance, never your main wallet.
106
+
107
+ ## Develop
108
+
109
+ ```bash
110
+ npm install
111
+ npm run inspect
112
+ ```
113
+
114
+ `npm run inspect` opens the MCP Inspector so you can try the tools by hand.
package/index.mjs CHANGED
@@ -1,304 +1,446 @@
1
- #!/usr/bin/env node
2
- // Autonomo MCP server: lets Claude, Codex, Cursor and other MCP clients find Autonomo x402 APIs, check the price
3
- // and pay per call in USDG or $AUTONOMO on Robinhood Chain, from a wallet the user controls.
4
- //
5
- // Tools: find_apis (free), get_price (free), call_api (pays). Runs locally over stdio, so the wallet key never
6
- // leaves this machine except as signed payments. Settings come from env vars (see README.md). Never write to
7
- // stdout here: it carries the MCP protocol, so logs go to stderr.
8
-
9
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
- import { homedir } from "node:os";
11
- import { join } from "node:path";
12
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
13
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
14
- import { createPublicClient, createWalletClient, defineChain, erc20Abi, formatUnits, http, maxUint256, parseUnits } from "viem";
15
- import { privateKeyToAccount } from "viem/accounts";
16
- import { x402Client } from "@x402/core/client";
17
- import { toClientEvmSigner } from "@x402/evm";
18
- import { ExactEvmScheme } from "@x402/evm/exact/client";
19
- import { wrapFetchWithPayment } from "@x402/fetch";
20
- import { z } from "zod";
21
-
22
- const VERSION = "0.1.2";
23
- const BASE = (process.env.AUTONOMO_BASE_URL || "https://autonomo.fun").replace(/\/+$/, "");
24
- const NETWORK = "eip155:4663";
25
- const RPC = "https://rpc.mainnet.chain.robinhood.com";
26
- const EXPLORER = "https://robinhoodchain.blockscout.com";
27
- const PERMIT2 = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
28
-
29
- // The two tokens this server pays with, each with a hard cap per call and a daily budget (env overrides).
30
- const TOKENS = {
31
- usdg: {
32
- symbol: "USDG",
33
- address: "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
34
- decimals: 6,
35
- cap: parseUnits("0.05", 6),
36
- daily: parseUnits(process.env.AUTONOMO_DAILY_USDG || "1", 6),
37
- },
38
- autonomo: {
39
- symbol: "AUTONOMO",
40
- address: "0xe83c85e1ead16fcfe85401e2b337fb4fb5b5cc96",
41
- decimals: 18,
42
- cap: parseUnits("5000", 18),
43
- daily: parseUnits(process.env.AUTONOMO_DAILY_AUTONOMO || "10000", 18),
44
- },
45
- };
46
- const DEFAULT_PAY = (process.env.AUTONOMO_PAY_WITH || "usdg").toLowerCase() === "autonomo" ? "autonomo" : "usdg";
47
-
48
- const robinhood = defineChain({
49
- id: 4663,
50
- name: "Robinhood Chain",
51
- nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
52
- rpcUrls: { default: { http: [RPC] } },
53
- });
54
-
55
- class Stop extends Error {}
56
- const fail = (message) => {
57
- throw new Stop(message);
58
- };
59
- const decode = (h) => (h ? JSON.parse(Buffer.from(h, "base64").toString("utf8")) : null);
60
- const tokenOf = (asset) => Object.values(TOKENS).find((t) => t.address.toLowerCase() === String(asset).toLowerCase());
61
-
62
- // ---------- Daily budget, kept in ~/.autonomo-mcp/spend.json (base units per token, reset each UTC day) ----------
63
-
64
- const SPEND_FILE = join(homedir(), ".autonomo-mcp", "spend.json");
65
- const today = () => new Date().toISOString().slice(0, 10);
66
-
67
- function spentToday() {
68
- try {
69
- const s = JSON.parse(readFileSync(SPEND_FILE, "utf8"));
70
- if (s.date === today()) return { usdg: BigInt(s.usdg ?? 0), autonomo: BigInt(s.autonomo ?? 0) };
71
- } catch {
72
- // No file yet, or unreadable: nothing spent today.
73
- }
74
- return { usdg: 0n, autonomo: 0n };
75
- }
76
-
77
- function recordSpend(pay, amount) {
78
- const s = spentToday();
79
- s[pay] += amount;
80
- mkdirSync(join(homedir(), ".autonomo-mcp"), { recursive: true });
81
- writeFileSync(SPEND_FILE, JSON.stringify({ date: today(), usdg: s.usdg.toString(), autonomo: s.autonomo.toString() }));
82
- }
83
-
84
- // ---------- Gateways ----------
85
-
86
- const UPDATING = "Autonomo is being updated right now. Please check back later.";
87
-
88
- async function getJson(url) {
89
- const res = await fetch(url, { signal: AbortSignal.timeout(15_000) });
90
- if (res.status === 503) fail(UPDATING);
91
- if (!res.ok) fail(`${new URL(url).pathname} answered ${res.status}.`);
92
- return res.json();
93
- }
94
-
95
- /** Only Autonomo gateway URLs: https://autonomo.fun/x/<slug><path>, nothing that escapes /x/<slug>. */
96
- function gatewayUrl(slug, path = "/") {
97
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(slug)) fail("slug should look like token-risk (lowercase letters, numbers, dashes).");
98
- const p = path.startsWith("/") ? path : `/${path}`;
99
- if (p.includes("..") || p.startsWith("//") || /[\s\\]/.test(p)) fail("path must be a plain path such as /risk/0x….");
100
- const url = new URL(`${BASE}/x/${slug}${p}`);
101
- if (url.origin !== new URL(BASE).origin || !(url.pathname === `/x/${slug}` || url.pathname.startsWith(`/x/${slug}/`))) {
102
- fail("That path leaves the gateway.");
103
- }
104
- return url.toString();
105
- }
106
-
107
- /** The 402 price list for a gateway call, without paying. */
108
- async function quote(url) {
109
- const res = await fetch(url, { signal: AbortSignal.timeout(20_000) });
110
- let required = decode(res.headers.get("payment-required"));
111
- if (!required && res.status === 402) {
112
- try {
113
- required = JSON.parse(await res.text());
114
- } catch {
115
- required = null;
116
- }
117
- } else {
118
- await res.body?.cancel();
119
- }
120
- if (res.status === 503 && res.headers.get("retry-after")) fail(UPDATING);
121
- if (res.status !== 402 || !Array.isArray(required?.accepts)) fail(`Expected a 402 price list, got ${res.status}.`);
122
- return required;
123
- }
124
-
125
- function offersFrom(required) {
126
- return required.accepts.map((a) => {
127
- const t = tokenOf(a.asset);
128
- return { token: t?.symbol ?? a.asset, amount: formatUnits(BigInt(a.amount), t?.decimals ?? 18), network: a.network, payTo: a.payTo };
129
- });
130
- }
131
-
132
- // ---------- Paying ----------
133
-
134
- function walletKey() {
135
- const key = process.env.AUTONOMO_WALLET_KEY?.trim();
136
- if (!key) fail("No wallet set. Add AUTONOMO_WALLET_KEY (a dedicated wallet with a little USDG or $AUTONOMO) to this server's env in your MCP config.");
137
- if (!/^0x[0-9a-fA-F]{64}$/.test(key)) fail("AUTONOMO_WALLET_KEY should be 0x followed by 64 hex characters.");
138
- return key;
139
- }
140
-
141
- async function pay(url, payWith) {
142
- const token = TOKENS[payWith];
143
- const account = privateKeyToAccount(walletKey());
144
- const pub = createPublicClient({ chain: robinhood, transport: http(RPC) });
145
-
146
- const required = await quote(url);
147
- const choice = required.accepts.find((a) => a.network === NETWORK && a.asset.toLowerCase() === token.address.toLowerCase());
148
- if (!choice) fail(`This API doesn't accept ${token.symbol}. It accepts: ${offersFrom(required).map((o) => `${o.amount} ${o.token}`).join(", ")}.`);
149
- const amount = BigInt(choice.amount);
150
- const price = `${formatUnits(amount, token.decimals)} ${token.symbol}`;
151
-
152
- if (amount > token.cap) fail(`The price (${price}) is above this server's cap of ${formatUnits(token.cap, token.decimals)} ${token.symbol} per call.`);
153
- const spent = spentToday()[payWith];
154
- if (spent + amount > token.daily) {
155
- fail(
156
- `Daily budget reached: ${formatUnits(spent, token.decimals)} of ${formatUnits(token.daily, token.decimals)} ${token.symbol} spent today (UTC). ` +
157
- `Raise AUTONOMO_DAILY_${payWith.toUpperCase()} to allow more.`,
158
- );
159
- }
160
- const balance = await pub.readContract({ address: token.address, abi: erc20Abi, functionName: "balanceOf", args: [account.address] });
161
- if (balance < amount) fail(`Not enough ${token.symbol}: the wallet ${account.address} has ${formatUnits(balance, token.decimals)}, the call costs ${price}.`);
162
-
163
- // $AUTONOMO is paid through Permit2: one approval transaction the first time (needs a little ETH for gas).
164
- let approveTx = null;
165
- if (choice.extra?.assetTransferMethod === "permit2") {
166
- const allowance = await pub.readContract({ address: token.address, abi: erc20Abi, functionName: "allowance", args: [account.address, PERMIT2] });
167
- if (allowance < amount) {
168
- const wallet = createWalletClient({ account, chain: robinhood, transport: http(RPC) });
169
- approveTx = await wallet.writeContract({ address: token.address, abi: erc20Abi, functionName: "approve", args: [PERMIT2, maxUint256] });
170
- await pub.waitForTransactionReceipt({ hash: approveTx });
171
- }
172
- }
173
-
174
- const client = x402Client.fromConfig({
175
- schemes: [{ network: NETWORK, client: new ExactEvmScheme(toClientEvmSigner(account, pub), { rpcUrl: RPC }) }],
176
- spendControls: {
177
- allowedAssets: [{ network: NETWORK, asset: token.address, maxAmountPerPayment: token.cap.toString() }],
178
- maxAmountPerPayment: false,
179
- },
180
- paymentRequirementsSelector: (_v, reqs) => reqs.find((r) => r.asset.toLowerCase() === token.address.toLowerCase()) ?? reqs[0],
181
- });
182
- const res = await wrapFetchWithPayment(fetch, client)(url, { signal: AbortSignal.timeout(60_000) });
183
- if (res.status !== 200) {
184
- const reason = decode(res.headers.get("payment-required"))?.error;
185
- fail(reason ? `Payment rejected: ${reason}` : `The API answered ${res.status} after payment (you weren't charged if it didn't settle).`);
186
- }
187
- const settlement = decode(res.headers.get("payment-response"));
188
- const tx = settlement?.transaction ?? null;
189
- recordSpend(payWith, amount);
190
-
191
- const text = await res.text();
192
- let data;
193
- try {
194
- data = JSON.parse(text);
195
- } catch {
196
- data = text.slice(0, 20_000);
197
- }
198
- return {
199
- paid: { amount: formatUnits(amount, token.decimals), token: token.symbol, from: account.address, to: choice.payTo },
200
- tx: tx ? `${EXPLORER}/tx/${tx}` : null,
201
- approveTx: approveTx ? `${EXPLORER}/tx/${approveTx}` : null,
202
- spentToday: `${formatUnits(spentToday()[payWith], token.decimals)} of ${formatUnits(token.daily, token.decimals)} ${token.symbol}`,
203
- data,
204
- };
205
- }
206
-
207
- // ---------- MCP ----------
208
-
209
- const ok = (value) => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
210
- const wrap = (fn) => async (args) => {
211
- try {
212
- return ok(await fn(args));
213
- } catch (e) {
214
- const message = e instanceof Stop ? e.message : e?.name === "TimeoutError" ? "The request timed out." : (e?.shortMessage ?? e?.message ?? String(e));
215
- return { content: [{ type: "text", text: message }], isError: true };
216
- }
217
- };
218
-
219
- const server = new McpServer({ name: "autonomo", version: VERSION });
220
-
221
- server.registerTool(
222
- "find_apis",
223
- {
224
- title: "Find Autonomo APIs",
225
- description:
226
- "Search the paid APIs on Autonomo (token prices, new launches, rug-risk checks, wallet portfolios, transaction explainers, " +
227
- "page reader and more on Robinhood Chain). Returns each API's slug, price and the path to call. verified means the provider holds the Verified minimum of " +
228
- "$AUTONOMO; it isn't a review of the API. Free. " +
229
- "Set include_directory to also search Autonomo's directory of 4K+ x402 projects on other networks (listed for reference; " +
230
- "call_api only pays Autonomo gateways).",
231
- inputSchema: {
232
- query: z.string().max(200).optional().describe("What the API should do, e.g. 'token risk' or 'wallet holdings'. Leave empty to list all."),
233
- include_directory: z.boolean().optional().describe("Also search the x402 directory (other projects and networks)."),
234
- },
235
- annotations: { readOnlyHint: true, openWorldHint: true },
236
- },
237
- wrap(async ({ query = "", include_directory = false }) => {
238
- const { data } = await getJson(`${BASE}/api/v1/gateways`);
239
- const words = query.toLowerCase().split(/[^a-z0-9$]+/).filter((w) => w.length > 1);
240
- const score = (g) => words.filter((w) => `${g.slug} ${g.name} ${g.description}`.toLowerCase().includes(w)).length;
241
- const apis = words.length ? data.map((g) => [score(g), g]).filter(([s]) => s > 0).sort((a, b) => b[0] - a[0]).map(([, g]) => g) : data;
242
- const result = {
243
- apis: (apis.length ? apis : data).map(({ slug, name, description, usage, price, verified }) => ({ slug, name, description, path: usage, price, verified })),
244
- note: !data.length
245
- ? "No Autonomo APIs are listed right now."
246
- : apis.length || !words.length
247
- ? undefined
248
- : "No close match, so every Autonomo API is listed.",
249
- next: "Call get_price or call_api with a slug and the path (fill in the <…> parts).",
250
- };
251
- if (include_directory && query) {
252
- const dir = await getJson(`${BASE}/api/v1/projects?q=${encodeURIComponent(query)}&limit=8`);
253
- result.directory = dir.data.map((p) => ({
254
- name: p.name,
255
- description: p.description,
256
- networks: p.networks,
257
- minPriceUsd: p.minPriceUsd,
258
- paidCalls30d: p.calls30d,
259
- website: p.website,
260
- page: `${BASE}${p.url}`,
261
- }));
262
- }
263
- return result;
264
- }),
265
- );
266
-
267
- server.registerTool(
268
- "get_price",
269
- {
270
- title: "Check an API's price",
271
- description: "Call an Autonomo API without paying and return its price in USDG and $AUTONOMO. Free; use it before call_api.",
272
- inputSchema: {
273
- slug: z.string().describe("The API's slug from find_apis, e.g. token-risk."),
274
- path: z.string().max(2000).optional().describe("The path from find_apis with the <…> parts filled in, e.g. /risk/0xabc…"),
275
- },
276
- annotations: { readOnlyHint: true, openWorldHint: true },
277
- },
278
- wrap(async ({ slug, path }) => {
279
- const url = gatewayUrl(slug, path);
280
- const required = await quote(url);
281
- return { url, description: required.resource?.description ?? null, offers: offersFrom(required), defaultPayment: TOKENS[DEFAULT_PAY].symbol };
282
- }),
283
- );
284
-
285
- server.registerTool(
286
- "call_api",
287
- {
288
- title: "Pay for and call an API",
289
- description:
290
- "Pay for one call to an Autonomo API with x402 and return the answer. Spends USDG or $AUTONOMO from the configured wallet on " +
291
- "Robinhood Chain (usually 0.01 USDG or 100 $AUTONOMO), within a per-call cap and a daily budget. Returns the data and the " +
292
- "payment transaction link.",
293
- inputSchema: {
294
- slug: z.string().describe("The API's slug from find_apis, e.g. token-risk."),
295
- path: z.string().max(2000).optional().describe("The path from find_apis with the <…> parts filled in, e.g. /risk/0xabc…"),
296
- pay_with: z.enum(["usdg", "autonomo"]).optional().describe(`Token to pay with (default ${DEFAULT_PAY}).`),
297
- },
298
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
299
- },
300
- wrap(async ({ slug, path, pay_with }) => pay(gatewayUrl(slug, path), pay_with ?? DEFAULT_PAY)),
301
- );
302
-
303
- await server.connect(new StdioServerTransport());
304
- console.error(`Autonomo MCP server ${VERSION} ready (${BASE})`);
1
+ #!/usr/bin/env node
2
+ // Autonomo MCP server: lets Claude, Codex, Cursor and other MCP clients find Autonomo x402 APIs, check the price
3
+ // and pay per call in USDG or $AUTONOMO on Robinhood Chain, or USDC on Base, from a wallet the user controls.
4
+ //
5
+ // Tools: find_apis (free), get_price (free), wallet_status (free), call_api (pays). Runs locally over stdio, so the wallet key never
6
+ // leaves this machine except as signed payments. Settings come from env vars (see README.md). Never write to
7
+ // stdout here: it carries the MCP protocol, so logs go to stderr.
8
+
9
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
13
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
14
+ import { createPublicClient, createWalletClient, defineChain, erc20Abi, formatUnits, http, maxUint256, parseUnits } from "viem";
15
+ import { privateKeyToAccount } from "viem/accounts";
16
+ import { base } from "viem/chains";
17
+ import { x402Client } from "@x402/core/client";
18
+ import { toClientEvmSigner } from "@x402/evm";
19
+ import { ExactEvmScheme } from "@x402/evm/exact/client";
20
+ import { wrapFetchWithPayment } from "@x402/fetch";
21
+ import { z } from "zod";
22
+
23
+ const VERSION = "0.1.4";
24
+ const BASE = (process.env.AUTONOMO_BASE_URL || "https://autonomo.fun").replace(/\/+$/, "");
25
+ const NETWORK = "eip155:4663";
26
+ const RPC = process.env.AUTONOMO_RPC_URL || "https://rpc.mainnet.chain.robinhood.com";
27
+ const EXPLORER = "https://robinhoodchain.blockscout.com";
28
+ const BASE_NETWORK = "eip155:8453";
29
+ const BASE_RPC = process.env.AUTONOMO_BASE_RPC_URL || "https://mainnet.base.org";
30
+ const PERMIT2 = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
31
+
32
+ // The tokens this server pays with, each with a hard cap per call and a daily budget (env overrides). USDG and USDC on
33
+ // Base are both dollars, so they share one cap and one daily budget (AUTONOMO_DAILY_USDG); `budget` names it.
34
+ /** An amount from an env var, in whole tokens. A value that isn't a plain number is ignored, with a note on stderr. */
35
+ function amountEnv(name, fallback, decimals) {
36
+ const raw = process.env[name]?.trim();
37
+ if (!raw) return parseUnits(fallback, decimals);
38
+ if (/^\d+(\.\d+)?$/.test(raw)) return parseUnits(raw, decimals);
39
+ console.error(`${name} should be a number such as ${fallback}; using ${fallback}.`);
40
+ return parseUnits(fallback, decimals);
41
+ }
42
+ const USD_DAILY = amountEnv("AUTONOMO_DAILY_USDG", "5", 6);
43
+ const USD_CAP = amountEnv("AUTONOMO_MAX_USDG_PER_CALL", "0.5", 6);
44
+ const TOKENS = {
45
+ usdg: {
46
+ symbol: "USDG",
47
+ label: "USDG",
48
+ address: "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",
49
+ decimals: 6,
50
+ network: NETWORK,
51
+ chain: "Robinhood Chain",
52
+ explorer: EXPLORER,
53
+ budget: "usd",
54
+ cap: USD_CAP,
55
+ daily: USD_DAILY,
56
+ },
57
+ autonomo: {
58
+ symbol: "AUTONOMO",
59
+ label: "AUTONOMO",
60
+ address: "0xe83c85e1ead16fcfe85401e2b337fb4fb5b5cc96",
61
+ decimals: 18,
62
+ network: NETWORK,
63
+ chain: "Robinhood Chain",
64
+ explorer: EXPLORER,
65
+ budget: "autonomo",
66
+ cap: amountEnv("AUTONOMO_MAX_AUTONOMO_PER_CALL", "5000", 18),
67
+ daily: amountEnv("AUTONOMO_DAILY_AUTONOMO", "10000", 18),
68
+ },
69
+ usdc: {
70
+ symbol: "USDC",
71
+ label: "USDC on Base",
72
+ address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
73
+ decimals: 6,
74
+ network: BASE_NETWORK,
75
+ chain: "Base",
76
+ explorer: "https://basescan.org",
77
+ budget: "usd",
78
+ cap: USD_CAP,
79
+ daily: USD_DAILY,
80
+ },
81
+ };
82
+ // The order "auto" tries them in.
83
+ const PAY_CHOICES = ["usdg", "autonomo", "usdc"];
84
+ const PAY_LABEL = { usdg: "USDG", autonomo: "AUTONOMO", usdc: "USDC on Base", auto: "auto: USDG, then AUTONOMO, then USDC on Base, whichever the wallet can pay with" };
85
+ const PAY_ENV = (process.env.AUTONOMO_PAY_WITH || "").trim().toLowerCase();
86
+ if (PAY_ENV && !Object.hasOwn(PAY_LABEL, PAY_ENV)) console.error("AUTONOMO_PAY_WITH should be auto, usdg, autonomo or usdc; using auto.");
87
+ const DEFAULT_PAY = Object.hasOwn(PAY_LABEL, PAY_ENV) ? PAY_ENV : "auto";
88
+
89
+ const robinhood = defineChain({
90
+ id: 4663,
91
+ name: "Robinhood Chain",
92
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
93
+ rpcUrls: { default: { http: [RPC] } },
94
+ });
95
+
96
+ class Stop extends Error {}
97
+ const fail = (message) => {
98
+ throw new Stop(message);
99
+ };
100
+ const decode = (h) => (h ? JSON.parse(Buffer.from(h, "base64").toString("utf8")) : null);
101
+ const tokenOf = (asset, network) =>
102
+ Object.values(TOKENS).find((t) => t.address.toLowerCase() === String(asset).toLowerCase() && (network === undefined || t.network === network));
103
+
104
+ // ---------- Daily budget, kept in ~/.autonomo-mcp/spend.json (base units per token, reset each UTC day) ----------
105
+ // USDG and USDC are kept apart in the file but count against one dollar budget.
106
+
107
+ const SPEND_FILE = join(homedir(), ".autonomo-mcp", "spend.json");
108
+ const today = () => new Date().toISOString().slice(0, 10);
109
+
110
+ function spentToday() {
111
+ try {
112
+ const s = JSON.parse(readFileSync(SPEND_FILE, "utf8"));
113
+ if (s.date === today()) return { usdg: BigInt(s.usdg ?? 0), autonomo: BigInt(s.autonomo ?? 0), usdc: BigInt(s.usdc ?? 0) };
114
+ } catch {
115
+ // No file yet, or unreadable: nothing spent today.
116
+ }
117
+ return { usdg: 0n, autonomo: 0n, usdc: 0n };
118
+ }
119
+
120
+ /** What counts against a token's budget today: dollars (USDG and USDC together) or $AUTONOMO. */
121
+ function spentOnBudget(pay) {
122
+ const s = spentToday();
123
+ return TOKENS[pay].budget === "usd" ? s.usdg + s.usdc : s.autonomo;
124
+ }
125
+
126
+ function recordSpend(pay, amount) {
127
+ const s = spentToday();
128
+ s[pay] += amount;
129
+ mkdirSync(join(homedir(), ".autonomo-mcp"), { recursive: true });
130
+ writeFileSync(SPEND_FILE, JSON.stringify({ date: today(), usdg: s.usdg.toString(), autonomo: s.autonomo.toString(), usdc: s.usdc.toString() }));
131
+ }
132
+
133
+ // ---------- Gateways ----------
134
+
135
+ const UPDATING = "Autonomo is being updated right now. Please check back later.";
136
+
137
+ async function getJson(url) {
138
+ const res = await fetch(url, { signal: AbortSignal.timeout(15_000) });
139
+ if (res.status === 503) fail(UPDATING);
140
+ if (!res.ok) fail(`${new URL(url).pathname} answered ${res.status}.`);
141
+ return res.json();
142
+ }
143
+
144
+ /** Only Autonomo gateway URLs: https://autonomo.fun/x/<slug><path>, nothing that escapes /x/<slug>. */
145
+ function gatewayUrl(slug, path = "/") {
146
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(slug)) fail("slug should look like token-risk (lowercase letters, numbers, dashes).");
147
+ const p = path.startsWith("/") ? path : `/${path}`;
148
+ if (p.includes("..") || p.startsWith("//") || /[\s\\]/.test(p)) fail("path must be a plain path such as /risk/0x….");
149
+ const url = new URL(`${BASE}/x/${slug}${p}`);
150
+ if (url.origin !== new URL(BASE).origin || !(url.pathname === `/x/${slug}` || url.pathname.startsWith(`/x/${slug}/`))) {
151
+ fail("That path leaves the gateway.");
152
+ }
153
+ return url.toString();
154
+ }
155
+
156
+ /** The 402 price list for a gateway call, without paying. */
157
+ async function quote(url) {
158
+ const res = await fetch(url, { signal: AbortSignal.timeout(20_000) });
159
+ let required = decode(res.headers.get("payment-required"));
160
+ if (!required && res.status === 402) {
161
+ try {
162
+ required = JSON.parse(await res.text());
163
+ } catch {
164
+ required = null;
165
+ }
166
+ } else {
167
+ await res.body?.cancel();
168
+ }
169
+ if (res.status === 503 && res.headers.get("retry-after")) fail(UPDATING);
170
+ if (res.status !== 402 || !Array.isArray(required?.accepts)) fail(`Expected a 402 price list, got ${res.status}.`);
171
+ return required;
172
+ }
173
+
174
+ function offersFrom(required) {
175
+ return required.accepts.map((a) => {
176
+ const t = tokenOf(a.asset, a.network);
177
+ return { token: t?.label ?? a.asset, amount: formatUnits(BigInt(a.amount), t?.decimals ?? 18), network: a.network, payTo: a.payTo };
178
+ });
179
+ }
180
+
181
+ // ---------- Paying ----------
182
+
183
+ function walletKey() {
184
+ const key = process.env.AUTONOMO_WALLET_KEY?.trim();
185
+ if (!key) {
186
+ fail("No wallet set. Add AUTONOMO_WALLET_KEY (a dedicated wallet with a little USDG or $AUTONOMO on Robinhood Chain, or USDC on Base) to this server's env in your MCP config.");
187
+ }
188
+ if (!/^0x[0-9a-fA-F]{64}$/.test(key)) fail("AUTONOMO_WALLET_KEY should be 0x followed by 64 hex characters.");
189
+ return key;
190
+ }
191
+
192
+ function clients() {
193
+ return { pub: createPublicClient({ chain: robinhood, transport: http(RPC) }), basePub: createPublicClient({ chain: base, transport: http(BASE_RPC) }) };
194
+ }
195
+
196
+ /**
197
+ * Whether one token can pay this price list right now: the API takes it, the price is within the cap and today's
198
+ * budget, and the wallet holds enough. Returns what to pay, or `why` it can't. Nothing is signed here.
199
+ */
200
+ async function check(name, required, account, { pub, basePub }) {
201
+ const token = TOKENS[name];
202
+ const usd = token.budget === "usd";
203
+ const choice = required.accepts.find((a) => a.scheme === "exact" && a.network === token.network && a.asset.toLowerCase() === token.address.toLowerCase());
204
+ if (!choice) return { why: `This API doesn't accept ${token.label}. It accepts: ${offersFrom(required).map((o) => `${o.amount} ${o.token}`).join(", ")}.` };
205
+ const amount = BigInt(choice.amount);
206
+ const price = `${formatUnits(amount, token.decimals)} ${token.label}`;
207
+ if (amount > token.cap) {
208
+ return { why: `The price (${price}) is above this server's cap of ${formatUnits(token.cap, token.decimals)} ${usd ? "USDG/USDC" : token.symbol} per call.` };
209
+ }
210
+ const spent = spentOnBudget(name);
211
+ if (spent + amount > token.daily) {
212
+ return {
213
+ why:
214
+ `Daily budget reached: ${formatUnits(spent, token.decimals)} of ${formatUnits(token.daily, token.decimals)} ${usd ? "dollars (USDG and USDC)" : token.symbol} spent today (UTC). ` +
215
+ `Raise AUTONOMO_DAILY_${usd ? "USDG" : "AUTONOMO"} to allow more.`,
216
+ };
217
+ }
218
+ const chainPub = token.network === BASE_NETWORK ? basePub : pub;
219
+ const balance = await chainPub.readContract({ address: token.address, abi: erc20Abi, functionName: "balanceOf", args: [account.address] });
220
+ if (balance < amount) return { why: `Not enough ${token.label}: the wallet ${account.address} has ${formatUnits(balance, token.decimals)}, the call costs ${price}.` };
221
+ return { name, token, choice, amount, price };
222
+ }
223
+
224
+ async function pay(url, payWith) {
225
+ const account = privateKeyToAccount(walletKey());
226
+ const both = clients();
227
+ const { pub, basePub } = both;
228
+ const required = await quote(url);
229
+
230
+ // "auto" takes the first token that can pay, in this order; a named token is that one or nothing.
231
+ const order = payWith === "auto" ? PAY_CHOICES : [payWith];
232
+ const whys = [];
233
+ let picked = null;
234
+ for (const name of order) {
235
+ const r = await check(name, required, account, both);
236
+ if (!r.why) {
237
+ picked = r;
238
+ break;
239
+ }
240
+ whys.push(order.length > 1 ? `${TOKENS[name].label}: ${r.why}` : r.why);
241
+ }
242
+ if (!picked) fail(order.length > 1 ? `No token could pay for this call. ${whys.join(" ")}` : whys[0]);
243
+ const { name, token, choice, amount } = picked;
244
+ const usd = token.budget === "usd";
245
+
246
+ // $AUTONOMO is paid through Permit2: one approval transaction the first time (needs a little ETH for gas).
247
+ let approveTx = null;
248
+ if (choice.extra?.assetTransferMethod === "permit2") {
249
+ if (token.network !== NETWORK) fail("A Permit2 payment is only expected on Robinhood Chain.");
250
+ const allowance = await pub.readContract({ address: token.address, abi: erc20Abi, functionName: "allowance", args: [account.address, PERMIT2] });
251
+ if (allowance < amount) {
252
+ const wallet = createWalletClient({ account, chain: robinhood, transport: http(RPC) });
253
+ approveTx = await wallet.writeContract({ address: token.address, abi: erc20Abi, functionName: "approve", args: [PERMIT2, maxUint256] });
254
+ await pub.waitForTransactionReceipt({ hash: approveTx });
255
+ }
256
+ }
257
+
258
+ // Only what was quoted and checked above is ever signed: the same token on the same chain, the same amount and the
259
+ // same payee. If the API's second price list differs, nothing is signed.
260
+ const client = x402Client.fromConfig({
261
+ schemes: [
262
+ token.network === BASE_NETWORK
263
+ ? { network: BASE_NETWORK, client: new ExactEvmScheme(toClientEvmSigner(account, basePub), { rpcUrl: BASE_RPC }) }
264
+ : { network: NETWORK, client: new ExactEvmScheme(toClientEvmSigner(account, pub), { rpcUrl: RPC }) },
265
+ ],
266
+ spendControls: {
267
+ allowedAssets: [{ network: token.network, asset: token.address, maxAmountPerPayment: token.cap.toString() }],
268
+ maxAmountPerPayment: false,
269
+ },
270
+ paymentRequirementsSelector: (_v, reqs) =>
271
+ reqs.find(
272
+ (r) =>
273
+ r.network === token.network &&
274
+ r.asset.toLowerCase() === token.address.toLowerCase() &&
275
+ String(r.amount) === String(choice.amount) &&
276
+ r.payTo.toLowerCase() === choice.payTo.toLowerCase(),
277
+ ) ?? fail("The price or payee changed after it was checked, so nothing was paid. Check the price again."),
278
+ });
279
+ const res = await wrapFetchWithPayment(fetch, client)(url, { signal: AbortSignal.timeout(60_000) });
280
+ if (res.status !== 200) {
281
+ const reason = decode(res.headers.get("payment-required"))?.error;
282
+ fail(reason ? `Payment rejected: ${reason}` : `The API answered ${res.status} after payment (you weren't charged if it didn't settle).`);
283
+ }
284
+ const settlement = decode(res.headers.get("payment-response"));
285
+ const tx = settlement?.transaction ?? null;
286
+ recordSpend(name, amount);
287
+
288
+ const text = await res.text();
289
+ let data;
290
+ try {
291
+ data = JSON.parse(text);
292
+ } catch {
293
+ data = text.slice(0, 20_000);
294
+ }
295
+ return {
296
+ paid: { amount: formatUnits(amount, token.decimals), token: token.label, chain: token.chain, from: account.address, to: choice.payTo },
297
+ tx: tx ? `${token.explorer}/tx/${tx}` : null,
298
+ approveTx: approveTx ? `${EXPLORER}/tx/${approveTx}` : null,
299
+ spentToday: `${formatUnits(spentOnBudget(name), token.decimals)} of ${formatUnits(token.daily, token.decimals)} ${usd ? "dollars (USDG and USDC)" : token.symbol}`,
300
+ data,
301
+ };
302
+ }
303
+
304
+ /** The wallet's balances on both chains, today's spending and the limits. Reads only. */
305
+ async function walletStatus() {
306
+ const account = privateKeyToAccount(walletKey());
307
+ const { pub, basePub } = clients();
308
+ const held = (client, token) => client.readContract({ address: token.address, abi: erc20Abi, functionName: "balanceOf", args: [account.address] });
309
+ const [robinhoodChain, baseChain] = await Promise.all([
310
+ Promise.all([held(pub, TOKENS.usdg), held(pub, TOKENS.autonomo), pub.getBalance({ address: account.address })])
311
+ .then(([usdg, autonomo, eth]) => ({ usdg: formatUnits(usdg, 6), autonomo: formatUnits(autonomo, 18), eth: formatUnits(eth, 18) }))
312
+ .catch(() => null),
313
+ held(basePub, TOKENS.usdc)
314
+ .then((usdc) => ({ usdc: formatUnits(usdc, 6) }))
315
+ .catch(() => null),
316
+ ]);
317
+ const s = spentToday();
318
+ return {
319
+ wallet: account.address,
320
+ robinhoodChain: robinhoodChain ?? "couldn't be read just now",
321
+ base: baseChain ?? "couldn't be read just now",
322
+ spentToday: {
323
+ dollars: `${formatUnits(s.usdg + s.usdc, 6)} of ${formatUnits(USD_DAILY, 6)} (USDG ${formatUnits(s.usdg, 6)}, USDC on Base ${formatUnits(s.usdc, 6)})`,
324
+ autonomo: `${formatUnits(s.autonomo, 18)} of ${formatUnits(TOKENS.autonomo.daily, 18)}`,
325
+ },
326
+ perCallCap: { dollars: formatUnits(TOKENS.usdg.cap, 6), autonomo: formatUnits(TOKENS.autonomo.cap, 18) },
327
+ defaultPayment: PAY_LABEL[DEFAULT_PAY],
328
+ note: "Paying in $AUTONOMO needs a little ETH on Robinhood Chain once, for the Permit2 approval. USDG and USDC need none.",
329
+ };
330
+ }
331
+
332
+ // ---------- MCP ----------
333
+
334
+ const ok = (value) => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
335
+ const wrap = (fn) => async (args) => {
336
+ try {
337
+ return ok(await fn(args));
338
+ } catch (e) {
339
+ const message = e instanceof Stop ? e.message : e?.name === "TimeoutError" ? "The request timed out." : (e?.shortMessage ?? e?.message ?? String(e));
340
+ return { content: [{ type: "text", text: message }], isError: true };
341
+ }
342
+ };
343
+
344
+ const server = new McpServer({ name: "autonomo", version: VERSION });
345
+
346
+ server.registerTool(
347
+ "find_apis",
348
+ {
349
+ title: "Find Autonomo APIs",
350
+ description:
351
+ "Search the paid APIs on Autonomo (token prices, new launches, rug-risk checks, wallet portfolios, transaction explainers, " +
352
+ "page reader and more on Robinhood Chain). Returns each API's slug, price and the path to call. verified means the provider holds the Verified minimum of " +
353
+ "$AUTONOMO; it isn't a review of the API. Free. " +
354
+ "Set include_directory to also search Autonomo's directory of 4K+ x402 projects on other networks (listed for reference; " +
355
+ "call_api only pays Autonomo gateways).",
356
+ inputSchema: {
357
+ query: z.string().max(200).optional().describe("What the API should do, e.g. 'token risk' or 'wallet holdings'. Leave empty to list all."),
358
+ include_directory: z.boolean().optional().describe("Also search the x402 directory (other projects and networks)."),
359
+ },
360
+ annotations: { readOnlyHint: true, openWorldHint: true },
361
+ },
362
+ wrap(async ({ query = "", include_directory = false }) => {
363
+ const { data } = await getJson(`${BASE}/api/v1/gateways`);
364
+ const words = query.toLowerCase().split(/[^a-z0-9$]+/).filter((w) => w.length > 1);
365
+ const score = (g) => words.filter((w) => `${g.slug} ${g.name} ${g.description}`.toLowerCase().includes(w)).length;
366
+ const apis = words.length ? data.map((g) => [score(g), g]).filter(([s]) => s > 0).sort((a, b) => b[0] - a[0]).map(([, g]) => g) : data;
367
+ const result = {
368
+ apis: (apis.length ? apis : data).map(({ slug, name, description, usage, price, verified }) => ({ slug, name, description, path: usage, price, verified })),
369
+ note: !data.length
370
+ ? "No Autonomo APIs are listed right now."
371
+ : apis.length || !words.length
372
+ ? undefined
373
+ : "No close match, so every Autonomo API is listed.",
374
+ next: "Call get_price or call_api with a slug and the path (fill in the <…> parts).",
375
+ };
376
+ if (include_directory && query) {
377
+ const dir = await getJson(`${BASE}/api/v1/projects?q=${encodeURIComponent(query)}&limit=8`);
378
+ result.directory = dir.data.map((p) => ({
379
+ name: p.name,
380
+ description: p.description,
381
+ networks: p.networks,
382
+ minPriceUsd: p.minPriceUsd,
383
+ paidCalls30d: p.calls30d,
384
+ website: p.website,
385
+ page: `${BASE}${p.url}`,
386
+ }));
387
+ }
388
+ return result;
389
+ }),
390
+ );
391
+
392
+ server.registerTool(
393
+ "get_price",
394
+ {
395
+ title: "Check an API's price",
396
+ description:
397
+ "Call an Autonomo API without paying and return its price in USDG and $AUTONOMO on Robinhood Chain, and USDC on Base where it takes it. Free; use it before call_api.",
398
+ inputSchema: {
399
+ slug: z.string().describe("The API's slug from find_apis, e.g. token-risk."),
400
+ path: z.string().max(2000).optional().describe("The path from find_apis with the <…> parts filled in, e.g. /risk/0xabc…"),
401
+ },
402
+ annotations: { readOnlyHint: true, openWorldHint: true },
403
+ },
404
+ wrap(async ({ slug, path }) => {
405
+ const url = gatewayUrl(slug, path);
406
+ const required = await quote(url);
407
+ return { url, description: required.resource?.description ?? null, offers: offersFrom(required), defaultPayment: PAY_LABEL[DEFAULT_PAY] };
408
+ }),
409
+ );
410
+
411
+ server.registerTool(
412
+ "call_api",
413
+ {
414
+ title: "Pay for and call an API",
415
+ description:
416
+ "Pay for one call to an Autonomo API with x402 and return the answer. Spends USDG or $AUTONOMO from the configured wallet on " +
417
+ "Robinhood Chain (usually 0.01 USDG, or 20% less in $AUTONOMO), or USDC on Base at the same dollar price, within a per-call cap " +
418
+ "and a daily budget. Returns the data and the payment transaction link.",
419
+ inputSchema: {
420
+ slug: z.string().describe("The API's slug from find_apis, e.g. token-risk."),
421
+ path: z.string().max(2000).optional().describe("The path from find_apis with the <…> parts filled in, e.g. /risk/0xabc…"),
422
+ pay_with: z
423
+ .enum(["auto", "usdg", "autonomo", "usdc"])
424
+ .optional()
425
+ .describe(`Token to pay with: usdg or autonomo on Robinhood Chain, usdc on Base, or auto for the first of those the wallet can pay with (default ${DEFAULT_PAY}).`),
426
+ },
427
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
428
+ },
429
+ wrap(async ({ slug, path, pay_with }) => pay(gatewayUrl(slug, path), pay_with ?? DEFAULT_PAY)),
430
+ );
431
+
432
+ server.registerTool(
433
+ "wallet_status",
434
+ {
435
+ title: "Check the agent's wallet",
436
+ description:
437
+ "What the configured wallet holds (USDG, $AUTONOMO and ETH on Robinhood Chain, USDC on Base), what it has spent today and its " +
438
+ "limits. Free, and it signs nothing. Use it when a payment fails, or before a run of paid calls.",
439
+ inputSchema: {},
440
+ annotations: { readOnlyHint: true, openWorldHint: true },
441
+ },
442
+ wrap(async () => walletStatus()),
443
+ );
444
+
445
+ await server.connect(new StdioServerTransport());
446
+ console.error(`Autonomo MCP server ${VERSION} ready (${BASE})`);
package/package.json CHANGED
@@ -1,45 +1,46 @@
1
- {
2
- "name": "autonomo-mcp",
3
- "version": "0.1.2",
4
- "mcpName": "io.github.autonomodotfun/autonomo",
5
- "description": "MCP server for Autonomo: AI agents find x402 APIs, check prices and pay per call in USDG or $AUTONOMO on Robinhood Chain.",
6
- "homepage": "https://autonomo.fun",
7
- "author": "Autonomo (https://autonomo.fun)",
8
- "license": "MIT",
9
- "type": "module",
10
- "bin": {
11
- "autonomo-mcp": "index.mjs"
12
- },
13
- "files": [
14
- "index.mjs",
15
- "README.md",
16
- "LICENSE"
17
- ],
18
- "engines": {
19
- "node": ">=20"
20
- },
21
- "scripts": {
22
- "start": "node index.mjs",
23
- "inspect": "npx @modelcontextprotocol/inspector node index.mjs"
24
- },
25
- "keywords": [
26
- "mcp",
27
- "x402",
28
- "autonomo",
29
- "robinhood-chain",
30
- "ai-agents",
31
- "model-context-protocol",
32
- "claude",
33
- "cursor",
34
- "codex",
35
- "usdg"
36
- ],
37
- "dependencies": {
38
- "@modelcontextprotocol/sdk": "1.32.1",
39
- "@x402/core": "2.28.0",
40
- "@x402/evm": "2.28.0",
41
- "@x402/fetch": "2.28.0",
42
- "viem": "2.57.12",
43
- "zod": "4.6.7"
44
- }
45
- }
1
+ {
2
+ "name": "autonomo-mcp",
3
+ "version": "0.1.4",
4
+ "mcpName": "io.github.autonomodotfun/autonomo",
5
+ "description": "MCP server for Autonomo: AI agents find x402 APIs, check prices and pay per call in USDG or $AUTONOMO on Robinhood Chain, or USDC on Base.",
6
+ "homepage": "https://autonomo.fun",
7
+ "author": "Autonomo (https://autonomo.fun)",
8
+ "license": "MIT",
9
+ "type": "module",
10
+ "bin": {
11
+ "autonomo-mcp": "index.mjs"
12
+ },
13
+ "files": [
14
+ "index.mjs",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "engines": {
19
+ "node": ">=20"
20
+ },
21
+ "scripts": {
22
+ "start": "node index.mjs",
23
+ "test": "node --test test/*.test.mjs",
24
+ "inspect": "npx @modelcontextprotocol/inspector node index.mjs"
25
+ },
26
+ "keywords": [
27
+ "mcp",
28
+ "x402",
29
+ "autonomo",
30
+ "robinhood-chain",
31
+ "ai-agents",
32
+ "model-context-protocol",
33
+ "claude",
34
+ "cursor",
35
+ "codex",
36
+ "usdg"
37
+ ],
38
+ "dependencies": {
39
+ "@modelcontextprotocol/sdk": "1.32.1",
40
+ "@x402/core": "2.28.0",
41
+ "@x402/evm": "2.28.0",
42
+ "@x402/fetch": "2.28.0",
43
+ "viem": "2.57.12",
44
+ "zod": "4.6.7"
45
+ }
46
+ }