turnstiles-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/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ Proprietary License
2
+
3
+ Copyright (c) 2026 Matthew Pausley. All rights reserved.
4
+
5
+ This package ("turnstiles-mcp") is proprietary software.
6
+
7
+ Permission is granted to install and run this package, unmodified, for the
8
+ sole purpose of accessing Turnstiles services (turnstiles.dev).
9
+
10
+ You may not, without prior written permission from the copyright holder:
11
+ - copy, modify, merge, publish, distribute, sublicense or sell this package
12
+ or any part of it;
13
+ - decompile, disassemble or reverse engineer it, except where applicable law
14
+ permits this despite this restriction;
15
+ - use it, or anything derived from it, to build or operate a product or
16
+ service that competes with Turnstiles.
17
+
18
+ THIS PACKAGE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
20
+ PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE
21
+ FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE PACKAGE OR ITS USE. Responses from Turnstiles are measurements, not
23
+ trading, financial or legal advice.
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,9 @@
1
+ #!/usr/bin/env node
2
+ import { X402LaunchpadMcpServer } from "./server.js";
3
+ const server = new X402LaunchpadMcpServer({
4
+ baseUrl: process.env.X402_API_URL ?? "https://turnstiles.dev",
5
+ agentPrivateKey: process.env.AGENT_PRIVATE_KEY,
6
+ maxAutoPayUsdc: process.env.MAX_AUTO_PAY_USDC ? Number(process.env.MAX_AUTO_PAY_USDC) : 0.05,
7
+ preferVampireAllowlist: process.env.PREFER_VAMPIRE_ALLOWLIST === "true", // parked: opt-in only
8
+ });
9
+ server.startStdio();
@@ -0,0 +1,130 @@
1
+ import type { PaymentRequired } from "@x402/core/types";
2
+ /** Base mainnet USDC: the default token for scans, not the settlement asset (that follows the 402 challenge) */
3
+ export declare const BASE_USDC_ADDRESS: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
4
+ export interface X402AgentClientOptions {
5
+ /** Base URL of the x402 API gateway (default: http://localhost:3000) */
6
+ baseUrl?: string;
7
+ /** EVM private key (0x...) that signs payments. The payer is always this key's address. */
8
+ agentPrivateKey?: string;
9
+ /** Maximum USDC (decimal, e.g., 0.05) allowed per automatic x402 payment */
10
+ maxAutoPayUsdc?: number;
11
+ /** Whether to attempt Phase 3 Vampire Allowlist headers first before signing a paid x402 payload */
12
+ preferVampireAllowlist?: boolean;
13
+ /** Custom fetch implementation (allows direct Hono app.fetch injection in tests/headless mode) */
14
+ fetchFn?: typeof fetch;
15
+ /** Maximum polling attempts when an endpoint returns HTTP 202 Accepted */
16
+ maxAsyncPollAttempts?: number;
17
+ /** Delay in ms between HTTP 202 status polls */
18
+ asyncPollIntervalMs?: number;
19
+ }
20
+ export declare class X402BudgetExceededError extends Error {
21
+ readonly requestedUsdc: number;
22
+ readonly maxAutoPayUsdc: number;
23
+ constructor(requestedUsdc: number, maxAutoPayUsdc: number);
24
+ }
25
+ export declare class X402AgentClient {
26
+ readonly baseUrl: string;
27
+ readonly maxAutoPayUsdc: number;
28
+ readonly preferVampireAllowlist: boolean;
29
+ readonly walletAddress: string;
30
+ private readonly account;
31
+ private readonly httpClient;
32
+ private readonly fetchFn;
33
+ private readonly maxAsyncPollAttempts;
34
+ private readonly asyncPollIntervalMs;
35
+ constructor(options?: X402AgentClientOptions);
36
+ /**
37
+ * Signs a lightweight EIP-191 proof of ownership header for the Phase 3 Vampire Allowlist
38
+ */
39
+ signVampireAllowlistHeaders(resourcePath: string): Promise<{
40
+ "X-AGENT-WALLET": string;
41
+ "X-AGENT-SIGNATURE": string;
42
+ "X-AGENT-NONCE": string;
43
+ }>;
44
+ /**
45
+ * Turns a 402 response into a signed PAYMENT-SIGNATURE header, after checking the price against MAX_AUTO_PAY_USDC.
46
+ */
47
+ createPaymentHeaders(response: Response): Promise<{
48
+ headers: Record<string, string>;
49
+ paymentRequired: PaymentRequired;
50
+ }>;
51
+ /**
52
+ * Executes a POST request to an x402 endpoint, automatically handling:
53
+ * 1. Vampire Allowlist fee-waiver headers (if enabled/eligible)
54
+ * 2. HTTP 402 Payment Required challenge parsing & budget check (MAX_AUTO_PAY_USDC)
55
+ * 3. EIP-3009 USDC authorization signing & retry with PAYMENT-SIGNATURE (x402 v2)
56
+ * 4. Idempotent HTTP 202 Accepted polling until completion
57
+ */
58
+ postWithAutoPay<TResponse = unknown>(path: string, body: Record<string, unknown>, options?: {
59
+ useVampireAllowlist?: boolean;
60
+ }): Promise<TResponse>;
61
+ private pollPendingOperation;
62
+ /**
63
+ * Tool 1: alpha_scan_token ($0.01 USDC on Base)
64
+ */
65
+ alphaScanToken(params: {
66
+ chain?: "base" | "solana" | "ethereum" | "arbitrum";
67
+ tokenAddress: string;
68
+ includeSocialCard?: boolean;
69
+ useVampireAllowlist?: boolean;
70
+ }): Promise<unknown>;
71
+ /**
72
+ * Tool 2: mev_shield_swap ($0.02 USDC on Base)
73
+ */
74
+ mevShieldSwap(params: {
75
+ chain?: "base" | "solana" | "ethereum" | "arbitrum";
76
+ mode?: "simulate_only" | "build" | "simulate_and_protect";
77
+ slippageBps?: number;
78
+ swap: {
79
+ tokenIn: string;
80
+ tokenOut: string;
81
+ amountInAtomic: string;
82
+ senderAddress?: string;
83
+ calldata?: string;
84
+ signedRawTx?: string;
85
+ };
86
+ useVampireAllowlist?: boolean;
87
+ }): Promise<unknown>;
88
+ /**
89
+ * Tool 3: check_agent_leaderboard_status (FREE)
90
+ */
91
+ checkAgentLeaderboardStatus(walletAddress?: string, options?: {
92
+ anonymous?: boolean;
93
+ }): Promise<any>;
94
+ /**
95
+ * Endpoint 3: Profile Wallet PnL ($0.01 USDC)
96
+ */
97
+ profileWalletPnl(payload: {
98
+ chain?: "base" | "solana" | "ethereum" | "arbitrum";
99
+ walletAddress: string;
100
+ tokenAddresses?: string[];
101
+ useVampireAllowlist?: boolean;
102
+ }): Promise<unknown>;
103
+ /**
104
+ * Endpoint 4: Predict Gas Fees ($0.005 USDC)
105
+ */
106
+ predictGasFees(payload?: {
107
+ chain?: "base" | "solana" | "ethereum" | "arbitrum";
108
+ speedPreference?: "economic" | "standard" | "instant";
109
+ useVampireAllowlist?: boolean;
110
+ }): Promise<unknown>;
111
+ /**
112
+ * Endpoint 5: Audit Contract Bytecode ($0.02 USDC)
113
+ */
114
+ auditContractBytecode(payload: {
115
+ chain?: "base" | "solana" | "ethereum" | "arbitrum";
116
+ contractAddress?: string;
117
+ bytecode?: string;
118
+ useVampireAllowlist?: boolean;
119
+ }): Promise<unknown>;
120
+ /**
121
+ * Endpoint 6: Token-Search ($0.005 USDC)
122
+ */
123
+ searchTokens(payload?: {
124
+ mode?: "search" | "trending" | "new_launches";
125
+ query?: string;
126
+ chain?: "base" | "solana" | "ethereum" | "arbitrum";
127
+ limit?: number;
128
+ useVampireAllowlist?: boolean;
129
+ }): Promise<unknown>;
130
+ }
package/dist/client.js ADDED
@@ -0,0 +1,246 @@
1
+ import crypto from "node:crypto";
2
+ import { isHex } from "viem";
3
+ import { privateKeyToAccount, generatePrivateKey } from "viem/accounts";
4
+ import { x402Client, x402HTTPClient } from "@x402/core/client";
5
+ import { ExactEvmScheme } from "@x402/evm/exact/client";
6
+ import { toClientEvmSigner } from "@x402/evm";
7
+ import { SETTLEMENT_NETWORKS, isSettlementNetwork } from "./networks.js";
8
+ /** Base mainnet USDC: the default token for scans, not the settlement asset (that follows the 402 challenge) */
9
+ export const BASE_USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
10
+ export class X402BudgetExceededError extends Error {
11
+ requestedUsdc;
12
+ maxAutoPayUsdc;
13
+ constructor(requestedUsdc, maxAutoPayUsdc) {
14
+ super(`x402 required payment ($${requestedUsdc.toFixed(6)} USDC) exceeds MAX_AUTO_PAY_USDC ($${maxAutoPayUsdc.toFixed(6)} USDC)`);
15
+ this.name = "X402BudgetExceededError";
16
+ this.requestedUsdc = requestedUsdc;
17
+ this.maxAutoPayUsdc = maxAutoPayUsdc;
18
+ }
19
+ }
20
+ export class X402AgentClient {
21
+ baseUrl;
22
+ maxAutoPayUsdc;
23
+ preferVampireAllowlist;
24
+ walletAddress;
25
+ account;
26
+ httpClient;
27
+ fetchFn;
28
+ maxAsyncPollAttempts;
29
+ asyncPollIntervalMs;
30
+ constructor(options = {}) {
31
+ this.baseUrl = (options.baseUrl ?? process.env.X402_API_URL ?? "http://localhost:3000").replace(/\/$/, "");
32
+ const envMax = process.env.MAX_AUTO_PAY_USDC ? Number(process.env.MAX_AUTO_PAY_USDC) : undefined;
33
+ this.maxAutoPayUsdc =
34
+ options.maxAutoPayUsdc ?? (envMax !== undefined && !Number.isNaN(envMax) ? envMax : 0.05);
35
+ this.preferVampireAllowlist = options.preferVampireAllowlist ?? false;
36
+ this.fetchFn = options.fetchFn ?? globalThis.fetch.bind(globalThis);
37
+ this.maxAsyncPollAttempts = options.maxAsyncPollAttempts ?? 15;
38
+ this.asyncPollIntervalMs = options.asyncPollIntervalMs ?? 60;
39
+ const rawKey = options.agentPrivateKey ?? process.env.AGENT_PRIVATE_KEY;
40
+ let privateKey;
41
+ if (rawKey && isHex(rawKey) && rawKey.length === 66) {
42
+ privateKey = rawKey;
43
+ }
44
+ else if (rawKey && isHex(`0x${rawKey}`) && rawKey.length === 64) {
45
+ privateKey = `0x${rawKey}`;
46
+ }
47
+ else {
48
+ privateKey = generatePrivateKey();
49
+ }
50
+ this.account = privateKeyToAccount(privateKey);
51
+ this.walletAddress = this.account.address.toLowerCase();
52
+ // Standard x402 v2 client: signs EIP-3009 `exact` payments, only on the networks Turnstiles settles on
53
+ const signer = toClientEvmSigner(this.account);
54
+ const core = x402Client.fromConfig({
55
+ schemes: Object.keys(SETTLEMENT_NETWORKS).map((network) => ({
56
+ network: network,
57
+ client: new ExactEvmScheme(signer),
58
+ })),
59
+ spendControls: { maxAmountPerPayment: `$${this.maxAutoPayUsdc}` },
60
+ });
61
+ this.httpClient = new x402HTTPClient(core);
62
+ }
63
+ /**
64
+ * Signs a lightweight EIP-191 proof of ownership header for the Phase 3 Vampire Allowlist
65
+ */
66
+ async signVampireAllowlistHeaders(resourcePath) {
67
+ const nonce = `vampire_${this.walletAddress}_${crypto.randomBytes(8).toString("hex")}`;
68
+ const message = `x402-vampire-waiver:${this.walletAddress}:${resourcePath}:${nonce}`;
69
+ const signature = await this.account.signMessage({ message });
70
+ return {
71
+ "X-AGENT-WALLET": this.walletAddress,
72
+ "X-AGENT-SIGNATURE": signature,
73
+ "X-AGENT-NONCE": nonce,
74
+ };
75
+ }
76
+ /**
77
+ * Turns a 402 response into a signed PAYMENT-SIGNATURE header, after checking the price against MAX_AUTO_PAY_USDC.
78
+ */
79
+ async createPaymentHeaders(response) {
80
+ let body;
81
+ try {
82
+ body = await response.clone().json();
83
+ }
84
+ catch {
85
+ body = undefined;
86
+ }
87
+ const paymentRequired = this.httpClient.getPaymentRequiredResponse((name) => response.headers.get(name), body);
88
+ const payable = paymentRequired.accepts.filter((accept) => accept.scheme === "exact" && isSettlementNetwork(accept.network));
89
+ if (payable.length === 0) {
90
+ throw new Error(`No supported x402 payment option in the 402 challenge (expected exact on ${Object.keys(SETTLEMENT_NETWORKS).join(" or ")})`);
91
+ }
92
+ const cheapestUsdc = Math.min(...payable.map((accept) => Number(BigInt(accept.amount)) / 1e6));
93
+ if (cheapestUsdc > this.maxAutoPayUsdc) {
94
+ throw new X402BudgetExceededError(cheapestUsdc, this.maxAutoPayUsdc);
95
+ }
96
+ const paymentPayload = await this.httpClient.createPaymentPayload({
97
+ ...paymentRequired,
98
+ accepts: payable,
99
+ });
100
+ return {
101
+ headers: this.httpClient.encodePaymentSignatureHeader(paymentPayload),
102
+ paymentRequired,
103
+ };
104
+ }
105
+ /**
106
+ * Executes a POST request to an x402 endpoint, automatically handling:
107
+ * 1. Vampire Allowlist fee-waiver headers (if enabled/eligible)
108
+ * 2. HTTP 402 Payment Required challenge parsing & budget check (MAX_AUTO_PAY_USDC)
109
+ * 3. EIP-3009 USDC authorization signing & retry with PAYMENT-SIGNATURE (x402 v2)
110
+ * 4. Idempotent HTTP 202 Accepted polling until completion
111
+ */
112
+ async postWithAutoPay(path, body, options) {
113
+ const url = `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
114
+ const tryVampire = options?.useVampireAllowlist ?? this.preferVampireAllowlist;
115
+ const initialHeaders = {
116
+ "Content-Type": "application/json",
117
+ };
118
+ if (tryVampire) {
119
+ const vampireHeaders = await this.signVampireAllowlistHeaders(path);
120
+ Object.assign(initialHeaders, vampireHeaders);
121
+ }
122
+ let response = await this.fetchFn(url, {
123
+ method: "POST",
124
+ headers: initialHeaders,
125
+ body: JSON.stringify(body),
126
+ });
127
+ // If unpaid or Vampire free calls exhausted, server returns HTTP 402 Payment Required
128
+ if (response.status === 402) {
129
+ const { headers: paymentHeaders } = await this.createPaymentHeaders(response);
130
+ response = await this.fetchFn(url, {
131
+ method: "POST",
132
+ headers: {
133
+ "Content-Type": "application/json",
134
+ ...paymentHeaders,
135
+ },
136
+ body: JSON.stringify(body),
137
+ });
138
+ }
139
+ // Handle HTTP 202 Accepted idempotent async recovery
140
+ if (response.status === 202) {
141
+ const pendingData = (await response.json());
142
+ return this.pollPendingOperation(pendingData.status_url);
143
+ }
144
+ if (!response.ok) {
145
+ const errBody = await response.text();
146
+ throw new Error(`x402 request failed with HTTP ${response.status}: ${errBody}`);
147
+ }
148
+ return (await response.json());
149
+ }
150
+ async pollPendingOperation(statusUrl) {
151
+ const fullUrl = statusUrl.startsWith("http")
152
+ ? statusUrl
153
+ : `${this.baseUrl}${statusUrl.startsWith("/") ? statusUrl : `/${statusUrl}`}`;
154
+ for (let attempt = 0; attempt < this.maxAsyncPollAttempts; attempt++) {
155
+ await new Promise((r) => setTimeout(r, this.asyncPollIntervalMs));
156
+ const pollRes = await this.fetchFn(fullUrl, { method: "GET" });
157
+ if (pollRes.status === 200) {
158
+ return (await pollRes.json());
159
+ }
160
+ if (pollRes.status !== 202) {
161
+ const text = await pollRes.text();
162
+ throw new Error(`Polling operation ${statusUrl} failed with HTTP ${pollRes.status}: ${text}`);
163
+ }
164
+ }
165
+ throw new Error(`Timed out waiting for async operation ${statusUrl} after ${this.maxAsyncPollAttempts} attempts`);
166
+ }
167
+ /**
168
+ * Tool 1: alpha_scan_token ($0.01 USDC on Base)
169
+ */
170
+ async alphaScanToken(params) {
171
+ return this.postWithAutoPay("/api/v1/quests/alpha-scan/resource", {
172
+ chain: params.chain ?? "base",
173
+ tokenAddress: params.tokenAddress,
174
+ includeSocialCard: params.includeSocialCard ?? true,
175
+ }, { useVampireAllowlist: params.useVampireAllowlist });
176
+ }
177
+ /**
178
+ * Tool 2: mev_shield_swap ($0.02 USDC on Base)
179
+ */
180
+ async mevShieldSwap(params) {
181
+ return this.postWithAutoPay("/api/v1/quests/mev-shield/resource", {
182
+ chain: params.chain ?? "base",
183
+ mode: params.mode ?? "simulate_only",
184
+ ...(params.slippageBps !== undefined ? { slippageBps: params.slippageBps } : {}),
185
+ swap: {
186
+ ...params.swap,
187
+ senderAddress: params.swap.senderAddress ?? this.walletAddress,
188
+ },
189
+ }, { useVampireAllowlist: params.useVampireAllowlist });
190
+ }
191
+ /**
192
+ * Tool 3: check_agent_leaderboard_status (FREE)
193
+ */
194
+ async checkAgentLeaderboardStatus(walletAddress, options = {}) {
195
+ const targetWallet = (walletAddress ?? this.walletAddress).toLowerCase();
196
+ const url = options.anonymous
197
+ ? `${this.baseUrl}/api/v1/leaderboard`
198
+ : `${this.baseUrl}/api/v1/leaderboard?wallet=${encodeURIComponent(targetWallet)}`;
199
+ const res = await this.fetchFn(url, { method: "GET" });
200
+ if (!res.ok) {
201
+ const errText = await res.text();
202
+ throw new Error(`Failed to fetch leaderboard status (HTTP ${res.status}): ${errText}`);
203
+ }
204
+ return (await res.json());
205
+ }
206
+ /**
207
+ * Endpoint 3: Profile Wallet PnL ($0.01 USDC)
208
+ */
209
+ async profileWalletPnl(payload) {
210
+ return this.postWithAutoPay("/api/v1/quests/wallet-pnl/resource", {
211
+ chain: payload.chain ?? "base",
212
+ walletAddress: payload.walletAddress,
213
+ tokenAddresses: payload.tokenAddresses,
214
+ }, { useVampireAllowlist: payload.useVampireAllowlist });
215
+ }
216
+ /**
217
+ * Endpoint 4: Predict Gas Fees ($0.005 USDC)
218
+ */
219
+ async predictGasFees(payload = {}) {
220
+ return this.postWithAutoPay("/api/v1/quests/gas-oracle/resource", {
221
+ chain: payload.chain ?? "base",
222
+ speedPreference: payload.speedPreference ?? "standard",
223
+ }, { useVampireAllowlist: payload.useVampireAllowlist });
224
+ }
225
+ /**
226
+ * Endpoint 5: Audit Contract Bytecode ($0.02 USDC)
227
+ */
228
+ async auditContractBytecode(payload) {
229
+ return this.postWithAutoPay("/api/v1/quests/contract-audit/resource", {
230
+ chain: payload.chain ?? "base",
231
+ contractAddress: payload.contractAddress,
232
+ bytecode: payload.bytecode,
233
+ }, { useVampireAllowlist: payload.useVampireAllowlist });
234
+ }
235
+ /**
236
+ * Endpoint 6: Token-Search ($0.005 USDC)
237
+ */
238
+ async searchTokens(payload = {}) {
239
+ return this.postWithAutoPay("/api/v1/quests/token-search/resource", {
240
+ mode: payload.mode ?? "search",
241
+ query: payload.query,
242
+ chain: payload.chain,
243
+ limit: payload.limit,
244
+ }, { useVampireAllowlist: payload.useVampireAllowlist });
245
+ }
246
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./client.js";
2
+ export * from "./networks.js";
3
+ export * from "./server.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./client.js";
2
+ export * from "./networks.js";
3
+ export * from "./server.js";
@@ -0,0 +1,15 @@
1
+ export declare const BASE_MAINNET_NETWORK: "eip155:8453";
2
+ export declare const BASE_SEPOLIA_NETWORK: "eip155:84532";
3
+ export type SettlementNetwork = typeof BASE_MAINNET_NETWORK | typeof BASE_SEPOLIA_NETWORK;
4
+ export interface SettlementNetworkInfo {
5
+ label: string;
6
+ usdcAddress: `0x${string}`;
7
+ testnet: boolean;
8
+ }
9
+ /** Networks Turnstiles can settle on. USDC addresses match the x402 default assets for each chain. */
10
+ export declare const SETTLEMENT_NETWORKS: Record<SettlementNetwork, SettlementNetworkInfo>;
11
+ /** Testnet by default, so a deploy that forgets X402_NETWORK can never take real USDC. */
12
+ export declare const DEFAULT_SETTLEMENT_NETWORK: SettlementNetwork;
13
+ export declare function isSettlementNetwork(value: string): value is SettlementNetwork;
14
+ /** Resolves an X402_NETWORK value. Unknown values throw so a typo fails loudly instead of settling elsewhere. */
15
+ export declare function resolveSettlementNetwork(value?: string): SettlementNetwork;
@@ -0,0 +1,29 @@
1
+ export const BASE_MAINNET_NETWORK = "eip155:8453";
2
+ export const BASE_SEPOLIA_NETWORK = "eip155:84532";
3
+ /** Networks Turnstiles can settle on. USDC addresses match the x402 default assets for each chain. */
4
+ export const SETTLEMENT_NETWORKS = {
5
+ [BASE_MAINNET_NETWORK]: {
6
+ label: "Base mainnet",
7
+ usdcAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
8
+ testnet: false,
9
+ },
10
+ [BASE_SEPOLIA_NETWORK]: {
11
+ label: "Base Sepolia testnet",
12
+ usdcAddress: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
13
+ testnet: true,
14
+ },
15
+ };
16
+ /** Testnet by default, so a deploy that forgets X402_NETWORK can never take real USDC. */
17
+ export const DEFAULT_SETTLEMENT_NETWORK = BASE_SEPOLIA_NETWORK;
18
+ export function isSettlementNetwork(value) {
19
+ return value in SETTLEMENT_NETWORKS;
20
+ }
21
+ /** Resolves an X402_NETWORK value. Unknown values throw so a typo fails loudly instead of settling elsewhere. */
22
+ export function resolveSettlementNetwork(value) {
23
+ if (!value)
24
+ return DEFAULT_SETTLEMENT_NETWORK;
25
+ if (!isSettlementNetwork(value)) {
26
+ throw new Error(`Unsupported X402_NETWORK "${value}". Expected one of: ${Object.keys(SETTLEMENT_NETWORKS).join(", ")}`);
27
+ }
28
+ return value;
29
+ }
@@ -0,0 +1,62 @@
1
+ import { X402AgentClient, X402AgentClientOptions } from "./client.js";
2
+ export interface McpToolDefinition {
3
+ name: "alpha_scan_token" | "mev_shield_swap" | "check_agent_leaderboard_status" | "profile_wallet_pnl" | "predict_gas_fees" | "audit_contract_bytecode" | "search_tokens";
4
+ description: string;
5
+ inputSchema: {
6
+ type: "object";
7
+ properties: Record<string, unknown>;
8
+ required?: string[];
9
+ };
10
+ }
11
+ export interface McpToolCallResult {
12
+ content: Array<{
13
+ type: "text";
14
+ text: string;
15
+ }>;
16
+ structuredContent?: unknown;
17
+ isError?: boolean;
18
+ }
19
+ export interface JsonRpcRequest {
20
+ jsonrpc: "2.0";
21
+ id?: string | number | null;
22
+ method: string;
23
+ params?: Record<string, unknown>;
24
+ }
25
+ export interface JsonRpcResponse {
26
+ jsonrpc: "2.0";
27
+ id: string | number | null;
28
+ result?: unknown;
29
+ error?: {
30
+ code: number;
31
+ message: string;
32
+ data?: unknown;
33
+ };
34
+ }
35
+ export declare const MCP_TOOLS: McpToolDefinition[];
36
+ /** Tools that call free endpoints. Everything else signs an x402 payment. */
37
+ export declare const FREE_MCP_TOOL_NAMES: ReadonlyArray<McpToolDefinition["name"]>;
38
+ export declare const LOCAL_PAID_TOOLS_HINT: string;
39
+ export interface X402LaunchpadMcpServerOptions extends X402AgentClientOptions {
40
+ /**
41
+ * Free tools only. The hosted /mcp and /sse routes use this: they never hold or accept a private key,
42
+ * so paid tools are not listed and calling one returns instructions for the local server.
43
+ */
44
+ freeToolsOnly?: boolean;
45
+ }
46
+ export declare class X402LaunchpadMcpServer {
47
+ readonly client: X402AgentClient;
48
+ readonly freeToolsOnly: boolean;
49
+ constructor(options?: X402LaunchpadMcpServerOptions);
50
+ listTools(): {
51
+ tools: McpToolDefinition[];
52
+ };
53
+ callTool(name: string, args?: Record<string, unknown>): Promise<McpToolCallResult>;
54
+ /**
55
+ * Handles a JSON-RPC 2.0 MCP message (initialize, tools/list, tools/call, ping)
56
+ */
57
+ handleJsonRpc(request: JsonRpcRequest): Promise<JsonRpcResponse | null>;
58
+ /**
59
+ * Starts the MCP server over stdio (newline-delimited JSON-RPC 2.0)
60
+ */
61
+ startStdio(): void;
62
+ }
package/dist/server.js ADDED
@@ -0,0 +1,464 @@
1
+ import readline from "node:readline";
2
+ import { X402AgentClient } from "./client.js";
3
+ export const MCP_TOOLS = [
4
+ {
5
+ name: "alpha_scan_token",
6
+ description: "Runs Alpha-Scan ($0.01 USDC via x402) for live token data: price, market cap, liquidity, 24h volume and trade counts (plus 5-minute, 1-hour and 6-hour windows) from DexScreener; a buy/sell simulation with tax bps from Honeypot.is (Base and Ethereum) or our own simulation against the deepest pool (Arbitrum, and where Honeypot.is has no answer); the share of that pool's LP token burned; mint and freeze authority status (Solana). Fields a source cannot supply are null. Measurements only, no grades or buy/sell signals.",
7
+ inputSchema: {
8
+ type: "object",
9
+ properties: {
10
+ chain: {
11
+ type: "string",
12
+ enum: ["base", "solana", "ethereum", "arbitrum"],
13
+ default: "base",
14
+ description: "Target token chain to scan",
15
+ },
16
+ tokenAddress: {
17
+ type: "string",
18
+ description: "EVM 0x contract address or Solana Base58 mint address",
19
+ },
20
+ includeSocialCard: {
21
+ type: "boolean",
22
+ default: false,
23
+ description: "Deprecated optional flag retained for backward compatibility",
24
+ },
25
+ },
26
+ required: ["tokenAddress"],
27
+ },
28
+ },
29
+ {
30
+ name: "mev_shield_swap",
31
+ description: "Runs MEV-Shield ($0.02 USDC via x402) for a live aggregator quote (KyberSwap on EVM, Jupiter on Solana): expected and minimum output, price impact bps, route split, and the most a sandwich could take at your slippage tolerance. In build mode it also returns the swap ready to sign (KyberSwap router transaction plus an exact approve() when needed on EVM, Jupiter's unsigned transaction on Solana). In simulate_and_protect mode it simulates your signed transaction against the chain and, if it succeeds, sends it to a private relay (Flashbots Protect, the Base or Arbitrum sequencer, or Jito); status is RELAYED only when the relay returns a transaction hash.",
32
+ inputSchema: {
33
+ type: "object",
34
+ properties: {
35
+ chain: {
36
+ type: "string",
37
+ enum: ["base", "solana", "ethereum", "arbitrum"],
38
+ default: "base",
39
+ description: "Target swap chain",
40
+ },
41
+ mode: {
42
+ type: "string",
43
+ enum: ["simulate_only", "build", "simulate_and_protect"],
44
+ default: "simulate_only",
45
+ description: "simulate_only: quote. build: quote plus the swap ready to sign for senderAddress. simulate_and_protect: simulate and privately relay signedRawTx",
46
+ },
47
+ tokenIn: {
48
+ type: "string",
49
+ description: "Input token contract/mint address",
50
+ },
51
+ tokenOut: {
52
+ type: "string",
53
+ description: "Output token contract/mint address",
54
+ },
55
+ amountInAtomic: {
56
+ type: "string",
57
+ description: "Input swap amount in atomic token units (positive integer string)",
58
+ },
59
+ senderAddress: {
60
+ type: "string",
61
+ description: "Optional sender wallet address (defaults to agent wallet)",
62
+ },
63
+ signedRawTx: {
64
+ type: "string",
65
+ description: "Required when mode is simulate_and_protect: your signed transaction (0x hex on EVM, base64 on Solana). It is simulated, then sent to a private relay. Signed by senderAddress.",
66
+ },
67
+ slippageBps: {
68
+ type: "number",
69
+ default: 50,
70
+ description: "Slippage tolerance in bps (1-5000); sets the minimum output and bounds sandwich exposure",
71
+ },
72
+ },
73
+ required: ["tokenIn", "tokenOut", "amountInAtomic"],
74
+ },
75
+ },
76
+ {
77
+ name: "profile_wallet_pnl",
78
+ description: "Realized and unrealized PnL for a wallet on one chain from Zerion (first in, first out): gains in USD and %, amount invested, cost basis and fees, plus a per-token breakdown for up to 25 tokenAddresses (\"native\" for the gas token). Costs $0.01 USDC.",
79
+ inputSchema: {
80
+ type: "object",
81
+ properties: {
82
+ chain: {
83
+ type: "string",
84
+ enum: ["base", "solana", "ethereum", "arbitrum"],
85
+ default: "base",
86
+ },
87
+ walletAddress: {
88
+ type: "string",
89
+ description: "EVM 0x wallet address or Solana Base58 public key to query",
90
+ },
91
+ tokenAddresses: {
92
+ type: "array",
93
+ items: { type: "string" },
94
+ maxItems: 25,
95
+ description: "Optional tokens to break PnL out for; \"native\" is the chain's gas token",
96
+ },
97
+ },
98
+ required: ["walletAddress"],
99
+ },
100
+ },
101
+ {
102
+ name: "predict_gas_fees",
103
+ description: "Runs Gas-Oracle ($0.005 USDC via x402) on the chain's own eth_feeHistory over about five minutes of blocks: next-block base fee, median priority fee for the chosen speed, base fee change and volatility over the window, an EIP-1559 max fee, and blob space on Ethereum.",
104
+ inputSchema: {
105
+ type: "object",
106
+ properties: {
107
+ chain: {
108
+ type: "string",
109
+ enum: ["base", "ethereum", "arbitrum"],
110
+ default: "base",
111
+ },
112
+ speedPreference: {
113
+ type: "string",
114
+ enum: ["economic", "standard", "instant"],
115
+ default: "standard",
116
+ },
117
+ },
118
+ },
119
+ },
120
+ {
121
+ name: "audit_contract_bytecode",
122
+ description: "Runs Contract-Audit ($0.02 USDC via x402) on deployed or supplied EVM bytecode: disassembles it, reports well-known privileged selectors (mint, pause, blacklist, fee setters, ownership, upgrade, withdraw), SELFDESTRUCT and DELEGATECALL instructions, and whether the address is a proxy (EIP-1967, beacon, EIP-1167), inspecting the implementation too. For a deployed address it also reports owner() and whether ownership is renounced (zero owner, Ownable pattern only) and the EIP-1967 admin. A selector's presence says the function exists, not who may call it.",
123
+ inputSchema: {
124
+ type: "object",
125
+ properties: {
126
+ chain: {
127
+ type: "string",
128
+ enum: ["base", "ethereum", "arbitrum"],
129
+ default: "base",
130
+ },
131
+ contractAddress: {
132
+ type: "string",
133
+ description: "Target contract address to inspect",
134
+ },
135
+ bytecode: {
136
+ type: "string",
137
+ description: "Optional raw hex bytecode to inspect",
138
+ },
139
+ },
140
+ },
141
+ },
142
+ {
143
+ name: "search_tokens",
144
+ description: "Runs Token-Search ($0.005 USDC via x402). In search mode it resolves a ticker, name or token address (DexScreener) to token addresses, one result per token at its deepest pool, deepest first; copies of a token with the same ticker are ranked below by liquidity, so pick by address and liquidity, not symbol alone. In trending or new_launches mode it lists a chain's trending or newest pools (GeckoTerminal), which need a chain. Each result carries price, liquidity, 24h volume, market cap, FDV, pair address and dex; brand-new launches often have null liquidity.",
145
+ inputSchema: {
146
+ type: "object",
147
+ properties: {
148
+ mode: {
149
+ type: "string",
150
+ enum: ["search", "trending", "new_launches"],
151
+ default: "search",
152
+ description: "search: look up query. trending or new_launches: list the chain's pools",
153
+ },
154
+ query: {
155
+ type: "string",
156
+ maxLength: 64,
157
+ description: "Ticker, name or token address (search mode)",
158
+ },
159
+ chain: {
160
+ type: "string",
161
+ enum: ["base", "solana", "ethereum", "arbitrum"],
162
+ description: "Required for trending and new_launches; for search, limits results to this chain",
163
+ },
164
+ limit: {
165
+ type: "integer",
166
+ minimum: 1,
167
+ maximum: 25,
168
+ default: 10,
169
+ description: "Maximum results to return",
170
+ },
171
+ },
172
+ },
173
+ },
174
+ {
175
+ name: "check_agent_leaderboard_status",
176
+ description: "Queries the free Turnstiles leaderboard and agent wallet status endpoint for EV-weighted points, point multiplier, and total MEV saved USD.",
177
+ inputSchema: {
178
+ type: "object",
179
+ properties: {
180
+ walletAddress: {
181
+ type: "string",
182
+ description: "Optional wallet address to inspect (defaults to configured agent wallet)",
183
+ },
184
+ },
185
+ },
186
+ },
187
+ ];
188
+ /** Tools that call free endpoints. Everything else signs an x402 payment. */
189
+ export const FREE_MCP_TOOL_NAMES = ["check_agent_leaderboard_status"];
190
+ export const LOCAL_PAID_TOOLS_HINT = "Paid tools run only in the local MCP server, so your private key never leaves your machine. " +
191
+ "Install it from packages/mcp-server (npm run mcp) with AGENT_PRIVATE_KEY set, or call the paid REST endpoints directly with any x402 v2 client. See /agents.md.";
192
+ function freeTools() {
193
+ return MCP_TOOLS.filter((tool) => FREE_MCP_TOOL_NAMES.includes(tool.name));
194
+ }
195
+ export class X402LaunchpadMcpServer {
196
+ client;
197
+ freeToolsOnly;
198
+ constructor(options = {}) {
199
+ const { freeToolsOnly, ...clientOptions } = options;
200
+ this.freeToolsOnly = freeToolsOnly ?? false;
201
+ this.client = new X402AgentClient(clientOptions);
202
+ }
203
+ listTools() {
204
+ return { tools: this.freeToolsOnly ? freeTools() : MCP_TOOLS };
205
+ }
206
+ async callTool(name, args = {}) {
207
+ try {
208
+ if (this.freeToolsOnly && !FREE_MCP_TOOL_NAMES.includes(name)) {
209
+ const known = MCP_TOOLS.some((tool) => tool.name === name);
210
+ return {
211
+ content: [
212
+ {
213
+ type: "text",
214
+ text: JSON.stringify({
215
+ error: known ? `${name} is a paid tool and is not available on the hosted MCP server.` : `Unknown MCP tool: ${name}`,
216
+ ...(known ? { how_to_use: LOCAL_PAID_TOOLS_HINT } : {}),
217
+ }),
218
+ },
219
+ ],
220
+ isError: true,
221
+ };
222
+ }
223
+ if (name === "alpha_scan_token") {
224
+ const tokenAddress = String(args.tokenAddress ?? "");
225
+ if (!tokenAddress) {
226
+ throw new Error("Missing required argument: tokenAddress");
227
+ }
228
+ const chain = args.chain ?? "base";
229
+ const includeSocialCard = typeof args.includeSocialCard === "boolean" ? args.includeSocialCard : true;
230
+ const useVampireAllowlist = typeof args.useVampireAllowlist === "boolean" ? args.useVampireAllowlist : undefined;
231
+ const result = await this.client.alphaScanToken({
232
+ chain,
233
+ tokenAddress,
234
+ includeSocialCard,
235
+ useVampireAllowlist,
236
+ });
237
+ return {
238
+ content: [
239
+ {
240
+ type: "text",
241
+ text: JSON.stringify(result, null, 2),
242
+ },
243
+ ],
244
+ structuredContent: result,
245
+ isError: false,
246
+ };
247
+ }
248
+ if (name === "mev_shield_swap") {
249
+ const nestedSwap = args.swap ?? {};
250
+ const tokenIn = String(args.tokenIn ?? nestedSwap.tokenIn ?? "");
251
+ const tokenOut = String(args.tokenOut ?? nestedSwap.tokenOut ?? "");
252
+ const amountInAtomic = String(args.amountInAtomic ?? nestedSwap.amountInAtomic ?? "");
253
+ if (!tokenIn || !tokenOut || !amountInAtomic) {
254
+ throw new Error("Missing required swap parameters: tokenIn, tokenOut, amountInAtomic");
255
+ }
256
+ const chain = args.chain ?? "base";
257
+ const mode = args.mode ?? "simulate_only";
258
+ const senderAddress = args.senderAddress ??
259
+ nestedSwap.senderAddress ??
260
+ this.client.walletAddress;
261
+ const signedRawTx = args.signedRawTx ?? nestedSwap.signedRawTx;
262
+ const useVampireAllowlist = typeof args.useVampireAllowlist === "boolean" ? args.useVampireAllowlist : undefined;
263
+ const slippageBps = typeof args.slippageBps === "number" ? args.slippageBps : undefined;
264
+ const result = await this.client.mevShieldSwap({
265
+ chain,
266
+ mode,
267
+ slippageBps,
268
+ swap: {
269
+ tokenIn,
270
+ tokenOut,
271
+ amountInAtomic,
272
+ senderAddress,
273
+ signedRawTx,
274
+ },
275
+ useVampireAllowlist,
276
+ });
277
+ return {
278
+ content: [
279
+ {
280
+ type: "text",
281
+ text: JSON.stringify(result, null, 2),
282
+ },
283
+ ],
284
+ structuredContent: result,
285
+ isError: false,
286
+ };
287
+ }
288
+ if (name === "profile_wallet_pnl") {
289
+ const walletAddress = String(args.walletAddress ?? "");
290
+ if (!walletAddress) {
291
+ throw new Error("Missing required argument: walletAddress");
292
+ }
293
+ const chain = args.chain ?? "base";
294
+ const tokenAddresses = Array.isArray(args.tokenAddresses) ? args.tokenAddresses.map(String) : undefined;
295
+ const result = await this.client.profileWalletPnl({ chain, walletAddress, tokenAddresses });
296
+ return {
297
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
298
+ structuredContent: result,
299
+ isError: false,
300
+ };
301
+ }
302
+ if (name === "predict_gas_fees") {
303
+ const chain = args.chain ?? "base";
304
+ const speedPreference = args.speedPreference ?? "standard";
305
+ const result = await this.client.predictGasFees({ chain, speedPreference });
306
+ return {
307
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
308
+ structuredContent: result,
309
+ isError: false,
310
+ };
311
+ }
312
+ if (name === "audit_contract_bytecode") {
313
+ const chain = args.chain ?? "base";
314
+ const contractAddress = args.contractAddress;
315
+ const bytecode = args.bytecode;
316
+ const result = await this.client.auditContractBytecode({ chain, contractAddress, bytecode });
317
+ return {
318
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
319
+ structuredContent: result,
320
+ isError: false,
321
+ };
322
+ }
323
+ if (name === "search_tokens") {
324
+ const mode = args.mode ?? "search";
325
+ const query = typeof args.query === "string" ? args.query : undefined;
326
+ const chain = args.chain;
327
+ const limit = typeof args.limit === "number" ? args.limit : undefined;
328
+ const result = await this.client.searchTokens({ mode, query, chain, limit });
329
+ return {
330
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
331
+ structuredContent: result,
332
+ isError: false,
333
+ };
334
+ }
335
+ if (name === "check_agent_leaderboard_status") {
336
+ const walletAddress = typeof args.walletAddress === "string" && args.walletAddress.trim().length > 0
337
+ ? args.walletAddress.trim()
338
+ : undefined;
339
+ // Hosted: there is no agent wallet to default to, so an omitted address means the public leaderboard
340
+ const result = await this.client.checkAgentLeaderboardStatus(walletAddress, {
341
+ anonymous: this.freeToolsOnly && !walletAddress,
342
+ });
343
+ return {
344
+ content: [
345
+ {
346
+ type: "text",
347
+ text: JSON.stringify(result, null, 2),
348
+ },
349
+ ],
350
+ structuredContent: result,
351
+ isError: false,
352
+ };
353
+ }
354
+ return {
355
+ content: [
356
+ {
357
+ type: "text",
358
+ text: JSON.stringify({ error: `Unknown MCP tool: ${name}` }),
359
+ },
360
+ ],
361
+ isError: true,
362
+ };
363
+ }
364
+ catch (error) {
365
+ const message = error instanceof Error ? error.message : String(error);
366
+ return {
367
+ content: [
368
+ {
369
+ type: "text",
370
+ text: JSON.stringify({ error: message }),
371
+ },
372
+ ],
373
+ isError: true,
374
+ };
375
+ }
376
+ }
377
+ /**
378
+ * Handles a JSON-RPC 2.0 MCP message (initialize, tools/list, tools/call, ping)
379
+ */
380
+ async handleJsonRpc(request) {
381
+ const id = request.id ?? null;
382
+ if (request.method === "notifications/initialized") {
383
+ return null;
384
+ }
385
+ if (request.method === "initialize") {
386
+ return {
387
+ jsonrpc: "2.0",
388
+ id,
389
+ result: {
390
+ protocolVersion: "2024-11-05",
391
+ capabilities: {
392
+ tools: {},
393
+ },
394
+ serverInfo: {
395
+ name: "turnstiles-mcp",
396
+ version: "1.0.0",
397
+ },
398
+ },
399
+ };
400
+ }
401
+ if (request.method === "ping") {
402
+ return {
403
+ jsonrpc: "2.0",
404
+ id,
405
+ result: {},
406
+ };
407
+ }
408
+ if (request.method === "tools/list") {
409
+ return {
410
+ jsonrpc: "2.0",
411
+ id,
412
+ result: this.listTools(),
413
+ };
414
+ }
415
+ if (request.method === "tools/call") {
416
+ const toolName = String(request.params?.name ?? "");
417
+ const toolArgs = request.params?.arguments ?? {};
418
+ const callResult = await this.callTool(toolName, toolArgs);
419
+ return {
420
+ jsonrpc: "2.0",
421
+ id,
422
+ result: callResult,
423
+ };
424
+ }
425
+ return {
426
+ jsonrpc: "2.0",
427
+ id,
428
+ error: {
429
+ code: -32601,
430
+ message: `Method not found: ${request.method}`,
431
+ },
432
+ };
433
+ }
434
+ /**
435
+ * Starts the MCP server over stdio (newline-delimited JSON-RPC 2.0)
436
+ */
437
+ startStdio() {
438
+ const rl = readline.createInterface({
439
+ input: process.stdin,
440
+ output: process.stdout,
441
+ terminal: false,
442
+ });
443
+ rl.on("line", async (line) => {
444
+ const trimmed = line.trim();
445
+ if (!trimmed)
446
+ return;
447
+ try {
448
+ const parsed = JSON.parse(trimmed);
449
+ const response = await this.handleJsonRpc(parsed);
450
+ if (response) {
451
+ process.stdout.write(`${JSON.stringify(response)}\n`);
452
+ }
453
+ }
454
+ catch (err) {
455
+ const message = err instanceof Error ? err.message : "Invalid JSON-RPC payload";
456
+ process.stdout.write(`${JSON.stringify({
457
+ jsonrpc: "2.0",
458
+ id: null,
459
+ error: { code: -32700, message },
460
+ })}\n`);
461
+ }
462
+ });
463
+ }
464
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "turnstiles-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 and x402 client for Turnstiles: pay-per-call onchain telemetry (token scans, MEV-protected swaps, gas, contract audits) settled in USDC on Base.",
5
+ "keywords": ["mcp", "x402", "usdc", "base", "onchain", "agents"],
6
+ "homepage": "https://turnstiles.dev",
7
+ "license": "SEE LICENSE IN LICENSE",
8
+ "type": "module",
9
+ "engines": {
10
+ "node": ">=20"
11
+ },
12
+ "bin": {
13
+ "turnstiles-mcp": "./dist/cli.js"
14
+ },
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "LICENSE"
26
+ ],
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
32
+ "prepack": "npm run build",
33
+ "start": "tsx src/cli.ts",
34
+ "test": "node --import tsx --test test/*.test.ts"
35
+ },
36
+ "dependencies": {
37
+ "@x402/core": "2.29.0",
38
+ "@x402/evm": "2.29.0",
39
+ "viem": "^2.23.5"
40
+ }
41
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.