-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1870 lines (1715 loc) · 86.4 KB
/
server.js
File metadata and controls
1870 lines (1715 loc) · 86.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* Sol MCP Server — Solana Crypto Analysis Tools
*
* Exposes Sol's Railway-deployed APIs as MCP tools:
* - get_token_risk: Risk score + analysis for any Solana token
* - get_momentum_signal: Buy/sell momentum signal for any token
* - batch_token_risk: Risk scores for up to 10 tokens at once
* - get_full_analysis: Risk + momentum combined
* - get_graduation_signals: Live BUY/SKIP decisions from Sol's graduation alert engine
* - get_trading_performance: Live trading stats (win rate, PnL, recent trades)
* - analyze_wallet: Scan a Solana wallet for risky SPL tokens (PRO)
* - get_market_regime: Classify current market as BULL/NEUTRAL/BEAR (PRO)
*
* Tiers:
* FREE → /mcp/free — 8 tools (get_token_risk, get_momentum_signal, get_market_pulse,
* get_graduation_signals, get_trading_performance,
* get_alpha_leaderboard, preview_wallet, get_pro_features)
* PRO → /mcp — All 10 tools, x402 native ($0.01/call USDC on Solana mainnet)
*
* Payment: x402 native on Solana mainnet — no account needed, wallet auto-pays.
* Fallback: https://sol-mcp-production.up.railway.app/mcp (for non-x402 clients)
*
* Usage:
* node server.js → stdio mode (Claude Desktop / Cursor)
* node server.js --http → HTTP mode (remote MCP server)
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import express from "express";
import { z } from "zod";
import { randomUUID } from "crypto";
import { paymentMiddleware } from "@x402/express";
import { x402ResourceServer, HTTPFacilitatorClient } from "@x402/core/server";
import { registerExactEvmScheme } from "@x402/evm/exact/server";
import { registerExactSvmScheme } from "@x402/svm/exact/server";
const RISK_API = "https://sol-risk-production.up.railway.app";
const MOMENTUM_API = "https://momentum-signal-production.up.railway.app";
const GRAD_ALERT_API = "https://grad-alert-production.up.railway.app";
// ─── Tool helpers ─────────────────────────────────────────────────────────────
async function fetchRisk(mint) {
const res = await fetch(`${RISK_API}/risk/${mint}`);
if (!res.ok) throw new Error(`Risk API error: ${res.status}`);
return res.json();
}
async function fetchMomentum(mint) {
const res = await fetch(`${MOMENTUM_API}/analyze/${mint}`);
if (!res.ok) throw new Error(`Momentum API error: ${res.status}`);
return res.json();
}
// ─── Create server factory ────────────────────────────────────────────────────
function createMcpServer() {
const server = new McpServer({
name: "sol-crypto-analysis",
version: "2.4.0",
description:
"PRO tier — Real-time Solana token risk scoring, momentum signals, and graduation alert decisions. " +
"All 10 tools including batch analysis, wallet portfolio risk, and market regime classification. $0.01/call USDC on Solana mainnet (x402 native — no account needed, wallet auto-pays). " +
"FREE tier at /mcp/free (7 tools, BUY signal mints hidden).",
});
// Tool: get_token_risk
server.tool(
"get_token_risk",
"Get a risk score (0–100) and risk label for a Solana token mint address. " +
"LOW (0-30) = safer, HIGH (56-75) = risky, EXTREME (76-100) = likely rug. " +
"Analyzes liquidity, whale concentration, holder count, and volume patterns.",
{
mint: z
.string()
.describe("Solana token mint address (base58 encoded)."),
},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
async ({ mint }) => {
try {
const data = await fetchRisk(mint);
const score = data.risk_score ?? data.score ?? "N/A";
const label = data.risk_label ?? "UNKNOWN";
const summary = data.summary ?? "";
const flags = data.flags?.length ? `\nFlags: ${data.flags.join(", ")}` : "";
const holders = data.holder_count ? `\nHolders: ${data.holder_count}` : "";
const liquidity = data.liquidity_usd
? `\nLiquidity: $${data.liquidity_usd.toLocaleString()}`
: "";
const whale =
data.whale_concentration_pct != null
? `\nWhale concentration: ${data.whale_concentration_pct.toFixed(1)}%`
: "";
const text =
`Token: ${mint}\n` +
`Risk Score: ${score}/100 (${label})\n` +
(summary ? `Summary: ${summary}` : "") +
holders +
liquidity +
whale +
flags;
return { content: [{ type: "text", text }] };
} catch (err) {
return {
content: [{ type: "text", text: `Error: ${err.message}` }],
isError: true,
};
}
}
);
// Tool: get_momentum_signal
server.tool(
"get_momentum_signal",
"Get a buy/sell momentum signal for a Solana token based on multi-window buy/sell ratio analysis. " +
"Returns STRONG_BUY / BUY / NEUTRAL / SELL / STRONG_SELL with confidence level.",
{
mint: z.string().describe("Solana token mint address (base58 encoded)."),
},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
async ({ mint }) => {
try {
const data = await fetchMomentum(mint);
const signal = data.signal ?? "UNKNOWN";
const score = data.momentum_score ?? "N/A";
const confidence = data.confidence ?? "UNKNOWN";
const symbol = data.symbol ?? mint.slice(0, 8) + "...";
let windows = "";
if (data.windows) {
const w = data.windows;
windows =
`\nM5: buys=${w.m5?.buys ?? "?"} sells=${w.m5?.sells ?? "?"} ratio=${w.m5?.ratio?.toFixed(2) ?? "?"}` +
`\nH1: buys=${w.h1?.buys ?? "?"} sells=${w.h1?.sells ?? "?"} ratio=${w.h1?.ratio?.toFixed(2) ?? "?"}` +
`\nH6: buys=${w.h6?.buys ?? "?"} sells=${w.h6?.sells ?? "?"} ratio=${w.h6?.ratio?.toFixed(2) ?? "?"}`;
}
const text =
`Token: ${symbol} (${mint})\n` +
`Signal: ${signal}\n` +
`Momentum Score: ${score}/100\n` +
`Confidence: ${confidence}` +
windows;
return { content: [{ type: "text", text }] };
} catch (err) {
return {
content: [{ type: "text", text: `Error: ${err.message}` }],
isError: true,
};
}
}
);
// Tool: batch_token_risk
server.tool(
"batch_token_risk",
"Get risk scores for multiple Solana tokens (up to 10) in one call. " +
"Returns results sorted by risk score, lowest (safest) first.",
{
mints: z
.array(z.string())
.min(1)
.max(10)
.describe("Array of Solana token mint addresses, 1–10 items."),
},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
async ({ mints }) => {
try {
const results = await Promise.allSettled(mints.map(fetchRisk));
const rows = results.map((r, i) => {
if (r.status === "rejected") {
return { mint: mints[i], score: null, label: "ERROR", error: r.reason.message };
}
const d = r.value;
return {
mint: mints[i],
score: d.risk_score ?? d.score ?? null,
label: d.risk_label ?? "UNKNOWN",
};
});
rows.sort((a, b) => {
if (a.score === null) return 1;
if (b.score === null) return -1;
return a.score - b.score;
});
const lines = rows.map((r) => {
if (r.error) return `❌ ${r.mint.slice(0, 12)}... ERROR: ${r.error}`;
const bar = "█".repeat(Math.floor((r.score ?? 0) / 10));
return `${r.label.padEnd(8)} ${String(r.score).padStart(3)}/100 ${bar} ${r.mint}`;
});
const text =
`Batch Risk Analysis — ${mints.length} tokens (safest first):\n\n` +
lines.join("\n");
return { content: [{ type: "text", text }] };
} catch (err) {
return {
content: [{ type: "text", text: `Batch error: ${err.message}` }],
isError: true,
};
}
}
);
// Tool: get_full_analysis
server.tool(
"get_full_analysis",
"Get both risk score AND momentum signal for a token in one call. " +
"Combined verdict: low risk + strong buy = best setup for entry.",
{
mint: z.string().describe("Solana token mint address (base58 encoded)."),
},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
async ({ mint }) => {
try {
const [riskResult, momentumResult] = await Promise.allSettled([
fetchRisk(mint),
fetchMomentum(mint),
]);
let text = `Full Analysis: ${mint}\n${"─".repeat(50)}\n`;
if (riskResult.status === "fulfilled") {
const d = riskResult.value;
const score = d.risk_score ?? d.score ?? "N/A";
const label = d.risk_label ?? "UNKNOWN";
text += `RISK: ${score}/100 (${label})\n`;
if (d.summary) text += `${d.summary}\n`;
if (d.liquidity_usd) text += `Liquidity: $${d.liquidity_usd.toLocaleString()}\n`;
if (d.whale_concentration_pct != null)
text += `Whale conc: ${d.whale_concentration_pct.toFixed(1)}%\n`;
if (d.flags?.length) text += `Flags: ${d.flags.join(", ")}\n`;
} else {
text += `RISK: Error — ${riskResult.reason.message}\n`;
}
text += "\n";
if (momentumResult.status === "fulfilled") {
const d = momentumResult.value;
text += `MOMENTUM: ${d.signal ?? "UNKNOWN"} (${d.confidence ?? "?"})\n`;
text += `Score: ${d.momentum_score ?? "N/A"}/100\n`;
if (d.windows) {
const w = d.windows;
text += `M5: ${w.m5?.ratio?.toFixed(2) ?? "?"} | H1: ${w.h1?.ratio?.toFixed(2) ?? "?"} | H6: ${w.h6?.ratio?.toFixed(2) ?? "?"}\n`;
}
} else {
text += `MOMENTUM: Error — ${momentumResult.reason.message}\n`;
}
const riskScore =
riskResult.status === "fulfilled"
? riskResult.value.risk_score ?? riskResult.value.score ?? 100
: 100;
const signal =
momentumResult.status === "fulfilled"
? momentumResult.value.signal ?? "NEUTRAL"
: "NEUTRAL";
text += "\n";
if (riskScore <= 30 && signal.includes("BUY")) {
text += "✅ VERDICT: Strong setup — low risk + buy signal";
} else if (riskScore <= 65 && signal.includes("BUY")) {
text += "🟡 VERDICT: Moderate setup — watch closely";
} else if (riskScore > 70) {
text += "🔴 VERDICT: High risk — avoid";
} else {
text += "⚪ VERDICT: Neutral — no clear edge";
}
return { content: [{ type: "text", text }] };
} catch (err) {
return {
content: [{ type: "text", text: `Error: ${err.message}` }],
isError: true,
};
}
}
);
// Tool: get_graduation_signals
server.tool(
"get_graduation_signals",
"Get recent token graduation signal decisions from Sol's on-chain analysis engine. " +
"Shows which pump.fun tokens were flagged as BUY or SKIP, with full reasoning. " +
"Tokens are evaluated at graduation (bonding curve completion) using risk score + momentum. " +
"BUY signals have risk ≤65 and strong momentum (2.0–3.0× ratio depending on risk tier). " +
"Use this to discover tokens Sol's AI has vetted as worth trading.",
{
limit: z
.number()
.int()
.min(1)
.max(50)
.default(10)
.describe("Number of recent decisions to return (1–50). Default: 10."),
filter: z
.enum(["all", "trade", "skip"])
.default("all")
.describe(
"Filter by decision type: 'trade' (BUY signals only), 'skip' (filtered out), or 'all'."
),
},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
async ({ limit, filter }) => {
try {
const url = `${GRAD_ALERT_API}/decisions?limit=${limit}`;
const res = await fetch(url);
if (!res.ok) throw new Error(`Grad-alert API error: ${res.status}`);
const data = await res.json();
const decisions = data.decisions ?? [];
const filtered = filter === "all"
? decisions
: decisions.filter((d) => {
if (filter === "trade") return d.decision === "TRADE";
if (filter === "skip") return d.decision === "SKIP";
return true;
});
const s = data.summary ?? {};
let text =
`Sol Graduation Signal Decisions (${data.version ?? "v?"}, ${data.agent_id ?? "sol"})\n` +
`Generated: ${data.generated_at ?? "unknown"}\n` +
`Total: ${s.total_decisions ?? 0} decisions — ` +
`${s.trades ?? 0} TRADES, ${s.skips ?? 0} SKIPS\n`;
if (s.win_rate_pct != null) {
text += `Live Win Rate: ${s.win_rate_pct.toFixed(1)}%\n`;
}
const todFilter = data.timeOfDayFilter;
if (todFilter) {
const allowed = todFilter.tradingAllowed;
text += `Trading now: ${allowed ? "✅ YES" : "🚫 NO (blocked hour UTC ${todFilter.currentUTCHour})"}\n`;
}
text += `\n${"─".repeat(55)}\n`;
if (filtered.length === 0) {
text += `No ${filter === "all" ? "" : filter + " "}decisions found in last ${limit} records.`;
} else {
for (const d of filtered) {
const ts = d.timestamp
? new Date(d.timestamp).toISOString().slice(0, 16).replace("T", " ")
: "?";
const icon = d.decision === "TRADE" ? "🟢" : "🔴";
const inp = d.inputs ?? {};
text += `\n${icon} ${d.decision} ${ts} UTC\n`;
text += ` Token: ${inp.token ?? "?"} (${(inp.mint ?? "").slice(0, 12)}...)\n`;
text += ` Risk: ${inp.risk_score ?? "?"}/100`;
if (inp.momentum_ratio != null) text += ` Momentum: ${inp.momentum_ratio}× (buys ${inp.momentum_buys ?? "?"}/${(inp.momentum_buys ?? 0) + (inp.momentum_sells ?? 0)} total)`;
text += `\n`;
if (d.reasoning) text += ` Reason: ${d.reasoning}\n`;
if (d.outcome) {
const o = d.outcome;
text += ` Outcome: ${o.result ?? "?"} ${o.pnl_sol != null ? `(${o.pnl_sol > 0 ? "+" : ""}${o.pnl_sol.toFixed(4)} SOL, ${o.multiple_x != null ? o.multiple_x.toFixed(2) + "×" : ""})` : ""}\n`;
}
}
}
return { content: [{ type: "text", text }] };
} catch (err) {
return {
content: [{ type: "text", text: `Error: ${err.message}` }],
isError: true,
};
}
}
);
// Tool: get_trading_performance
server.tool(
"get_trading_performance",
"Get Sol's live trading performance stats and recent closed trades. " +
"Shows win rate, total PnL, ROI, and the most recent trade outcomes. " +
"Sol trades pump.fun graduating tokens on Solana using a risk + momentum strategy. " +
"Useful for evaluating signal quality before using get_graduation_signals for trade ideas.",
{
recent_count: z
.number()
.int()
.min(1)
.max(20)
.default(5)
.describe("Number of recent closed trades to show (1–20). Default: 5."),
},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
async ({ recent_count }) => {
try {
const res = await fetch(`${GRAD_ALERT_API}/real-trades?limit=${recent_count}`);
if (!res.ok) throw new Error(`Trading API error: ${res.status}`);
const data = await res.json();
const st = data.stats ?? {};
let text =
`Sol Trading Performance (real capital, ${data.mode ?? "?"})\n` +
`${"─".repeat(50)}\n` +
`Total Trades: ${st.total_trades ?? 0}\n` +
`Win Rate: ${st.win_rate_pct != null ? st.win_rate_pct.toFixed(1) + "%" : "N/A"} ` +
`(${st.wins ?? 0}W / ${st.losses ?? 0}L)\n` +
`Total PnL: ${st.total_pnl_sol != null ? (st.total_pnl_sol > 0 ? "+" : "") + st.total_pnl_sol.toFixed(4) : "?"} SOL\n` +
`ROI: ${st.roi_pct != null ? (st.roi_pct > 0 ? "+" : "") + st.roi_pct.toFixed(2) + "%" : "?"}\n` +
`Capital Deployed: ${st.capital_deployed_sol ?? "?"} SOL\n` +
`Avg Hold: ${st.avg_hold_mins != null ? st.avg_hold_mins.toFixed(1) + " min" : "?"}\n` +
`Best Trade: ${st.best_trade_sol != null ? "+" + st.best_trade_sol.toFixed(4) + " SOL" : "?"}\n` +
`Worst Trade: ${st.worst_trade_sol != null ? st.worst_trade_sol.toFixed(4) + " SOL" : "?"}\n`;
const open = data.open_positions ?? [];
if (open.length > 0) {
text += `\nOpen Positions: ${open.length}\n`;
for (const p of open) {
text += ` 🔵 ${(p.mint ?? "?").slice(0, 12)}... risk=${p.risk_score ?? "?"} entry=${p.entry_sol ?? "?"}SOL\n`;
}
} else {
text += `\nOpen Positions: None\n`;
}
const closed = data.recent_closed ?? [];
if (closed.length > 0) {
text += `\nRecent Closed Trades (${closed.length}):\n`;
for (const t of closed) {
const icon = t.exit_reason === "TP" ? "✅" : "❌";
const pnl = t.pnl_sol != null ? `${t.pnl_sol > 0 ? "+" : ""}${t.pnl_sol.toFixed(4)} SOL` : "?";
const mult = t.multiple_x != null ? `${t.multiple_x.toFixed(2)}×` : "?";
const hold = t.hold_mins != null ? `${t.hold_mins}min` : "?";
const ts = t.entry_time
? new Date(t.entry_time).toISOString().slice(0, 16).replace("T", " ")
: "?";
text += ` ${icon} ${ts} UTC | risk=${t.risk_score ?? "?"} | ${pnl} (${mult}) | held ${hold} | exit=${t.exit_reason ?? "?"}\n`;
}
}
return { content: [{ type: "text", text }] };
} catch (err) {
return {
content: [{ type: "text", text: `Error: ${err.message}` }],
isError: true,
};
}
}
);
// Tool: analyze_wallet
server.tool(
"analyze_wallet",
"Analyze all SPL tokens held by a Solana wallet address. " +
"Returns a full portfolio risk report — every token with its balance, risk score (0-100), " +
"and risk label sorted by danger level (EXTREME first). " +
"Use this to audit a wallet before copying trades, check your own exposure, or " +
"screen a trader's holdings for rug risk. Analyzes up to 20 tokens per wallet.",
{
wallet: z
.string()
.describe("Solana wallet address (base58 encoded public key)."),
},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
async ({ wallet }) => {
try {
// 1. Fetch all SPL token accounts for this wallet via public Solana RPC
const rpcRes = await fetch("https://api.mainnet-beta.solana.com", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "getTokenAccountsByOwner",
params: [
wallet,
{ programId: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" },
{ encoding: "jsonParsed", commitment: "confirmed" },
],
}),
});
const rpcData = await rpcRes.json();
if (rpcData.error) throw new Error(`RPC error: ${rpcData.error.message}`);
const accounts = rpcData.result?.value ?? [];
if (accounts.length === 0) {
return {
content: [{
type: "text",
text: `No SPL tokens found for wallet: ${wallet}\n\nPossible reasons:\n- Wallet only holds SOL\n- Empty wallet\n- Invalid address`,
}],
};
}
// 2. Extract mints with non-zero balances (top 20 by amount)
const holdings = accounts
.map((acc) => {
const info = acc.account?.data?.parsed?.info;
if (!info) return null;
const amount = parseFloat(info.tokenAmount?.uiAmount ?? 0);
return amount > 0 ? { mint: info.mint, amount } : null;
})
.filter(Boolean)
.slice(0, 20);
if (holdings.length === 0) {
return {
content: [{ type: "text", text: `Wallet ${wallet} has token accounts but all balances are zero.` }],
};
}
const mints = holdings.map((h) => h.mint);
// 3. Batch risk score all mints
let riskMap = {};
try {
const batchRes = await fetch(`${RISK_API}/batch`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ mints }),
});
if (batchRes.ok) {
const body = await batchRes.json();
const results = body.results ?? body;
if (Array.isArray(results)) {
for (const r of results) { if (r.mint) riskMap[r.mint] = r; }
} else if (typeof results === "object") {
riskMap = results;
}
}
} catch (_) {
// Batch failed — try individual for first 5
for (const mint of mints.slice(0, 5)) {
try { riskMap[mint] = await fetchRisk(mint); } catch (_) {}
}
}
// 4. Build scored list sorted by risk (highest first)
const ORDER = { EXTREME: 0, HIGH: 1, MEDIUM: 2, LOW: 3, UNKNOWN: 4 };
const ICONS = { EXTREME: "🔴", HIGH: "🟠", MEDIUM: "🟡", LOW: "🟢", UNKNOWN: "⚪" };
const scored = holdings
.map((h) => {
const r = riskMap[h.mint] ?? {};
return {
mint: h.mint,
amount: h.amount,
score: r.risk_score ?? r.score ?? null,
label: r.risk_label ?? "UNKNOWN",
symbol: r.symbol ?? h.mint.slice(0, 8) + "...",
};
})
.sort((a, b) => {
const ao = ORDER[a.label] ?? 4;
const bo = ORDER[b.label] ?? 4;
return ao !== bo ? ao - bo : (b.score ?? 0) - (a.score ?? 0);
});
const extremeCount = scored.filter((s) => s.label === "EXTREME").length;
const highCount = scored.filter((s) => s.label === "HIGH").length;
const safeCount = scored.filter((s) => ["LOW", "MEDIUM"].includes(s.label)).length;
let text =
`Wallet Portfolio Risk Analysis\n` +
`Wallet: ${wallet.slice(0, 14)}...${wallet.slice(-6)}\n` +
`Tokens: ${scored.length}${accounts.length > 20 ? ` (top 20 of ${accounts.length})` : ""}\n` +
`${"─".repeat(55)}\n` +
`Summary: 🔴 ${extremeCount} EXTREME 🟠 ${highCount} HIGH 🟢 ${safeCount} SAFE\n\n`;
for (const s of scored) {
const icon = ICONS[s.label] ?? "⚪";
const scoreStr = s.score != null ? `${s.score}/100` : "?/100";
const amtFmt =
s.amount < 0.01
? s.amount.toExponential(2)
: s.amount < 1000
? s.amount.toFixed(4)
: s.amount.toLocaleString(undefined, { maximumFractionDigits: 0 });
text += `${icon} ${s.symbol.slice(0, 12).padEnd(12)} ${scoreStr.padStart(7)} bal: ${amtFmt}\n`;
text += ` ${s.mint}\n`;
}
if (extremeCount > 0) {
text += `\n⚠️ ${extremeCount} EXTREME risk token(s) — likely rugs or illiquid. Consider exiting.\n`;
}
text += `\nRisk scoring by Sol Risk API v2.1. Data: Solana mainnet.`;
return { content: [{ type: "text", text }] };
} catch (err) {
return {
content: [{ type: "text", text: `Error analyzing wallet: ${err.message}` }],
isError: true,
};
}
}
);
// Tool: get_market_regime
server.tool(
"get_market_regime",
"Classify the current pump.fun graduation market as BULL, NEUTRAL, or BEAR based on 24h signal quality. " +
"Analyzes Sol's live graduation alert engine: graduation velocity (tokens/hr), BUY signal rate, " +
"average momentum ratios, skip reason distribution, and 24h vs 72h performance trend. " +
"Use this before trading to know whether the market is generating actionable signals or if conditions are unfavorable. " +
"A BULL regime = high graduation rate + strong momentum + healthy BUY signal frequency. " +
"A BEAR regime = sparse quality signals, weak momentum, mostly filtered/skipped. " +
"PRO-only — requires signal pattern intelligence only available from live bot data.",
{},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
async () => {
try {
const [decisionsRes, paperRes, healthRes] = await Promise.all([
fetch(`${GRAD_ALERT_API}/decisions?limit=300`),
fetch(`${GRAD_ALERT_API}/paper-trades?limit=50`),
fetch(`${GRAD_ALERT_API}/health`),
]);
if (!decisionsRes.ok) throw new Error(`Decisions API error: ${decisionsRes.status}`);
const decisionsData = await decisionsRes.json();
const paperData = paperRes.ok ? await paperRes.json() : null;
const healthData = healthRes.ok ? await healthRes.json() : null;
const allDecisions = decisionsData.decisions ?? [];
const now = Date.now();
const H24 = 24 * 3600 * 1000;
const H72 = 72 * 3600 * 1000;
// ── Window slices ──
const last24h = allDecisions.filter(d => now - new Date(d.timestamp).getTime() < H24);
const last72h = allDecisions.filter(d => now - new Date(d.timestamp).getTime() < H72);
const prev24to48h = allDecisions.filter(d => {
const age = now - new Date(d.timestamp).getTime();
return age >= H24 && age < H24 * 2;
});
if (last24h.length === 0) {
return { content: [{ type: "text", text: "Insufficient data: no decisions in last 24h. Bot may be paused or data unavailable." }] };
}
// ── Core metrics (24h) ──
const buys24h = last24h.filter(d => d.decision === "TRADE");
const skips24h = last24h.filter(d => d.decision === "SKIP");
const buyRate24h = last24h.length > 0 ? buys24h.length / last24h.length : 0;
const gradVelocity = last24h.length / 24; // tokens analyzed per hour
const withMom = last24h.filter(d => d.inputs?.momentum_ratio != null);
const avgMom = withMom.length > 0
? withMom.reduce((s, d) => s + d.inputs.momentum_ratio, 0) / withMom.length
: null;
// ── Trend: 24h vs prev 24-48h ──
const buyRatePrev = prev24to48h.length > 0
? prev24to48h.filter(d => d.decision === "TRADE").length / prev24to48h.length
: null;
const withMomPrev = prev24to48h.filter(d => d.inputs?.momentum_ratio != null);
const avgMomPrev = withMomPrev.length > 0
? withMomPrev.reduce((s, d) => s + d.inputs.momentum_ratio, 0) / withMomPrev.length
: null;
const signalTrend =
buyRatePrev == null ? "⚪ UNKNOWN"
: buyRate24h > buyRatePrev * 1.15 ? "📈 IMPROVING"
: buyRate24h < buyRatePrev * 0.85 ? "📉 DEGRADING"
: "➡️ STABLE";
// ── Skip reason breakdown ──
const skipReasons = skips24h.reduce((acc, d) => {
const r = d.skip_reason ?? "unknown";
acc[r] = (acc[r] ?? 0) + 1;
return acc;
}, {});
const topSkips = Object.entries(skipReasons).sort((a, b) => b[1] - a[1]).slice(0, 5);
// ── Paper trade performance (recent 20) ──
let paperWR = null;
let paperAvgPnl = null;
let paperCount = 0;
if (paperData) {
const trades = Array.isArray(paperData) ? paperData : (paperData.trades ?? paperData.paper_trades ?? []);
const recent = trades.slice(0, 20);
paperCount = recent.length;
if (paperCount > 0) {
const wins = recent.filter(t => (t.pnl_pct ?? t.pnl ?? 0) > 0).length;
paperWR = wins / paperCount;
paperAvgPnl = recent.reduce((s, t) => s + (t.pnl_pct ?? t.pnl ?? 0), 0) / paperCount;
}
}
// ── Regime classification ──
// BULL: high grad velocity + solid buy rate + strong momentum + positive paper performance
// BEAR: low velocity, very low buy rate, or clearly negative paper performance
// NEUTRAL: everything in between
const bullSignals = [
gradVelocity >= 60, // 60+ tokens/hr analyzed = active market
buyRate24h >= 0.08, // ≥8% convert to BUY
avgMom != null && avgMom >= 1.6, // avg momentum ≥ 1.6x
paperWR != null && paperWR >= 0.50, // paper WR ≥ 50% recent 20
signalTrend === "📈 IMPROVING",
].filter(Boolean).length;
const bearSignals = [
gradVelocity < 20, // <20/hr = quiet/dead market
buyRate24h < 0.02, // <2% BUY rate = basically nothing passing
avgMom != null && avgMom < 1.2, // momentum very weak
paperWR != null && paperWR < 0.30, // paper WR <30% = strategy losing
signalTrend === "📉 DEGRADING" && buyRate24h < 0.04,
].filter(Boolean).length;
let regime, regimeIcon, regimeDesc;
if (bullSignals >= 3 && bearSignals === 0) {
regime = "BULL"; regimeIcon = "🟢";
regimeDesc = "Strong graduation market. Multiple quality signals per hour. Momentum ratios healthy. Favorable conditions for entries.";
} else if (bearSignals >= 2) {
regime = "BEAR"; regimeIcon = "🔴";
regimeDesc = "Weak market. Few graduations meeting quality thresholds, low momentum. Recommend caution — most signals are filtered noise.";
} else {
regime = "NEUTRAL"; regimeIcon = "🟡";
regimeDesc = "Mixed conditions. Some quality signals present but market not in ideal momentum regime. Standard filtering applies.";
}
const confidence =
(bullSignals + bearSignals) >= 3 ? "HIGH"
: (bullSignals + bearSignals) >= 2 ? "MEDIUM"
: "LOW";
// ── Format output ──
let text =
`Sol Market Regime Analysis — ${new Date().toISOString().slice(0, 16).replace("T", " ")} UTC\n` +
`${"═".repeat(55)}\n\n` +
`Regime: ${regimeIcon} ${regime} (confidence: ${confidence})\n` +
`${regimeDesc}\n\n` +
`── 24h Signal Quality ──\n` +
`Graduation velocity: ${gradVelocity.toFixed(1)} tokens/hr analyzed\n` +
`BUY signal rate: ${(buyRate24h * 100).toFixed(1)}% (${buys24h.length} BUY / ${last24h.length} total)\n`;
if (avgMom != null) {
text += `Avg momentum ratio: ${avgMom.toFixed(2)}×`;
if (avgMomPrev != null) {
const momChg = ((avgMom - avgMomPrev) / avgMomPrev * 100).toFixed(1);
text += ` (vs ${avgMomPrev.toFixed(2)}× prev 24h, ${momChg > 0 ? "+" : ""}${momChg}%)`;
}
text += `\n`;
}
text += `Signal trend: ${signalTrend}`;
if (buyRatePrev != null) {
text += ` (${(buyRate24h * 100).toFixed(1)}% now vs ${(buyRatePrev * 100).toFixed(1)}% prev 24h)`;
}
text += `\n`;
if (paperCount > 0) {
text +=
`\n── Recent Paper Performance (last ${paperCount} trades) ──\n` +
`Win rate: ${(paperWR * 100).toFixed(1)}%\n` +
`Avg PnL: ${paperAvgPnl >= 0 ? "+" : ""}${paperAvgPnl.toFixed(2)}%\n`;
}
if (topSkips.length > 0) {
text += `\n── Why Tokens Are Filtered (24h) ──\n`;
for (const [reason, count] of topSkips) {
const pct = ((count / skips24h.length) * 100).toFixed(0);
text += ` ${reason}: ${count} (${pct}%)\n`;
}
}
if (healthData) {
const cb = healthData.circuit_breaker ?? {};
text +=
`\n── Bot Status ──\n` +
`Circuit breaker: ${cb.paused ? `⏸️ PAUSED (${cb.remainingMin ?? "?"}min remaining)` : "✅ Active"}\n` +
`WS feed: ${(healthData.ws?.status === "active") ? "✅ Live" : "⚠️ " + (healthData.ws?.status ?? "?")}\n`;
}
text +=
`\n${"─".repeat(55)}\n` +
`Bull signals: ${bullSignals}/5 Bear signals: ${bearSignals}/5\n` +
`Data: last ${last24h.length} decisions (24h window from ${last72h.length} available)\n`;
return { content: [{ type: "text", text }] };
} catch (err) {
return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
}
}
);
return server;
}
// ─── Free Tier Server (6 tools, no paywall) ───────────────────────────────────
function createFreeMcpServer() {
const server = new McpServer({
name: "sol-crypto-analysis-free",
version: "2.4.0",
description:
"FREE tier — Real-time Solana token risk scoring, momentum signals, and graduation alert decisions. " +
"5 free tools. BUY signal token details are PRO-only (free tier shows risk/momentum hints, not mints). " +
"Upgrade at sol-mcp-production.up.railway.app/mcp ($0.01/call USDC) to unlock all signals + batch analysis.",
});
// Register all 6 free tools by re-using the full server's tool definitions.
// We achieve this by creating the full server and filtering — but it's cleaner
// to register independently so the description accurately reflects free tier.
server.tool(
"get_token_risk",
"[FREE] Get a risk score (0–100) and risk label for a Solana token mint address. " +
"LOW (0-30) = safer, HIGH (56-75) = risky, EXTREME (76-100) = likely rug. " +
"Analyzes liquidity, whale concentration, holder count, and volume patterns.",
{ mint: z.string().describe("Solana token mint address (base58 encoded).") },
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
async ({ mint }) => {
try {
const data = await fetchRisk(mint);
const score = data.risk_score ?? data.score ?? "N/A";
const label = data.risk_label ?? "UNKNOWN";
const summary = data.summary ?? "";
const flags = data.flags?.length ? `\nFlags: ${data.flags.join(", ")}` : "";
const holders = data.holder_count ? `\nHolders: ${data.holder_count}` : "";
const liquidity = data.liquidity_usd
? `\nLiquidity: $${data.liquidity_usd.toLocaleString()}` : "";
const whale = data.whale_concentration_pct != null
? `\nWhale concentration: ${data.whale_concentration_pct.toFixed(1)}%` : "";
const text =
`Token: ${mint}\n` +
`Risk Score: ${score}/100 (${label})\n` +
(summary ? `Summary: ${summary}` : "") +
holders + liquidity + whale + flags +
`\n\n─────────────────────────────────────\n` +
`⚡ UPGRADE TO PRO — $0.01/call (USDC)\n` +
` get_full_analysis: risk + momentum in ONE call (vs 2 free calls)\n` +
` batch_token_risk: score 10 tokens at once\n` +
` → sol-mcp-production.up.railway.app/mcp`;
return { content: [{ type: "text", text }] };
} catch (err) {
return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
}
}
);
server.tool(
"get_momentum_signal",
"[FREE] Get a buy/sell momentum signal for a Solana token based on multi-window buy/sell ratio analysis. " +
"Returns STRONG_BUY / BUY / NEUTRAL / SELL / STRONG_SELL with confidence level.",
{ mint: z.string().describe("Solana token mint address (base58 encoded).") },
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
async ({ mint }) => {
try {
const data = await fetchMomentum(mint);
const signal = data.signal ?? "UNKNOWN";
const score = data.momentum_score ?? "N/A";
const confidence = data.confidence ?? "UNKNOWN";
const symbol = data.symbol ?? mint.slice(0, 8) + "...";
let windows = "";
if (data.windows) {
const w = data.windows;
windows =
`\nM5: buys=${w.m5?.buys ?? "?"} sells=${w.m5?.sells ?? "?"} ratio=${w.m5?.ratio?.toFixed(2) ?? "?"}` +
`\nH1: buys=${w.h1?.buys ?? "?"} sells=${w.h1?.sells ?? "?"} ratio=${w.h1?.ratio?.toFixed(2) ?? "?"}` +
`\nH6: buys=${w.h6?.buys ?? "?"} sells=${w.h6?.sells ?? "?"} ratio=${w.h6?.ratio?.toFixed(2) ?? "?"}`;
}
const actionLine = signal.includes("BUY")
? `\n💡 Signal looks bullish? get_full_analysis (PRO) gives you risk + momentum in 1 call.`
: signal.includes("SELL")
? `\n💡 Bearish signal? Combine with get_token_risk (free) or get_full_analysis (PRO, 1 call).`
: `\n💡 PRO: get_full_analysis combines risk + momentum in 1 call vs 2 free calls.`;
const text =
`Token: ${symbol} (${mint})\n` +
`Signal: ${signal}\n` +
`Momentum Score: ${score}/100\n` +
`Confidence: ${confidence}` + windows +
actionLine +
`\n→ sol-mcp-production.up.railway.app/mcp ($0.01/call USDC)`;
return { content: [{ type: "text", text }] };
} catch (err) {
return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
}
}
);
server.tool(
"get_graduation_signals",
"[FREE] Get recent token graduation signal decisions from Sol's on-chain analysis engine. " +
"Shows SKIP decisions with full reasoning (why tokens were rejected). " +
"BUY signal token details are PRO-only — free tier shows count + risk/momentum hints. " +
"Upgrade at sol-mcp-production.up.railway.app/mcp ($0.01/call USDC) to see buy signal mints.",
{
limit: z.number().int().min(1).max(50).default(10)
.describe("Number of recent decisions to return (1–50). Default: 10."),
filter: z.enum(["all", "skip"]).default("all")
.describe("Filter: 'skip' (rejected tokens with full reasoning) or 'all' (includes redacted BUY signals)."),
},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
async ({ limit, filter }) => {
try {
const url = `${GRAD_ALERT_API}/decisions?limit=${limit}`;
const res = await fetch(url);
if (!res.ok) throw new Error(`Grad-alert API error: ${res.status}`);
const data = await res.json();
const decisions = data.decisions ?? [];
const s = data.summary ?? {};
// Free tier: always show all for filtering, but redact TRADE details
const filtered = filter === "skip"
? decisions.filter((d) => d.decision === "SKIP")
: decisions;
let text =
`Sol Graduation Signal Decisions (${data.version ?? "v?"}, ${data.agent_id ?? "sol"})\n` +
`Generated: ${data.generated_at ?? "unknown"}\n` +
`Total: ${s.total_decisions ?? 0} decisions — ${s.trades ?? 0} TRADE signals, ${s.skips ?? 0} SKIPS\n`;
if (s.win_rate_pct != null) text += `Live Win Rate: ${s.win_rate_pct.toFixed(1)}%\n`;
const tradeCount = filtered.filter(d => d.decision === "TRADE").length;
if (tradeCount > 0) {
text += `\n⚠️ ${tradeCount} BUY signal${tradeCount > 1 ? "s" : ""} in this batch — token details are PRO-only (see below)\n`;
}
text += `\n${"─".repeat(55)}\n`;
if (filtered.length === 0) {
text += `No decisions found in last ${limit} records.`;
} else {
for (const d of filtered) {
const ts = d.timestamp
? new Date(d.timestamp).toISOString().slice(0, 16).replace("T", " ") : "?";
const inp = d.inputs ?? {};
if (d.decision === "TRADE") {
// Redact BUY signals in free tier — tease risk/momentum but hide token identity
text += `\n🔒 [PRO] TRADE SIGNAL ${ts} UTC\n`;
text += ` Risk: ${inp.risk_score ?? "?"}/100`;
if (inp.momentum_ratio != null)
text += ` Momentum: ${inp.momentum_ratio}× (${inp.momentum_buys ?? "?"}B/${inp.momentum_sells ?? "?"}S)`;
text += `\n Token: [hidden — upgrade to unlock]\n`;
text += ` → sol-mcp-production.up.railway.app/mcp ($0.01/call USDC)\n`;
} else {
// Full SKIP decision shown — these are the rejects, no trading value
text += `\n🔴 SKIP ${ts} UTC\n`;
text += ` Token: ${inp.token ?? "?"} (${(inp.mint ?? "").slice(0, 12)}...)\n`;
text += ` Risk: ${inp.risk_score ?? "?"}/100`;
if (inp.momentum_ratio != null)
text += ` Momentum: ${inp.momentum_ratio}× (${inp.momentum_buys ?? "?"}B/${inp.momentum_sells ?? "?"}S)`;
text += `\n`;
if (d.reasoning) text += ` Reason: ${d.reasoning}\n`;
}
}
}
text +=
`\n${"═".repeat(55)}\n` +
`🔒 PRO TIER — Unlock BUY signal token identities\n` +
` All TRADE signal mints revealed in real time\n` +
` batch_token_risk: score 10 tokens in 1 call\n` +
` get_full_analysis: risk + momentum combined\n` +
` $0.01/call USDC → sol-mcp-production.up.railway.app/mcp`;
return { content: [{ type: "text", text }] };
} catch (err) {
return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
}
}
);
server.tool(
"get_trading_performance",
"[FREE] Get Sol's live signal accuracy stats and trading performance. " +
"Leads with paper validation (130+ trades, same signals, zero execution noise) then real capital results. " +
"Sol trades pump.fun graduating tokens using a risk + momentum strategy — 60.5% WR on risk-70 expansion. " +
"Useful for evaluating signal quality and understanding strategy edge.",
{
recent_count: z.number().int().min(1).max(20).default(5)
.describe("Number of recent closed trades to show (1–20). Default: 5."),
},
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
async ({ recent_count }) => {
try {
// Fetch both real and paper trade stats in parallel
const [realRes, paperRes] = await Promise.all([
fetch(`${GRAD_ALERT_API}/real-trades?limit=${recent_count}`),
fetch(`${GRAD_ALERT_API}/paper-trades?limit=5`),
]);
if (!realRes.ok) throw new Error(`Trading API error: ${realRes.status}`);
const data = await realRes.json();
const paperData = paperRes.ok ? await paperRes.json() : null;
let text = `Sol Signal Performance Dashboard\n${"═".repeat(50)}\n\n`;
// Lead with paper validation (clean signal quality metric)
if (paperData) {
const ps = paperData.stats ?? {};
const rb = paperData.risk_breakdown ?? {};
const core = rb.core_risk_31_to_65 ?? {};
const exp70 = rb.experiment_risk_66_to_75 ?? {};
text += `── SIGNAL ACCURACY (Paper Validation — ${ps.total_trades ?? "?"} trades) ──\n`;
text +=
`Overall Win Rate: ${ps.win_rate_pct != null ? ps.win_rate_pct.toFixed(1) + "%" : "?"} ` +
`(${ps.wins ?? 0}W / ${ps.losses ?? 0}L)\n`;
if (ps.best_trade_pct != null) {