-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1756 lines (1487 loc) · 68.7 KB
/
server.py
File metadata and controls
1756 lines (1487 loc) · 68.7 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 python3
"""Warframe Toolkit MCP Server - market prices, syndicate lookup, world state, arbitrage"""
import json
import os
import re
import requests
from datetime import datetime
from pathlib import Path
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("warframe-market")
API_BASE = "https://api.warframe.market/v2"
API_V1 = "https://api.warframe.market/v1"
WFSTAT = "https://api.warframestat.us/pc"
HEADERS = {"Accept": "application/json", "Language": "en"}
TOOLKIT_DIR = Path(__file__).parent
VERIFIED_JSON = TOOLKIT_DIR / "syndicate_mods_verified.json"
PRICE_HISTORY = TOOLKIT_DIR / "price_history.json"
DE_USAGE_URL = "https://www-static.warframe.com/repos/WarframeUsageData{year}.json"
# Cache item list so we don't spam the API
_item_cache = None
_syndicate_cache = None
def _get_items():
"""Fetch and cache all tradeable items."""
global _item_cache
if _item_cache is None:
res = requests.get(f"{API_BASE}/items", headers=HEADERS, timeout=10)
res.raise_for_status()
_item_cache = res.json()["data"]
return _item_cache
def _find_item_slug(query: str) -> tuple[str, str]:
"""Fuzzy match an item name to its slug. Returns (slug, matched_name)."""
items = _get_items()
query_lower = query.lower().strip()
# Exact match first
for item in items:
name = item["i18n"]["en"]["name"].lower()
if name == query_lower:
return item["slug"], item["i18n"]["en"]["name"]
# Partial match
matches = []
for item in items:
name = item["i18n"]["en"]["name"].lower()
if query_lower in name:
matches.append((item["slug"], item["i18n"]["en"]["name"]))
if matches:
matches.sort(key=lambda x: len(x[1]))
return matches[0]
# Word-based fuzzy match
query_words = set(query_lower.split())
best = None
best_score = 0
for item in items:
name = item["i18n"]["en"]["name"].lower()
name_words = set(name.split())
score = len(query_words & name_words)
if score > best_score:
best_score = score
best = (item["slug"], item["i18n"]["en"]["name"])
if best and best_score >= 1:
return best
return None, None
def _load_syndicate_data():
"""Load verified syndicate mod data."""
global _syndicate_cache
if _syndicate_cache is None:
if VERIFIED_JSON.exists():
with open(VERIFIED_JSON) as f:
_syndicate_cache = json.load(f)
else:
_syndicate_cache = {}
return _syndicate_cache
def _get_syndicate_mods(syndicate_name: str) -> list[str]:
"""Get all mods for a syndicate from verified data."""
data = _load_syndicate_data()
syndicates = data.get("syndicates", {})
# Fuzzy match syndicate name
name_lower = syndicate_name.lower().strip()
matched_key = None
for key in syndicates:
if name_lower in key.lower() or key.lower() in name_lower:
matched_key = key
break
if not matched_key:
return []
syn = syndicates[matched_key]
mods = list(syn.get("weapon_augments", []))
for wf_mods in syn.get("warframe_augments", {}).values():
mods.extend(wf_mods)
return mods
def _fetch_statistics(slug: str) -> dict:
"""Fetch v1 /statistics endpoint for a slug. Returns {} on failure."""
try:
res = requests.get(f"{API_V1}/items/{slug}/statistics",
headers=HEADERS, timeout=10)
if res.status_code != 200:
return {}
return res.json().get("payload", {}).get("statistics_closed", {})
except Exception:
return {}
def _traded_median_from_stats(stats: dict, days: int = 7):
"""Compute volume-weighted median of traded prices over last N days.
Returns (median_price, avg_daily_volume) or (None, 0) if insufficient data.
"""
entries = stats.get("90days", []) or []
if not entries:
return (None, 0)
# Last N daily entries (api returns chronologically sorted)
recent = entries[-days:]
total_vol = sum(e.get("volume", 0) for e in recent)
if total_vol < 5: # need at least 5 trades in window
return (None, total_vol / max(len(recent), 1))
# Volume-weighted median of daily medians
# Expand: treat each daily median as weighted by its volume
weighted = []
for e in recent:
median = e.get("median", e.get("avg_price", 0))
vol = e.get("volume", 0)
weighted.extend([median] * int(vol))
if not weighted:
return (None, 0)
weighted.sort()
mid = len(weighted) // 2
if len(weighted) % 2 == 0:
median_price = (weighted[mid - 1] + weighted[mid]) / 2
else:
median_price = weighted[mid]
avg_daily_volume = total_vol / len(recent)
return (median_price, avg_daily_volume)
def _liquidity_tier(avg_daily_volume: float) -> str:
"""Map daily volume to a liquidity label."""
if avg_daily_volume >= 10:
return "HIGH"
if avg_daily_volume >= 3:
return "MED"
if avg_daily_volume > 0:
return "LOW"
return "DEAD"
def _quick_price(item_name: str) -> dict:
"""Get accurate price for an item.
Priority:
1. Volume-weighted median of last 7 days of actual trades (source='traded_7d')
2. Fallback: bottom-3 online sellers avg (source='orderbook') with warning
3. DEAD: no trades + no sellers (source='none')
Returns:
{
name, avg, low, orders,
volume (daily avg), liquidity ('HIGH'|'MED'|'LOW'|'DEAD'),
source ('traded_7d'|'orderbook'|'none'),
warning (str or None),
error (str or None)
}
"""
slug, matched_name = _find_item_slug(item_name)
if not slug:
return {"name": item_name, "low": 0, "avg": 0, "orders": 0,
"volume": 0, "liquidity": "DEAD", "source": "none",
"warning": None, "error": "not found"}
# 1. Fetch both order book and statistics in parallel (sequential is fine here)
order_err = None
sell_orders = []
try:
res = requests.get(f"{API_BASE}/orders/item/{slug}", headers=HEADERS, timeout=10)
if res.status_code == 200:
data = res.json().get("data", [])
if isinstance(data, list):
sell_orders = [o for o in data if o.get("type") == "sell"
and o.get("user", {}).get("status") in ("ingame", "online")]
if not sell_orders:
sell_orders = [o for o in data if o.get("type") == "sell"]
else:
order_err = f"orders api {res.status_code}"
except Exception as e:
order_err = str(e)
stats = _fetch_statistics(slug)
# Low price from order book (for undercut reference)
low_price = 0
if sell_orders:
sell_orders.sort(key=lambda x: x.get("platinum", 999999))
low_price = sell_orders[0].get("platinum", 0)
# Listed avg of bottom 3 (for warning comparison)
listed_avg = 0
if sell_orders:
bottom_3 = [o.get("platinum", 0) for o in sell_orders[:3]]
listed_avg = sum(bottom_3) / len(bottom_3)
# 2. Primary: traded median from last 7 days
traded_median, avg_daily_vol = _traded_median_from_stats(stats, days=7)
if traded_median is not None:
warning = None
# Warning if listed avg >> traded median (stale holdouts)
if listed_avg > 0 and traded_median > 0:
diff_ratio = abs(listed_avg - traded_median) / traded_median
if diff_ratio > 0.3:
warning = (f"Listed avg {listed_avg:.0f}p differs from traded "
f"median {traded_median:.0f}p — list near {int(max(low_price, traded_median - 1))}p")
return {
"name": matched_name,
"avg": round(traded_median),
"low": low_price,
"orders": len(sell_orders),
"volume": round(avg_daily_vol, 1),
"liquidity": _liquidity_tier(avg_daily_vol),
"source": "traded_7d",
"warning": warning,
"error": None,
}
# 3. Fallback: bottom-3 online sellers
if sell_orders and len(sell_orders) >= 1:
n = min(3, len(sell_orders))
bottom_n_prices = [o.get("platinum", 0) for o in sell_orders[:n]]
fallback_avg = sum(bottom_n_prices) / len(bottom_n_prices)
return {
"name": matched_name,
"avg": round(fallback_avg),
"low": low_price,
"orders": len(sell_orders),
"volume": 0,
"liquidity": "LOW",
"source": "orderbook",
"warning": "no recent trades — price estimated from listings only",
"error": None,
}
# 4. Dead: no data at all
return {
"name": matched_name, "avg": 0, "low": 0, "orders": 0,
"volume": 0, "liquidity": "DEAD", "source": "none",
"warning": "no trades and no listings", "error": order_err,
}
def _save_price_history(syndicate: str, prices: list[dict]):
"""Append price scan to history file."""
history = {}
if PRICE_HISTORY.exists():
with open(PRICE_HISTORY) as f:
history = json.load(f)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
if syndicate not in history:
history[syndicate] = []
entry = {
"date": timestamp,
"mods": {p["name"]: {"low": p["low"], "avg": p["avg"], "orders": p["orders"]}
for p in prices if not p.get("error")},
}
history[syndicate].append(entry)
# Keep last 30 scans per syndicate
if len(history[syndicate]) > 30:
history[syndicate] = history[syndicate][-30:]
with open(PRICE_HISTORY, "w") as f:
json.dump(history, f, indent=2)
# ============================================================
# MARKET TOOLS — price_check, search_items, price_check_multiple, trending_items, item_statistics
# ============================================================
@mcp.tool()
def price_check(item_name: str) -> str:
"""Look up the current price of any Warframe tradeable item on warframe.market.
Returns the cheapest sell orders from online/in-game players, plus average price stats.
Works for mods, prime parts, arcanes, sets, blueprints, etc.
"""
slug, matched_name = _find_item_slug(item_name)
if not slug:
return f"Could not find item matching '{item_name}'. Try a more specific name."
try:
res = requests.get(f"{API_BASE}/orders/item/{slug}", headers=HEADERS, timeout=10)
res.raise_for_status()
data = res.json()["data"]
except Exception as e:
try:
res = requests.get(
f"https://api.warframe.market/v1/items/{slug}/orders",
headers=HEADERS, timeout=10
)
res.raise_for_status()
data = res.json()["payload"]["orders"]
except Exception:
return f"Found '{matched_name}' but failed to fetch orders: {e}"
if isinstance(data, list):
sell_orders = [o for o in data if o.get("type") == "sell"
and o.get("user", {}).get("status") in ("ingame", "online")]
else:
sell_orders = []
if not sell_orders and isinstance(data, list):
sell_orders = [o for o in data if o.get("type") == "sell"]
if sell_orders:
sell_orders.sort(key=lambda x: x.get("platinum", 999999))
sell_orders = sell_orders[:15]
if not sell_orders:
return f"**{matched_name}** — No active sell orders found."
sell_orders.sort(key=lambda x: x.get("platinum", 999999))
lines = [f"**{matched_name}** — Price Check\n"]
lines.append("| # | Price | Seller | Status | Quantity |")
lines.append("|---|-------|--------|--------|----------|")
for i, order in enumerate(sell_orders[:10]):
user = order.get("user", {})
name = user.get("ingameName", user.get("ingame_name", "Unknown"))
status = user.get("status", "?")
plat = order.get("platinum", "?")
qty = order.get("quantity", 1)
mod_rank = order.get("rank", order.get("mod_rank"))
rank_str = f" (R{mod_rank})" if mod_rank is not None else ""
lines.append(f"| {i+1} | {plat}p{rank_str} | {name} | {status} | {qty} |")
prices = [o.get("platinum", 0) for o in sell_orders[:20]]
if prices:
avg = sum(prices) / len(prices)
lines.append(f"\n**Lowest:** {prices[0]}p | **Average (top 20):** {avg:.0f}p | **Orders:** {len(sell_orders)}")
return "\n".join(lines)
@mcp.tool()
def search_items(query: str) -> str:
"""Search for Warframe items by name. Returns matching items with their slugs.
Use this when you're not sure of the exact item name.
"""
items = _get_items()
query_lower = query.lower().strip()
matches = []
for item in items:
name = item["i18n"]["en"]["name"]
if query_lower in name.lower():
tags = ", ".join(item.get("tags", []))
matches.append(f"- **{name}** (slug: `{item['slug']}`, tags: {tags})")
if not matches:
return f"No items found matching '{query}'."
if len(matches) > 25:
matches = matches[:25]
matches.append(f"\n... and more. Try a more specific search.")
return f"**Items matching '{query}'** ({len(matches)} results):\n\n" + "\n".join(matches)
@mcp.tool()
def price_check_multiple(item_names: str) -> str:
"""Check prices for multiple items at once. Provide comma-separated item names.
Great for comparing values of items from a screenshot.
Example: 'Condition Overload, Blind Rage, Primed Flow'
"""
names = [n.strip() for n in item_names.split(",") if n.strip()]
results = []
icon_map = {"HIGH": "🟢", "MED": "🟡", "LOW": "🟠", "DEAD": "⚫"}
for name in names:
p = _quick_price(name)
if p.get("error") == "not found":
results.append(f"- **{name}** — Not found")
continue
if p["avg"] == 0:
results.append(f"- **{p['name']}** — No trades or sellers")
continue
icon = icon_map.get(p.get("liquidity", ""), "")
src = p.get("source", "")
src_tag = " (listings only)" if src == "orderbook" else ""
warn = " ⚠️" if p.get("warning") else ""
results.append(
f"- **{p['name']}**{warn} — Median: {p['avg']}p | Low: {p['low']}p | "
f"Vol: {p.get('volume', 0)}/d {icon} | Sellers: {p['orders']}{src_tag}"
)
lines = ["**Multi-Item Price Check:** (7-day traded median)"]
lines.extend(results)
return "\n".join(lines)
@mcp.tool()
def trending_items() -> str:
"""Get the most actively traded items on warframe.market right now.
Checks a curated list of high-volume items using live sell orders for accurate prices.
"""
popular_slugs = [
"condition_overload", "blind_rage", "adaptation", "rolling_guard",
"primed_continuity", "primed_flow", "primed_pressure_point",
"growing_power", "steel_charge", "energy_siphon",
"arcane_energize", "arcane_grace", "arcane_avenger", "arcane_guardian",
"overextended", "transient_fortitude", "narrow_minded", "fleeting_expertise",
"galvanized_chamber", "galvanized_hell", "galvanized_aptitude", "galvanized_diffusion",
"melee_influence", "melee_exposure", "melee_vortex", "melee_animosity",
"combat_discipline", "brief_respite", "primary_merciless", "secondary_dexterity",
]
results = []
for slug in popular_slugs:
try:
res = requests.get(f"{API_BASE}/orders/item/{slug}", headers=HEADERS, timeout=5)
if res.status_code != 200:
continue
data = res.json()["data"]
if not isinstance(data, list):
continue
sells = [o for o in data if o.get("type") == "sell"
and o.get("user", {}).get("status") in ("ingame", "online")]
if not sells:
sells = [o for o in data if o.get("type") == "sell"]
if not sells:
continue
sells.sort(key=lambda x: x.get("platinum", 999999))
prices = [o.get("platinum", 0) for o in sells[:10]]
name = sells[0].get("item", {}).get("i18n", {}).get("en", {}).get("name", slug.replace("_", " ").title())
results.append((name, prices[0], round(sum(prices) / len(prices)), len(sells)))
except Exception:
continue
results.sort(key=lambda x: x[2], reverse=True)
lines = ["**Trending Items — Live Prices:**\n"]
lines.append("| Item | Low | Avg | Sellers |")
lines.append("|------|-----|-----|---------|")
for name, low, avg, orders in results:
lines.append(f"| {name} | {low}p | {avg}p | {orders} |")
return "\n".join(lines)
@mcp.tool()
def item_statistics(item_name: str) -> str:
"""Get detailed price statistics and history for an item.
Shows 48-hour and 90-day price trends, volume, min/max prices.
"""
slug, matched_name = _find_item_slug(item_name)
if not slug:
return f"Could not find item matching '{item_name}'."
try:
res = requests.get(
f"https://api.warframe.market/v1/items/{slug}/statistics",
headers=HEADERS, timeout=10
)
res.raise_for_status()
data = res.json()["payload"]["statistics_closed"]
stats_48h = data.get("48hours", [])
stats_90d = data.get("90days", [])
lines = [f"**{matched_name}** — Price Statistics\n"]
if stats_48h:
recent = stats_48h[-1]
lines.append("**Last 48 Hours:**")
lines.append(f"- Avg: {recent.get('avg_price', 'N/A')}p")
lines.append(f"- Min: {recent.get('min_price', 'N/A')}p")
lines.append(f"- Max: {recent.get('max_price', 'N/A')}p")
lines.append(f"- Volume: {recent.get('volume', 'N/A')} trades")
lines.append(f"- Median: {recent.get('median', 'N/A')}p")
if stats_90d:
lines.append("\n**90-Day Trend (last 5 data points):**")
lines.append("| Date | Avg | Min | Max | Volume |")
lines.append("|------|-----|-----|-----|--------|")
for stat in stats_90d[-5:]:
date = stat.get("datetime", "")[:10]
lines.append(
f"| {date} | {stat.get('avg_price', '?')}p | "
f"{stat.get('min_price', '?')}p | {stat.get('max_price', '?')}p | "
f"{stat.get('volume', '?')} |"
)
return "\n".join(lines)
except Exception as e:
return f"Failed to get statistics for {matched_name}: {e}"
# ============================================================
# SYNDICATE TOOLS — syndicate_lookup, best_buys, price_history
# ============================================================
@mcp.tool()
def syndicate_lookup(syndicate_name: str) -> str:
"""Look up all verified mods for a syndicate with live prices, sorted by profit.
Uses wiki-verified data (syndicate_mods_verified.json) — no guessing.
Example: syndicate_lookup('Arbiters of Hexis')
"""
data = _load_syndicate_data()
if not data:
return "Error: syndicate_mods_verified.json not found. Run wiki scraper first."
syndicates = data.get("syndicates", {})
name_lower = syndicate_name.lower().strip()
matched_key = None
for key in syndicates:
if name_lower in key.lower() or key.lower() in name_lower:
matched_key = key
break
if not matched_key:
available = ", ".join(syndicates.keys())
return f"Syndicate '{syndicate_name}' not found. Available: {available}"
syn = syndicates[matched_key]
all_mods = list(syn.get("weapon_augments", []))
warframe_map = syn.get("warframe_augments", {})
for wf_mods in warframe_map.values():
all_mods.extend(wf_mods)
# Build warframe lookup
mod_to_warframe = {}
for wf, mods in warframe_map.items():
for mod in mods:
mod_to_warframe[mod] = wf
for mod in syn.get("weapon_augments", []):
mod_to_warframe[mod] = "Weapon"
# Price check all mods
priced = []
for mod in all_mods:
p = _quick_price(mod)
p["warframe"] = mod_to_warframe.get(mod, "?")
priced.append(p)
# Save to price history
_save_price_history(matched_key, priced)
# Sort by avg price descending
priced.sort(key=lambda x: x["avg"], reverse=True)
lines = [f"**{matched_key}** — {len(priced)} mods (traded median, last 7d)\n"]
# Split into tiers
rare = [p for p in priced if p["avg"] >= 20]
good = [p for p in priced if 15 <= p["avg"] < 20]
common = [p for p in priced if 10 <= p["avg"] < 15]
cheap = [p for p in priced if p["avg"] < 10]
def liq_icon(p):
tier = p.get("liquidity", "?")
return {"HIGH": "🟢", "MED": "🟡", "LOW": "🟠", "DEAD": "⚫"}.get(tier, "❓")
def row(p):
flag = " ⚠️" if p.get("warning") else ""
src = p.get("source", "?")
vol = p.get("volume", 0)
return (f"| {p['name']}{flag} | {p['avg']}p | {p['low']}p | "
f"{vol}/d {liq_icon(p)} | {p['orders']} | {p['warframe']} |")
def table_header():
return (["| Mod | Median | Low | Vol | Sellers | Frame |",
"|-----|--------|-----|-----|---------|-------|"])
if rare:
lines.append("**RARE SELLS (20p+):**")
lines.extend(table_header())
for p in rare: lines.append(row(p))
if good:
lines.append("\n**CONSISTENT (15-19p):**")
lines.extend(table_header())
for p in good: lines.append(row(p))
if common:
lines.append("\n**QUICK SELLS (10-14p):**")
lines.extend(table_header())
for p in common: lines.append(row(p))
if cheap:
lines.append(f"\n**LOW VALUE (<10p):** {', '.join(p['name'] + ' (' + str(p['avg']) + 'p)' for p in cheap)}")
# Warnings summary — show stale-listing mods
warnings = [p for p in priced if p.get("warning") and p["avg"] >= 10]
if warnings:
lines.append("\n**⚠️ Stale Listings Detected** (listed avg differs from actual traded median):")
for p in warnings[:10]:
lines.append(f"- **{p['name']}**: {p['warning']}")
# Summary
all_avg = [p["avg"] for p in priced if p["avg"] > 0]
if all_avg:
top5 = sorted(all_avg, reverse=True)[:5]
high_liq = sum(1 for p in priced if p.get("liquidity") == "HIGH")
med_liq = sum(1 for p in priced if p.get("liquidity") == "MED")
lines.append(f"\n**Summary:** Avg all={sum(all_avg)/len(all_avg):.1f}p | "
f"Top 5 avg={sum(top5)/5:.1f}p | 20p+ mods={len(rare)} | "
f"🟢High liq={high_liq} 🟡Med={med_liq}")
lines.append("\n*Prices = volume-weighted median of actual trades last 7d. "
"⚠️ = listings inflated above real market. List near 'Low' to sell fast.*")
return "\n".join(lines)
@mcp.tool()
def best_buys(syndicate_name: str, standing: int = 100000) -> str:
"""Get optimal shopping list for a syndicate given your available standing.
Ranks mods by plat-per-standing efficiency and tells you exactly what to buy.
Each augment costs 25,000 standing. Example: best_buys('Cephalon Suda', 132000)
"""
mods = _get_syndicate_mods(syndicate_name)
if not mods:
return f"Syndicate '{syndicate_name}' not found or no verified data."
# Price all mods
priced = []
for mod in mods:
p = _quick_price(mod)
if not p.get("error") and p["avg"] > 0:
p["efficiency"] = round(p["avg"] / 25, 2) # plat per 1k standing
priced.append(p)
priced.sort(key=lambda x: x["avg"], reverse=True)
cost_per_mod = 25000
budget = standing
cart = []
total_plat = 0
for p in priced:
if budget >= cost_per_mod:
cart.append(p)
budget -= cost_per_mod
total_plat += p["avg"]
lines = [f"**Best Buys — {standing:,} standing budget**\n"]
lines.append(f"Can buy **{len(cart)} mods** (25,000 standing each)\n")
lines.append("| # | Buy This | Avg Price | Efficiency | Orders |")
lines.append("|---|----------|-----------|------------|--------|")
for i, p in enumerate(cart):
lines.append(f"| {i+1} | {p['name']} | {p['avg']}p | {p['efficiency']}p/1k | {p['orders']} |")
lines.append(f"\n**Total expected plat: ~{total_plat}p** from {len(cart)} trades")
lines.append(f"**Standing left over: {budget:,}**")
if priced:
lines.append(f"\n**Best single buy:** {priced[0]['name']} at {priced[0]['avg']}p ({priced[0]['efficiency']}p per 1k standing)")
return "\n".join(lines)
@mcp.tool()
def price_history(syndicate_name: str) -> str:
"""Show price trend history for a syndicate's mods across multiple scans.
Tracks how prices change over time. Run syndicate_lookup first to record data.
"""
if not PRICE_HISTORY.exists():
return "No price history yet. Run syndicate_lookup on a syndicate first to start tracking."
with open(PRICE_HISTORY) as f:
history = json.load(f)
# Fuzzy match
name_lower = syndicate_name.lower().strip()
matched_key = None
for key in history:
if name_lower in key.lower() or key.lower() in name_lower:
matched_key = key
break
if not matched_key or not history[matched_key]:
available = ", ".join(history.keys()) if history else "none"
return f"No history for '{syndicate_name}'. Available: {available}"
scans = history[matched_key]
lines = [f"**{matched_key}** — Price History ({len(scans)} scans)\n"]
if len(scans) < 2:
lines.append("Only 1 scan recorded. Run syndicate_lookup again later to track changes.")
scan = scans[0]
lines.append(f"\nScan date: {scan['date']}")
top = sorted(scan["mods"].items(), key=lambda x: x[1]["avg"], reverse=True)[:10]
lines.append("| Mod | Avg | Low | Orders |")
lines.append("|-----|-----|-----|--------|")
for name, data in top:
lines.append(f"| {name} | {data['avg']}p | {data['low']}p | {data['orders']} |")
return "\n".join(lines)
# Compare latest vs previous
latest = scans[-1]
previous = scans[-2]
lines.append(f"Latest scan: {latest['date']} | Previous: {previous['date']}\n")
# Find biggest movers
movers = []
for mod, curr in latest["mods"].items():
if mod in previous["mods"]:
prev = previous["mods"][mod]
diff = curr["avg"] - prev["avg"]
if diff != 0:
movers.append((mod, prev["avg"], curr["avg"], diff))
movers.sort(key=lambda x: abs(x[3]), reverse=True)
if movers:
lines.append("**Biggest Price Changes:**")
lines.append("| Mod | Was | Now | Change |")
lines.append("|-----|-----|-----|--------|")
for mod, prev_avg, curr_avg, diff in movers[:15]:
arrow = "+" if diff > 0 else ""
lines.append(f"| {mod} | {prev_avg}p | {curr_avg}p | {arrow}{diff}p |")
else:
lines.append("No price changes detected between scans.")
# Overall trend
latest_avgs = [v["avg"] for v in latest["mods"].values() if v["avg"] > 0]
prev_avgs = [v["avg"] for v in previous["mods"].values() if v["avg"] > 0]
if latest_avgs and prev_avgs:
curr_mean = sum(latest_avgs) / len(latest_avgs)
prev_mean = sum(prev_avgs) / len(prev_avgs)
trend = "UP" if curr_mean > prev_mean else "DOWN" if curr_mean < prev_mean else "FLAT"
lines.append(f"\n**Overall trend:** {trend} (avg {prev_mean:.1f}p → {curr_mean:.1f}p)")
return "\n".join(lines)
# ============================================================
# PHASE 2 — WORLD STATE & ARBITRAGE TOOLS
# ============================================================
@mcp.tool()
def fissure_sniper() -> str:
"""Find the fastest active Void Fissures for relic cracking.
Filters for Capture/Exterminate missions on Meso/Neo/Axi tiers only —
the fastest mission types for speed-cracking relics.
"""
try:
res = requests.get(f"{WFSTAT}/fissures", headers=HEADERS, timeout=10)
res.raise_for_status()
fissures = res.json()
except Exception as e:
return f"Failed to fetch fissures: {e}"
fast_types = {"Capture", "Exterminate"}
good_tiers = {"Meso", "Neo", "Axi"}
filtered = [
f for f in fissures
if f.get("missionType") in fast_types
and f.get("tier") in good_tiers
and not f.get("expired", False)
]
if not filtered:
lines = ["**Fissure Sniper** — No fast fissures right now.\n"]
lines.append("No Capture/Exterminate fissures active for Meso/Neo/Axi tiers.")
lines.append("Current fissures are slower mission types. Check back in a few minutes.\n")
all_good = [f for f in fissures if f.get("tier") in good_tiers and not f.get("expired", False)]
if all_good:
lines.append("**All Meso/Neo/Axi fissures (any type):**")
lines.append("| Tier | Node | Type | Enemy | Expires |")
lines.append("|------|------|------|-------|---------|")
for f in sorted(all_good, key=lambda x: good_tiers.__iter__().__next__):
lines.append(
f"| {f.get('tier', '?')} | {f.get('node', '?')} | "
f"{f.get('missionType', '?')} | {f.get('enemy', '?')} | "
f"{f.get('eta', '?')} |"
)
return "\n".join(lines)
# Sort by tier priority: Axi > Neo > Meso
tier_order = {"Axi": 0, "Neo": 1, "Meso": 2}
filtered.sort(key=lambda x: tier_order.get(x.get("tier", ""), 99))
lines = [f"**Fissure Sniper** — {len(filtered)} fast fissures found\n"]
lines.append("| Tier | Node | Type | Enemy | Expires |")
lines.append("|------|------|------|-------|---------|")
for f in filtered:
lines.append(
f"| {f.get('tier', '?')} | {f.get('node', '?')} | "
f"{f.get('missionType', '?')} | {f.get('enemy', '?')} | "
f"{f.get('eta', '?')} |"
)
lines.append("\nThese are Capture/Exterminate only — fastest for cracking relics.")
return "\n".join(lines)
@mcp.tool()
def world_state_dashboard() -> str:
"""Quick weekly endgame tracker. Shows Archon Hunt, Duviri Cycle, and Sortie
status in one view — everything you need for your weekly reset.
"""
try:
res = requests.get(WFSTAT, headers=HEADERS, timeout=10)
res.raise_for_status()
state = res.json()
except Exception as e:
return f"Failed to fetch world state: {e}"
lines = ["**World State Dashboard**\n"]
# Archon Hunt
archon = state.get("archonHunt")
if archon:
lines.append("**Archon Hunt:**")
boss = archon.get("boss", "Unknown")
eta = archon.get("eta", "?")
lines.append(f"- Boss: {boss}")
lines.append(f"- Resets in: {eta}")
missions = archon.get("missions", [])
if missions:
lines.append("- Missions:")
for m in missions:
node = m.get("node", "?")
mtype = m.get("type", "?")
lines.append(f" - {mtype} — {node}")
else:
lines.append("**Archon Hunt:** No data available")
lines.append("")
# Duviri Cycle
duviri = state.get("duviriCycle")
if duviri:
mood = duviri.get("state", "Unknown")
eta = duviri.get("eta", "?")
lines.append(f"**Duviri Cycle:** {mood} (changes in {eta})")
else:
lines.append("**Duviri Cycle:** No data available")
lines.append("")
# Sortie
sortie = state.get("sortie")
if sortie:
lines.append("**Sortie:**")
boss = sortie.get("boss", "Unknown")
eta = sortie.get("eta", "?")
lines.append(f"- Boss: {boss}")
lines.append(f"- Resets in: {eta}")
variants = sortie.get("variants", [])
if variants:
lines.append("- Missions:")
for v in variants:
node = v.get("node", "?")
mtype = v.get("missionType", "?")
modifier = v.get("modifier", "")
mod_desc = v.get("modifierDescription", "")
line = f" - {mtype} — {node}"
if modifier:
line += f" [{modifier}]"
lines.append(line)
else:
lines.append("**Sortie:** No data available")
return "\n".join(lines)
@mcp.tool()
def baro_tracker() -> str:
"""Check Baro Ki'Teer's status and inventory.
Shows when he arrives (if gone) or what he's selling (if active) with Ducat/Credit costs.
"""
try:
res = requests.get(f"{WFSTAT}/voidTrader", headers=HEADERS, timeout=10)
res.raise_for_status()
baro = res.json()
except Exception as e:
return f"Failed to fetch Baro Ki'Teer data: {e}"
active = baro.get("active", False)
if not active:
arrival = baro.get("startString", baro.get("activation", "Unknown"))
relay = baro.get("location", "TBD")
lines = ["**Baro Ki'Teer** — Not here yet\n"]
lines.append(f"- Arrives: {arrival}")
lines.append(f"- Location: {relay}")
lines.append("\nCheck back when he arrives for his inventory.")
return "\n".join(lines)
# Baro is active
location = baro.get("location", "Unknown")
end_string = baro.get("endString", baro.get("eta", "?"))
inventory = baro.get("inventory", [])
lines = [f"**Baro Ki'Teer** — Active at {location}\n"]
lines.append(f"Leaves in: {end_string}\n")
if inventory:
lines.append(f"**Inventory ({len(inventory)} items):**")
lines.append("| Item | Ducats | Credits |")
lines.append("|------|--------|---------|")
for item in inventory:
name = item.get("item", "Unknown")
ducats = item.get("ducats", 0)
credits = item.get("credits", 0)
lines.append(f"| {name} | {ducats:,} | {credits:,} |")
else:
lines.append("Inventory not yet loaded or empty.")
return "\n".join(lines)
@mcp.tool()
def market_spread_finder(item_name: str) -> str:
"""Find the flip margin between Buy and Sell orders for a specific item.
Shows the highest buy offer, lowest sell listing, and the platinum spread.
Use this to find arbitrage opportunities — buy low from buy orders, sell at sell price.
Example: market_spread_finder('Condition Overload')
"""
slug, matched_name = _find_item_slug(item_name)
if not slug:
return f"Could not find item matching '{item_name}'. Try a more specific name."
try:
res = requests.get(
f"{API_V1}/items/{slug}/orders",
headers={**HEADERS, "Platform": "pc"},
timeout=10,
)
res.raise_for_status()
orders = res.json()["payload"]["orders"]
except Exception as e:
# Fallback to v2
try:
res = requests.get(f"{API_BASE}/orders/item/{slug}", headers=HEADERS, timeout=10)
res.raise_for_status()
orders = res.json()["data"]
except Exception:
return f"Failed to fetch orders for '{matched_name}': {e}"
# Filter for online/ingame users only
live = [o for o in orders if o.get("user", {}).get("status") in ("ingame", "online")]
if not live:
live = orders # Fall back to all orders
sells = [o for o in live if o.get("order_type", o.get("type")) == "sell"]
buys = [o for o in live if o.get("order_type", o.get("type")) == "buy"]
if not sells and not buys:
return f"**{matched_name}** — No active orders found."
lowest_sell = min((o.get("platinum", 999999) for o in sells), default=None) if sells else None
highest_buy = max((o.get("platinum", 0) for o in buys), default=None) if buys else None
lines = [f"**{matched_name}** — Market Spread Analysis\n"]
if lowest_sell is not None:
lines.append(f"- Lowest Sell: **{lowest_sell}p** ({len(sells)} sell orders)")
else:
lines.append("- Lowest Sell: No sell orders")
if highest_buy is not None:
lines.append(f"- Highest Buy: **{highest_buy}p** ({len(buys)} buy orders)")
else:
lines.append("- Highest Buy: No buy orders")
if lowest_sell is not None and highest_buy is not None:
spread = lowest_sell - highest_buy
if spread > 0:
lines.append(f"\n**Spread: {spread}p** profit per flip")
lines.append(f"Buy at {highest_buy}p (buy order) -> Sell at {lowest_sell}p (sell listing)")
if spread >= 10:
lines.append("HIGH margin — worth flipping.")
elif spread >= 5:
lines.append("Decent margin — viable if volume is there.")