x420-mcp 0.0.0-stage → 1.0.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,135 @@
1
- # Temporary Holding Version
1
+ # x420-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
+ [Model Context Protocol](https://modelcontextprotocol.io) server for **X420**'s pay-per-call agent services at
4
+ [https://signature-theme.com](https://signature-theme.com): website audits, hail and storm history, geocoding,
5
+ DNS/TLS/RDAP lookups, government and chain data, and whatever X420 sells next. Every service becomes an MCP tool;
6
+ every paid call is settled with [x402](https://x402.org) in USDC on Base **from your own wallet**.
7
+
8
+ **X420 never sees your key.** The private key is read from your environment inside this local process, signs an
9
+ EIP-3009 USDC authorization, and only that signature leaves the machine (as the `PAYMENT-SIGNATURE` header). It is
10
+ never logged, never written to disk by this package, and never sent to X420 or anyone else.
11
+
12
+ **This spends real money.** A successful paid call moves USDC on Base mainnet. Fund a dedicated wallet with only what
13
+ you are willing to spend, keep `X420_MCP_MAX_USD` low, and rotate the key when you stop using the server.
14
+
15
+ ## Install
16
+
17
+ ```
18
+ npx x420-mcp
19
+ ```
20
+
21
+ The server speaks MCP on stdin/stdout. On start it fetches the live catalog (`GET https://signature-theme.com/a2a/catalog`)
22
+ and registers one tool per service, named `x420_<id>` with dots replaced by underscores (`sitescan.check` →
23
+ `x420_sitescan_check`, `hail.point-history` → `x420_hail_point-history`), plus two free tools:
24
+
25
+ - `x420_catalog` — the live catalog with prices, inputs and deliverables.
26
+ - `x420_quote` — a free price quote for one service and input (no order is placed).
27
+
28
+ Nothing is hard-coded: new X420 services appear on the next start.
29
+
30
+ ### Claude Desktop
31
+
32
+ `claude_desktop_config.json` (Settings → Developer → Edit Config):
33
+
34
+ ```json
35
+ {
36
+ "mcpServers": {
37
+ "x420": {
38
+ "command": "npx",
39
+ "args": ["-y", "x420-mcp"],
40
+ "env": {
41
+ "X420_MCP_WALLET_PRIVATE_KEY": "0x<your private key>",
42
+ "X420_MCP_MAX_USD": "1.00"
43
+ }
44
+ }
45
+ }
46
+ }
47
+ ```
48
+
49
+ ### Claude Code
50
+
51
+ ```
52
+ claude mcp add x420 -e X420_MCP_WALLET_PRIVATE_KEY=0x<your private key> -e X420_MCP_MAX_USD=1.00 -- npx -y x420-mcp
53
+ ```
54
+
55
+ ### Cursor
56
+
57
+ `.cursor/mcp.json` (project) or `~/.cursor/mcp.json` (global):
58
+
59
+ ```json
60
+ {
61
+ "mcpServers": {
62
+ "x420": {
63
+ "command": "npx",
64
+ "args": ["-y", "x420-mcp"],
65
+ "env": {
66
+ "X420_MCP_WALLET_PRIVATE_KEY": "0x<your private key>",
67
+ "X420_MCP_MAX_USD": "1.00"
68
+ }
69
+ }
70
+ }
71
+ }
72
+ ```
73
+
74
+ Without a key the server still starts: the free tools work and every paid tool returns an error explaining how to set
75
+ the key. Nothing is spent until a key is present.
76
+
77
+ ## Environment
78
+
79
+ | Variable | Default | Meaning |
80
+ | --- | --- | --- |
81
+ | `X420_MCP_WALLET_PRIVATE_KEY` | unset | 0x-prefixed private key of the paying wallet (USDC on Base). Unset = paid tools refuse with instructions. Never logged, never sent. |
82
+ | `X420_MCP_MAX_USD` | `1.00` | Per-call cap in USD. A service priced above it is refused before any request; a 402 asking for more than it is refused before signing. |
83
+ | `X420_MCP_ORIGIN` | `https://signature-theme.com` | The X420 seller to talk to. |
84
+ | `X420_MCP_NETWORK` | `eip155:8453` (Base mainnet) | CAIP-2 network the payer will sign on; a 402 on any other network is refused. |
85
+
86
+ ## How a paid call works
87
+
88
+ 1. The tool call becomes `GET <origin>/a2a/x402/<service id>?<params>`.
89
+ 2. X420 answers `402` with an x402 v2 `PAYMENT-REQUIRED` header (exact scheme, USDC on Base, amount, pay-to).
90
+ 3. The server checks scheme, network, asset and amount against your cap, signs the authorization with your key
91
+ (`@x402/fetch` + `@x402/evm`), and retries with `PAYMENT-SIGNATURE`.
92
+ 4. X420's facilitator settles on Base and X420 returns the deliverable with a signed receipt; the tool result carries
93
+ the deliverable, the receipt, the order and the settlement transaction hash from `PAYMENT-RESPONSE`.
94
+
95
+ ```json
96
+ {
97
+ "service": "sitescan.check",
98
+ "price_usd": 0.5,
99
+ "paid_usd": 0.5,
100
+ "deliverable": { "target": "https://example.com", "summary": { "score": 82, "grade": "B", "findings": 3 }, "findings": [] },
101
+ "receipt": { "receipt_id": "...", "deliverable_sha256": "...", "payee": "x420:...", "sig": "<ed25519 hex>" },
102
+ "order": { "id": "...", "status": "delivered", "amount_usd": 0.5, "rail": "x402" },
103
+ "settlement": { "transaction": "0x...", "network": "eip155:8453", "payer": "0x...", "success": true, "error": null }
104
+ }
105
+ ```
106
+
107
+ A refused call (no key, over the cap, wrong network, non-USDC asset, missing input) returns an MCP error result with
108
+ the reason, and nothing is signed.
109
+
110
+ ## No key? Use the hosted endpoint
111
+
112
+ X420 also serves the same tools over MCP Streamable HTTP at **https://signature-theme.com/mcp**. That endpoint holds
113
+ no wallet: `x420_catalog` and `x420_quote` work as above, and each paid tool validates your input and returns
114
+ **payment instructions** (price, pay-to address, network and the x402 URL) instead of the deliverable, so an agent with
115
+ its own x402 client can pay directly.
116
+
117
+ ```
118
+ claude mcp add --transport http x420 https://signature-theme.com/mcp
119
+ ```
120
+
121
+ ## Programmatic use
122
+
123
+ ```ts
124
+ import { createX420McpServer } from "x420-mcp";
125
+ const { server, tools } = await createX420McpServer({ origin: "https://signature-theme.com", maxUsd: 1, privateKey: process.env.X420_MCP_WALLET_PRIVATE_KEY ?? null });
126
+ ```
127
+
128
+ `x420-mcp/hosted` exports `createHostedMcpHandler({ origin })`, the express-compatible stateless Streamable HTTP
129
+ handler behind the hosted endpoint.
130
+
131
+ ## Disclaimer
132
+
133
+ Automated services on public data; not professional, legal, insurance, engineering, medical, financial or tax advice.
134
+
135
+ MIT License. Source: https://github.com/BodhiNath/X420 (`packages/x420-mcp`, built from `src/mcp`).
@@ -0,0 +1,35 @@
1
+ export const TOOL_PREFIX = "x420_";
2
+ /** `sitescan.check` -> `x420_sitescan_check`; anything outside the MCP tool-name alphabet also becomes `_`. */
3
+ export const toolName = (id) => TOOL_PREFIX + id.replace(/\./g, "_").replace(/[^A-Za-z0-9_-]/g, "_");
4
+ export const isOptionalParam = (description) => /\b(default|optional)\b/i.test(description);
5
+ export const trimOrigin = (origin) => origin.replace(/\/+$/, "");
6
+ export async function fetchCatalog(origin, fetchImpl = fetch) {
7
+ const url = `${trimOrigin(origin)}/a2a/catalog`;
8
+ const res = await fetchImpl(url, { headers: { accept: "application/json" } });
9
+ if (!res.ok)
10
+ throw new Error(`catalog ${url} answered HTTP ${res.status}`);
11
+ const c = (await res.json());
12
+ if (!Array.isArray(c.services))
13
+ throw new Error(`catalog ${url} carries no services array`);
14
+ const services = c.services.filter((s) => Boolean(s) && typeof s.id === "string" && s.id.length > 0);
15
+ return { agent: String(c.agent ?? ""), rails: Array.isArray(c.rails) ? c.rails.map(String) : [], services };
16
+ }
17
+ export function serviceTool(s) {
18
+ const input = s.input && typeof s.input === "object" ? s.input : {};
19
+ const properties = {};
20
+ const required = [];
21
+ for (const [k, d] of Object.entries(input)) {
22
+ const description = String(d);
23
+ properties[k] = { type: "string", description };
24
+ if (!isOptionalParam(description))
25
+ required.push(k);
26
+ }
27
+ const price = Number(s.price_usd) || 0;
28
+ const cost = price > 0
29
+ ? `PAID: $${price.toFixed(2)} USDC per call, settled on Base via x402 from the wallet in X420_MCP_WALLET_PRIVATE_KEY (real money).`
30
+ : "Free call.";
31
+ const example = s.examples?.input ? ` Example input: ${JSON.stringify(s.examples.input)}.` : "";
32
+ const description = `${s.name}: ${s.description} ${cost} Returns: ${s.output ?? "JSON"} - the deliverable plus X420's signed receipt and the settlement transaction.${example}`;
33
+ return { name: toolName(s.id), service: s, description, inputSchema: { type: "object", properties, required, additionalProperties: false } };
34
+ }
35
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"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AO,GAAG,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,mBAAmB,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IAChG,MAAM,WAAW,GAAG,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,WAAW,IAAI,IAAI,aAAa,CAAC,CAAC,MAAM,IAAI,MAAM,gFAAgF,OAAO,EAAE,CAAC;IAChL,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,WAAW,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,oBAAoB,EAAE,KAAK,EAAE,EAAE,CAAC;AAC/I,CAAC"}
package/dist/cli.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `x420-mcp`: run X420's services as MCP tools over stdio. Settings come from the environment (see docs/mcp-server.md):
4
+ * X420_MCP_ORIGIN, X420_MCP_WALLET_PRIVATE_KEY, X420_MCP_MAX_USD, X420_MCP_NETWORK.
5
+ */
6
+ import { startStdio } from "./server.js";
7
+ startStdio().catch((e) => {
8
+ process.stderr.write(`x420-mcp: ${e.message}\n`);
9
+ process.exit(1);
10
+ });
11
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../../src/mcp/cli.ts"],"names":[],"mappings":";AACA;;;GAGG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,UAAU,EAAE,CAAC,KAAK,CAAC,CAAC,CAAU,EAAE,EAAE;IAChC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,aAAc,CAAW,CAAC,OAAO,IAAI,CAAC,CAAC;IAC5D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
package/dist/hosted.js ADDED
@@ -0,0 +1,118 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
4
+ import { fetchCatalog, serviceTool, trimOrigin } from "./catalog.js";
5
+ import { CATALOG_TOOL, callFreeTool, freeTools, missingInputResult, serviceRequest, text } from "./tools.js";
6
+ export const HOSTED_SERVER_NAME = "x420-mcp-hosted";
7
+ export const HOSTED_SERVER_VERSION = "1.0.0";
8
+ export const DEFAULT_CACHE_MS = 60_000;
9
+ export const PAY_HOW = "GET the url; read PAYMENT-REQUIRED from the 402; retry with PAYMENT-SIGNATURE (x402 v2). Or run the local x420-mcp server with your own wallet key to pay automatically.";
10
+ export async function fetchPayments(origin, fetchImpl = fetch) {
11
+ const res = await fetchImpl(`${trimOrigin(origin)}/.well-known/agent.json`, { headers: { accept: "application/json" } });
12
+ if (!res.ok)
13
+ throw new Error(`agent card answered HTTP ${res.status}`);
14
+ const card = (await res.json());
15
+ const p = card.payments ?? {};
16
+ return { network: p.network ?? "base", network_caip2: p.network_caip2 ?? null, pay_to: p.pay_to ?? null, currency: p.currency ?? "USDC" };
17
+ }
18
+ /** The hosted description: the same facts as the local tool, then what this endpoint actually returns. */
19
+ export function hostedDescription(t) {
20
+ const s = t.service;
21
+ const price = Number(s.price_usd) || 0;
22
+ return `${s.name}: ${s.description} Price: $${price.toFixed(2)} USDC per call (x402 on Base). This hosted tool does NOT pay and does NOT return the deliverable: it validates the input and returns payment instructions (pay_to, network, price and the x402 URL to pay at). ${PAY_HOW} Deliverable once paid: ${s.output ?? "JSON"}.`;
23
+ }
24
+ export function createHostedMcpHandler(opts) {
25
+ const origin = trimOrigin(opts.origin);
26
+ const fetchImpl = opts.fetchImpl ?? fetch;
27
+ const cacheMs = opts.cacheMs ?? DEFAULT_CACHE_MS;
28
+ const loadCatalog = opts.catalog ?? (() => fetchCatalog(origin, fetchImpl));
29
+ const loadPayments = opts.payments ?? (() => fetchPayments(origin, fetchImpl));
30
+ let snap = null;
31
+ let loading = null;
32
+ const snapshot = async () => {
33
+ if (snap && Date.now() - snap.at < cacheMs)
34
+ return snap;
35
+ if (!loading) {
36
+ loading = (async () => {
37
+ try {
38
+ const [catalog, payments] = await Promise.all([loadCatalog(), loadPayments()]);
39
+ const serviceTools = new Map();
40
+ for (const s of catalog.services) {
41
+ const t = serviceTool(s);
42
+ serviceTools.set(t.name, t);
43
+ }
44
+ const tools = [
45
+ ...freeTools(origin, catalog),
46
+ ...[...serviceTools.values()].map((t) => ({ name: t.name, description: hostedDescription(t), inputSchema: t.inputSchema, annotations: { title: t.service.name, readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true } })),
47
+ ];
48
+ snap = { at: Date.now(), catalog, payments, tools, serviceTools };
49
+ return snap;
50
+ }
51
+ catch (e) {
52
+ if (snap)
53
+ return snap; // a stale snapshot beats an outage
54
+ throw e;
55
+ }
56
+ finally {
57
+ loading = null;
58
+ }
59
+ })();
60
+ }
61
+ return loading;
62
+ };
63
+ const buildServer = (s) => {
64
+ const server = new Server({ name: HOSTED_SERVER_NAME, version: HOSTED_SERVER_VERSION }, { capabilities: { tools: {} }, instructions: `X420 agent services (${s.catalog.agent || origin}), hosted endpoint. Paid tools here return x402 payment instructions, not deliverables; pay with your own x402 client or run the local x420-mcp with your wallet key. x420_catalog and x420_quote are free.` });
65
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: s.tools }));
66
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
67
+ const name = req.params.name;
68
+ const args = (req.params.arguments ?? {});
69
+ try {
70
+ const free = await callFreeTool(name, args, origin, s.catalog, fetchImpl);
71
+ if (free)
72
+ return free;
73
+ const t = s.serviceTools.get(name);
74
+ if (!t)
75
+ return text(`unknown tool ${name}; call ${CATALOG_TOOL} to list X420's services`, true);
76
+ const request = serviceRequest(origin, t, args);
77
+ if ("missing" in request)
78
+ return missingInputResult(t, request.missing);
79
+ return text({
80
+ pay_required: true,
81
+ service: t.service.id,
82
+ price_usd: Number(t.service.price_usd) || 0,
83
+ currency: s.payments.currency,
84
+ network: s.payments.network_caip2 ?? s.payments.network,
85
+ pay_to: s.payments.pay_to,
86
+ url: request.url,
87
+ how: PAY_HOW,
88
+ });
89
+ }
90
+ catch (e) {
91
+ return text(`${name} failed: ${e.message}`, true);
92
+ }
93
+ });
94
+ return server;
95
+ };
96
+ return async (req, res) => {
97
+ let server = null;
98
+ let transport = null;
99
+ try {
100
+ const s = await snapshot();
101
+ server = buildServer(s);
102
+ transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
103
+ res.on("close", () => { void transport?.close(); void server?.close(); });
104
+ await server.connect(transport);
105
+ await transport.handleRequest(req, res, req.body);
106
+ }
107
+ catch (e) {
108
+ if (!res.headersSent) {
109
+ res.statusCode = 500;
110
+ res.setHeader("content-type", "application/json");
111
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: `x420 mcp: ${e.message}` }, id: null }));
112
+ }
113
+ else if (!res.writableEnded)
114
+ res.end();
115
+ }
116
+ };
117
+ }
118
+ //# sourceMappingURL=hosted.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hosted.js","sourceRoot":"","sources":["../../../src/mcp/hosted.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAkC,MAAM,oCAAoC,CAAC;AACnI,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAkC,MAAM,cAAc,CAAC;AACrG,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,SAAS,EAAE,kBAAkB,EAAE,cAAc,EAAE,IAAI,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I,CAAC,SAAS,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,aAAc,CAAW,CAAC,OAAO,EAAE,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;YAC/H,CAAC;iBAAM,IAAI,CAAC,GAAG,CAAC,aAAa;gBAAE,GAAG,CAAC,GAAG,EAAE,CAAC;QAC3C,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/dist/pay.js ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The paid step of a tool call: a GET that the seller answers with 402 (x402 v2 PAYMENT-REQUIRED) and, once a signed
3
+ * USDC authorization is attached as PAYMENT-SIGNATURE, with 200 and a PAYMENT-RESPONSE settlement header. The step is
4
+ * a function value (`PayFn`) so tests inject a stand-in and never touch a chain; the real one wraps fetch with the
5
+ * official `@x402/fetch` client and the `@x402/evm` exact scheme, signing with the key from the environment.
6
+ *
7
+ * The private key is read from X420_MCP_WALLET_PRIVATE_KEY only, lives in this process only, is never logged and is
8
+ * never sent anywhere: the seller sees a signed EIP-3009 authorization, not the key.
9
+ */
10
+ export const KEY_ENV = "X420_MCP_WALLET_PRIVATE_KEY";
11
+ export const MAX_ENV = "X420_MCP_MAX_USD";
12
+ export const ORIGIN_ENV = "X420_MCP_ORIGIN";
13
+ export const NETWORK_ENV = "X420_MCP_NETWORK";
14
+ export const DEFAULT_ORIGIN = "https://signature-theme.com";
15
+ export const DEFAULT_MAX_USD = 1;
16
+ /** Base mainnet, where X420 sells. A 402 asking for any other network is refused before signing. */
17
+ export const DEFAULT_NETWORK = "eip155:8453";
18
+ export const USDC_DECIMALS = 6;
19
+ const USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
20
+ export const isPrivateKey = (k) => typeof k === "string" && /^0x[0-9a-fA-F]{64}$/.test(k);
21
+ export function missingKeyMessage() {
22
+ return `${KEY_ENV} is not set, so this paid tool cannot run. Set it in the MCP server's environment to the 0x-prefixed private key of a wallet holding USDC on Base (eip155:8453), then restart the server. Every paid call spends real USDC from that wallet; ${MAX_ENV} (default $${DEFAULT_MAX_USD.toFixed(2)}) caps each call. X420 never receives the key: it stays in this local process and only signs payment authorizations.`;
23
+ }
24
+ /** Decode a response body as JSON when it is JSON, else keep the text. */
25
+ export async function readBody(res) {
26
+ const text = await res.text();
27
+ try {
28
+ return JSON.parse(text);
29
+ }
30
+ catch {
31
+ return text;
32
+ }
33
+ }
34
+ const isUsdc = (r) => r.asset.toLowerCase() === USDC_BASE.toLowerCase() || /^(usdc|usd coin)$/i.test(String(r.extra?.name ?? ""));
35
+ /**
36
+ * The real payer. Policy sits in the requirement selector: exact scheme only, the configured network only, USDC only,
37
+ * and the 402's amount within `maxUsd` even when the catalog price said less. The SDK's own default spend control
38
+ * ($1 per payment) is replaced by that cap so the user's X420_MCP_MAX_USD is the single number that matters.
39
+ */
40
+ export function createX402Payer(privateKey, opts = {}) {
41
+ if (!isPrivateKey(privateKey))
42
+ throw new Error(`${KEY_ENV} must be a 0x-prefixed 64-hex-character private key`);
43
+ const network = opts.network ?? DEFAULT_NETWORK;
44
+ const fetchImpl = opts.fetchImpl ?? fetch;
45
+ return async (url, maxUsd) => {
46
+ const { privateKeyToAccount } = await import("viem/accounts");
47
+ const { wrapFetchWithPayment, x402Client, decodePaymentResponseHeader } = await import("@x402/fetch");
48
+ const { registerExactEvmScheme } = await import("@x402/evm/exact/client");
49
+ let chosen = null;
50
+ const select = (_version, reqs) => {
51
+ if (!reqs.length)
52
+ throw new Error("402 carries no payment requirements");
53
+ const exact = reqs.filter((r) => r.scheme === "exact");
54
+ if (!exact.length)
55
+ throw new Error("402 offers no exact-scheme requirement");
56
+ const onNetwork = exact.filter((r) => r.network === network);
57
+ if (!onNetwork.length)
58
+ throw new Error(`402 wants payment on ${[...new Set(exact.map((r) => r.network))].join("/")}; this server pays on ${network} only (${NETWORK_ENV})`);
59
+ const r = onNetwork.find(isUsdc);
60
+ if (!r)
61
+ throw new Error(`402 asks for asset ${onNetwork[0].asset}; this server pays USDC only`);
62
+ const amount = Number(r.amount) / 10 ** USDC_DECIMALS;
63
+ if (!(amount <= maxUsd))
64
+ throw new Error(`402 asks for $${amount} USDC, above the per-call cap ${MAX_ENV}=$${maxUsd}`);
65
+ chosen = r;
66
+ return r;
67
+ };
68
+ const account = privateKeyToAccount(privateKey);
69
+ const client = new x402Client(select);
70
+ registerExactEvmScheme(client, { signer: account, paymentRequirementsSelector: select });
71
+ client.setSpendControls(false);
72
+ const fetchWithPay = wrapFetchWithPayment(fetchImpl, client);
73
+ const res = await fetchWithPay(url, { headers: { accept: "application/json" } });
74
+ const body = await readBody(res);
75
+ let settlement = null;
76
+ const header = res.headers.get("PAYMENT-RESPONSE") ?? res.headers.get("X-PAYMENT-RESPONSE");
77
+ if (header) {
78
+ try {
79
+ const s = decodePaymentResponseHeader(header);
80
+ settlement = { success: Boolean(s.success), transaction: s.transaction || null, network: s.network ?? null, payer: s.payer ?? account.address, error: s.errorReason ? `${s.errorReason}${s.errorMessage ? `: ${s.errorMessage}` : ""}` : null };
81
+ }
82
+ catch (e) {
83
+ settlement = { success: false, transaction: null, network: null, payer: account.address, error: `settlement header unreadable: ${e.message}` };
84
+ }
85
+ }
86
+ const paid = chosen ? Number(chosen.amount) / 10 ** USDC_DECIMALS : 0;
87
+ return { status: res.status, body, settlement, paid_usd: res.ok && settlement?.success ? paid : 0 };
88
+ };
89
+ }
90
+ //# sourceMappingURL=pay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pay.js","sourceRoot":"","sources":["../../../src/mcp/pay.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,6BAA6B,CAAC;AACrD,MAAM,CAAC,MAAM,OAAO,GAAG,kBAAkB,CAAC;AAC1C,MAAM,CAAC,MAAM,UAAU,GAAG,iBAAiB,CAAC;AAC5C,MAAM,CAAC,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the user's own wallet. The catalog is read live at start (one tool per service, see catalog.ts), two free tools
4
+ * expose the catalog and quotes, and every paid call is gated twice: the catalog price against X420_MCP_MAX_USD
5
+ * before any request, and the 402's own amount inside the payment selector (pay.ts). Stdio transport: nothing but
6
+ * protocol goes to stdout; status lines go to stderr; the key goes nowhere. The hosted, non-paying variant for public
7
+ * directories is hosted.ts.
8
+ */
9
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
10
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
12
+ import { fetchCatalog, serviceTool, trimOrigin } from "./catalog.js";
13
+ import { DEFAULT_MAX_USD, DEFAULT_NETWORK, DEFAULT_ORIGIN, KEY_ENV, MAX_ENV, NETWORK_ENV, ORIGIN_ENV, createX402Payer, isPrivateKey, missingKeyMessage, readBody } from "./pay.js";
14
+ import { CATALOG_TOOL, QUOTE_TOOL, callFreeTool, freeTools, missingInputResult, serviceRequest, text } from "./tools.js";
15
+ export { CATALOG_TOOL, QUOTE_TOOL };
16
+ export const SERVER_NAME = "x420-mcp";
17
+ export const SERVER_VERSION = "1.0.0";
18
+ /** Read the server's settings from the environment. The key value is returned, never printed. */
19
+ export function optionsFromEnv(env = process.env) {
20
+ const max = env[MAX_ENV] === undefined || env[MAX_ENV] === "" ? DEFAULT_MAX_USD : Number(env[MAX_ENV]);
21
+ if (!Number.isFinite(max) || max < 0)
22
+ throw new Error(`${MAX_ENV} must be a non-negative number of US dollars (got ${JSON.stringify(env[MAX_ENV])})`);
23
+ const key = env[KEY_ENV];
24
+ if (key && !isPrivateKey(key))
25
+ throw new Error(`${KEY_ENV} is set but is not a 0x-prefixed 64-hex-character private key`);
26
+ return { origin: env[ORIGIN_ENV] || DEFAULT_ORIGIN, maxUsd: max, privateKey: key || null, network: env[NETWORK_ENV] || DEFAULT_NETWORK };
27
+ }
28
+ export async function createX420McpServer(opts = {}) {
29
+ const origin = trimOrigin(opts.origin ?? DEFAULT_ORIGIN);
30
+ const maxUsd = opts.maxUsd ?? DEFAULT_MAX_USD;
31
+ const fetchImpl = opts.fetchImpl ?? fetch;
32
+ const log = opts.log ?? ((line) => process.stderr.write(`${line}\n`));
33
+ const payer = opts.payer ?? (opts.privateKey ? createX402Payer(opts.privateKey, { network: opts.network, fetchImpl }) : null);
34
+ const catalog = await fetchCatalog(origin, fetchImpl);
35
+ const serviceTools = new Map();
36
+ for (const s of catalog.services) {
37
+ const t = serviceTool(s);
38
+ serviceTools.set(t.name, t);
39
+ }
40
+ const tools = [
41
+ ...freeTools(origin, catalog),
42
+ ...[...serviceTools.values()].map((t) => ({
43
+ name: t.name,
44
+ description: t.description,
45
+ inputSchema: t.inputSchema,
46
+ annotations: { title: t.service.name, readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
47
+ })),
48
+ ];
49
+ const server = new Server({ name: SERVER_NAME, version: SERVER_VERSION }, { capabilities: { tools: {} }, instructions: `X420 agent services (${catalog.agent || origin}). Paid tools spend real USDC on Base via x402 from the user's wallet; each call is capped at $${maxUsd.toFixed(2)} (${MAX_ENV}). Check x420_catalog for prices first.` });
50
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
51
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
52
+ const name = req.params.name;
53
+ const args = (req.params.arguments ?? {});
54
+ try {
55
+ const free = await callFreeTool(name, args, origin, catalog, fetchImpl);
56
+ if (free)
57
+ return free;
58
+ const t = serviceTools.get(name);
59
+ if (!t)
60
+ return text(`unknown tool ${name}; call ${CATALOG_TOOL} to list X420's services`, true);
61
+ return await callService(t, args);
62
+ }
63
+ catch (e) {
64
+ return text(`${name} failed: ${e.message}`, true);
65
+ }
66
+ });
67
+ async function callService(t, args) {
68
+ const s = t.service;
69
+ const price = Number(s.price_usd) || 0;
70
+ if (price > maxUsd)
71
+ return text(`refused: ${s.id} costs $${price.toFixed(2)} USDC per call, above the per-call cap ${MAX_ENV}=$${maxUsd.toFixed(2)}. Raise ${MAX_ENV} in the MCP server's environment (and restart it) only if you mean to spend that much per call.`, true);
72
+ const request = serviceRequest(origin, t, args);
73
+ if ("missing" in request)
74
+ return missingInputResult(t, request.missing);
75
+ const { url } = request;
76
+ if (price > 0 && !payer)
77
+ return text(missingKeyMessage(), true);
78
+ const result = payer && price > 0
79
+ ? await payer(url, maxUsd)
80
+ : await (async () => { const r = await fetchImpl(url, { headers: { accept: "application/json" } }); return { status: r.status, body: await readBody(r), settlement: null, paid_usd: 0 }; })();
81
+ const body = (result.body && typeof result.body === "object" ? result.body : { raw: result.body });
82
+ if (result.status !== 200) {
83
+ log(`${s.id} -> HTTP ${result.status}`);
84
+ return text({ error: `${s.id} answered HTTP ${result.status}`, ...(result.status === 402 ? { hint: "the payment was not accepted; nothing was delivered" } : {}), response: body, settlement: result.settlement }, true);
85
+ }
86
+ log(`${s.id} -> delivered${result.settlement?.transaction ? ` tx ${result.settlement.transaction}` : ""}${result.paid_usd ? ` ($${result.paid_usd} USDC)` : ""}`);
87
+ return text({
88
+ service: s.id,
89
+ price_usd: price,
90
+ paid_usd: result.paid_usd,
91
+ deliverable: body.deliverable ?? body,
92
+ receipt: body.receipt ?? null,
93
+ order: body.order ?? null,
94
+ settlement: result.settlement ? { transaction: result.settlement.transaction, network: result.settlement.network, payer: result.settlement.payer, success: result.settlement.success, error: result.settlement.error } : null,
95
+ });
96
+ }
97
+ log(`${SERVER_NAME}: ${serviceTools.size} service tool(s) from ${origin}; cap $${maxUsd.toFixed(2)}/call; wallet ${payer ? "configured" : `not configured (set ${KEY_ENV} to enable paid tools)`}`);
98
+ return { server, catalog, tools, serviceTools, origin, maxUsd };
99
+ }
100
+ /** Entry point for the CLI: settings from the environment, catalog from the origin, then serve on stdio. */
101
+ export async function startStdio(env = process.env) {
102
+ const s = await createX420McpServer(optionsFromEnv(env));
103
+ await s.server.connect(new StdioServerTransport());
104
+ return s;
105
+ }
106
+ //# sourceMappingURL=server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ClE,CAAC;AAED,4GAA4G;AAC5G,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,MAAyB,OAAO,CAAC,GAAG;IACnE,MAAM,CAAC,GAAG,MAAM,mBAAmB,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC;IACzD,MAAM,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAC;IACnD,OAAO,CAAC,CAAC;AACX,CAAC"}
package/dist/tools.js ADDED
@@ -0,0 +1,73 @@
1
+ import { fetchCatalog } from "./catalog.js";
2
+ import { readBody } from "./pay.js";
3
+ export const CATALOG_TOOL = "x420_catalog";
4
+ export const QUOTE_TOOL = "x420_quote";
5
+ export const text = (value, isError = false) => ({ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }], ...(isError ? { isError: true } : {}) });
6
+ /** The rails a quote may name; x402 is the one this server pays on. */
7
+ export const railsOf = (catalog) => (catalog.rails.length ? catalog.rails : ["x402"]);
8
+ export const defaultRail = (rails) => (rails.includes("x402") ? "x402" : rails[0]);
9
+ /** `x420_catalog` and `x420_quote`, identical on both servers. */
10
+ export function freeTools(origin, catalog) {
11
+ const rails = railsOf(catalog);
12
+ return [
13
+ {
14
+ name: CATALOG_TOOL,
15
+ description: `Free. Fetches X420's live service catalog from ${origin}/a2a/catalog: every service with its id, price in USD, input parameters and deliverable. Use it to see what the x420_* tools cost before calling one.`,
16
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
17
+ annotations: { readOnlyHint: true, openWorldHint: true },
18
+ },
19
+ {
20
+ name: QUOTE_TOOL,
21
+ description: `Free. Asks X420 for a price quote (POST ${origin}/a2a/quote) for one service and input: amount in USD, currency, rail, pay-to address, nonce and expiry. A quote costs nothing and does not place an order.`,
22
+ inputSchema: {
23
+ type: "object",
24
+ properties: {
25
+ service: { type: "string", description: `service id from the catalog, e.g. ${catalog.services[0]?.id ?? "sitescan.check"}` },
26
+ input: { type: "object", description: "the service's input parameters (string values), exactly as you would pass to its tool", additionalProperties: { type: "string" } },
27
+ rail: { type: "string", enum: rails, description: `payment rail; default ${defaultRail(rails)}` },
28
+ },
29
+ required: ["service"],
30
+ additionalProperties: false,
31
+ },
32
+ annotations: { readOnlyHint: true, openWorldHint: true },
33
+ },
34
+ ];
35
+ }
36
+ /** Run one of the free tools; returns null when `name` is neither. */
37
+ export async function callFreeTool(name, args, origin, catalog, fetchImpl) {
38
+ if (name === CATALOG_TOOL)
39
+ return text(await fetchCatalog(origin, fetchImpl));
40
+ if (name === QUOTE_TOOL)
41
+ return text(await quote(origin, fetchImpl, args, railsOf(catalog)));
42
+ return null;
43
+ }
44
+ export async function quote(origin, fetchImpl, args, rails) {
45
+ const service = String(args.service ?? "");
46
+ if (!service)
47
+ throw new Error("quote needs a service id");
48
+ const rail = args.rail ? String(args.rail) : defaultRail(rails);
49
+ const input = args.input && typeof args.input === "object" ? args.input : {};
50
+ const res = await fetchImpl(`${origin}/a2a/quote`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify({ service, input, rail }) });
51
+ const body = await readBody(res);
52
+ if (!res.ok)
53
+ throw new Error(`quote answered HTTP ${res.status}: ${typeof body === "string" ? body : JSON.stringify(body)}`);
54
+ return body;
55
+ }
56
+ const present = (v) => v !== undefined && v !== null && v !== "";
57
+ /**
58
+ * Check a call's arguments against the service tool's schema. Either the names of the missing required parameters,
59
+ * or the paid URL (`<origin>/a2a/x402/<id>?<params>`, known parameters only, optional ones only when given).
60
+ */
61
+ export function serviceRequest(origin, t, args) {
62
+ const missing = t.inputSchema.required.filter((k) => !present(args[k]));
63
+ if (missing.length)
64
+ return { missing };
65
+ const params = {};
66
+ for (const k of Object.keys(t.inputSchema.properties))
67
+ if (present(args[k]))
68
+ params[k] = String(args[k]);
69
+ const qs = new URLSearchParams(params);
70
+ return { url: `${origin}/a2a/x402/${encodeURIComponent(t.service.id)}${qs.size ? `?${qs}` : ""}`, params };
71
+ }
72
+ export const missingInputResult = (t, missing) => text(`missing required input: ${missing.join(", ")} (${t.service.id} takes ${Object.keys(t.inputSchema.properties).join(", ")})`, true);
73
+ //# sourceMappingURL=tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/mcp/tools.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,YAAY,EAAkC,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEpC,MAAM,CAAC,MAAM,YAAY,GAAG,cAAc,CAAC;AAC3C,MAAM,CAAC,MAAM,UAAU,GAAG,YAAY,CAAC;AAEvC,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,KAAc,EAAE,OAAO,GAAG,KAAK,EAAkB,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AAE5N,uEAAuE;AACvE,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,OAAgB,EAAY,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AACzG,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,KAAe,EAAU,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAErG,kEAAkE;AAClE,M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2BAA2B,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,EAAE,UAAU,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "x420-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "MCP server for X420's pay-per-call agent services (x402, USDC on Base, paid from your own wallet).",
5
+ "mcpName": "com.signature-theme/x420-mcp",
6
+ "type": "module",
7
+ "license": "MIT",
8
+ "author": "BodhiNath",
9
+ "homepage": "https://signature-theme.com",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/BodhiNath/X420",
13
+ "directory": "packages/x420-mcp"
14
+ },
15
+ "bugs": "https://github.com/BodhiNath/X420/issues",
16
+ "keywords": [
17
+ "mcp",
18
+ "x402",
19
+ "agent",
20
+ "usdc",
21
+ "base",
22
+ "pay-per-call"
23
+ ],
24
+ "bin": {
25
+ "x420-mcp": "./dist/cli.js"
26
+ },
27
+ "main": "./dist/server.js",
28
+ "exports": {
29
+ ".": "./dist/server.js",
30
+ "./hosted": "./dist/hosted.js",
31
+ "./catalog": "./dist/catalog.js",
32
+ "./pay": "./dist/pay.js"
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "README.md"
37
+ ],
38
+ "engines": {
39
+ "node": ">=22"
40
+ },
41
+ "scripts": {
42
+ "build": "tsc -p tsconfig.json"
43
+ },
44
+ "dependencies": {
45
+ "@modelcontextprotocol/sdk": "1.32.2",
46
+ "@x402/core": "2.31.0",
47
+ "@x402/evm": "2.31.0",
48
+ "@x402/fetch": "2.31.0",
49
+ "viem": "2.57.16",
50
+ "zod": "4.6.7"
51
+ },
52
+ "devDependencies": {
53
+ "@types/node": "24.3.0",
54
+ "typescript": "5.9.2"
55
+ }
56
+ }