#!/usr/bin/env node
// PerpCheck MCP server over stdio (newline-delimited JSON-RPC 2.0). Read-only: never places, signs or holds orders.
// Free by default: the hosted free preview (verdict, issue and warning codes, confidence; 10/min per IP).
// Full results: set PERPCHECK_X402_PRIVATE_KEY (or X402_PRIVATE_KEY) to a Base wallet key holding a little USDC (NOT your
// trading key), and this server pays the hosted API per call over x402 ($0.01 full): https://api.youraitools.co/perpcheck
// node src/mcp-stdio.js (run from a source checkout: https://agentgate-source.pages.dev/x402-perpcheck/)
import { createInterface } from 'node:readline';
import { toOrder, preview, DISCLAIMER, FULL_DETAILS, API_BASE, PRICES } from './lite.js';
import { createPaidClient } from './paid.js';
import { MCP_TOOLS, resultText } from './tool.js';
import { VERSION_STR as VERSION } from './version.js';
export { VERSION };
export const TOOLS = MCP_TOOLS.map((t) => ({ ...t, description: `${t.description} Free by default: verdict and issue codes from the hosted preview. With PERPCHECK_X402_PRIVATE_KEY set (a small Base USDC wallet, not your trading key) it returns the full check (${PRICES.full} USDC per call over x402). Not financial advice; the exchange decides whether an order is accepted.` }));
const PROTOCOLS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
const summarizePreview = (r, note) => `${note ? note + '\n' : ''}PerpCheck ${r.coin} ${r.side}: ${r.verdict}; issues: ${(r.issue_codes || []).join(', ') || 'none'}; warnings: ${(r.warning_codes || []).join(', ') || 'none'}; confidence ${r.confidence}${r.sources_failed?.length ? `; failed: ${r.sources_failed.join(', ')}` : ''}.\n${FULL_DETAILS} Set PERPCHECK_X402_PRIVATE_KEY to get them here.\n${DISCLAIMER}`;
let paidClient;
const paid = async (opts) => { if (paidClient === undefined) paidClient = await createPaidClient(opts); return paidClient; };
export async function handle(m, opts = {}) {
if (!m || m.jsonrpc !== '2.0' || typeof m.method !== 'string') return { jsonrpc: '2.0', id: m?.id ?? null, error: { code: -32600, message: 'Invalid Request' } };
const note = m.id === undefined || m.id === null;
const ok = (result) => (note ? null : { jsonrpc: '2.0', id: m.id, result });
const err = (text) => ok({ isError: true, content: [{ type: 'text', text: `${text}\n${DISCLAIMER}` }] });
switch (m.method) {
case 'initialize': {
const client = await paid(opts);
const mode = client && !client.error ? `Paid mode: full checks from ${client.apiBase} over x402.` : `Free preview mode; full checks at ${API_BASE} (x402) or free on the remote MCP ${API_BASE}/mcp (30/day).`;
return ok({ protocolVersion: PROTOCOLS.includes(m.params?.protocolVersion) ? m.params.protocolVersion : '2025-06-18', capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'perpcheck', title: 'PerpCheck', version: VERSION }, instructions: `Call check_perp_order with the Hyperliquid perp order you are about to send. ${mode} Read-only. ${DISCLAIMER}` });
}
case 'ping': return ok({});
case 'tools/list': return ok({ tools: TOOLS });
case 'tools/call': {
const name = m.params?.name;
if (!TOOLS.some((t) => t.name === name)) return note ? null : { jsonrpc: '2.0', id: m.id, error: { code: -32602, message: `Unknown tool: ${name}` } };
const t = toOrder(m.params?.arguments || {});
if (t.error) return err(`bad_request: ${t.error}`);
const client = await paid(opts);
let fallbackNote = '';
if (client?.error) fallbackNote = client.error;
else if (client) {
try {
const r = await client.call('full', t.query);
if (r.result && !r.error) return ok({ content: [{ type: 'text', text: resultText(r.result) }], structuredContent: { ...r.result, payer: client.payer, ...(r.paymentResponse ? { payment_response: r.paymentResponse } : {}) }, isError: false });
fallbackNote = `Paid call failed (${r.error}${r.detail ? `: ${r.detail}` : ''}); showing the free preview.`;
} catch (e) { fallbackNote = `Paid call failed (${String(e?.message || e).slice(0, 200)}); showing the free preview.`; }
}
const r = await preview(t.query, { fetchImpl: opts.fetchImpl, apiBase: opts.apiBase || process.env.PERPCHECK_API_URL || API_BASE });
if (r.error) return err(`${r.error}: ${r.message}${fallbackNote ? ` (${fallbackNote})` : ''}. Verdict UNKNOWN; do not treat this as OK.`);
delete r.full;
return ok({ content: [{ type: 'text', text: summarizePreview(r, fallbackNote) }], structuredContent: fallbackNote ? { ...r, paid_error: fallbackNote } : r, isError: false });
}
default:
return m.method.startsWith('notifications/') || note ? null : { jsonrpc: '2.0', id: m.id, error: { code: -32601, message: `Method not found: ${m.method}` } };
}
}
export function serve({ input = process.stdin, output = process.stdout } = {}) {
const rl = createInterface({ input, crlfDelay: Infinity });
const write = (o) => output.write(JSON.stringify(o) + '\n');
rl.on('line', async (l) => {
if (!l.trim()) return;
let msg; try { msg = JSON.parse(l); } catch { return write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
const batch = Array.isArray(msg);
const replies = (await Promise.all((batch ? msg : [msg]).map((x) => handle(x)))).filter(Boolean);
if (replies.length) write(batch ? replies : replies[0]);
});
return rl;
}
const self = process.argv[1] || '';
if (import.meta.url === `file://${self}` || /perpcheck(-mcp)?$/.test(self)) serve();
agentgate-source: code mirror on Cloudflare Pages. All repos