# /// script
# requires-python = ">=3.10"
# dependencies = ["mcp>=2", "httpx"]
# ///
"""LabelYX MCP server: Hyperliquid wallet and market analytics for Claude,
Cursor and any other MCP client. https://labelyx.com/tools/mcp

Install (needs uv: https://docs.astral.sh/uv/):

    claude mcp add labelyx -- uv run https://labelyx.com/labelyx-mcp.py

or, in Claude Desktop / Cursor config:

    {"mcpServers": {"labelyx": {"command": "uv",
                                "args": ["run", "https://labelyx.com/labelyx-mcp.py"]}}}

Why a script you run rather than a URL you add: Hyperliquid meters API reads
per IP. This script fetches a wallet's Hyperliquid data on YOUR machine and
posts it to labelyx.com, which does the maths and sends back the numbers. It
is the same protocol the website's own pages use, so LabelYX's shared budget
is never spent on your lookups. Market tools (funding, leaderboard, vaults)
read LabelYX's cache and need no Hyperliquid call at all.
Read-only: no keys, no signatures, no trading.
"""
import os
import re
from typing import Any

import httpx
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations

__version__ = "0.2.0"

BASE = os.environ.get("LABELYX_URL", "https://labelyx.com").rstrip("/")
SITE = "https://labelyx.com"  # links in results always point at the public site
HL_URL = "https://api.hyperliquid.xyz/info"
MAX_ROUNDS = 4  # matches client_store.MAX_ROUNDS on the server
MAX_ITEMS = 25  # longest list a tool returns; the dashboard has the rest
ADDRESS = re.compile(r"^0x[0-9a-fA-F]{40}$")
WINDOWS = ("day", "week", "month", "allTime")
# Chart series the web page draws. An assistant needs the numbers, not the lines.
_SERIES = {"data", "labels", "pnl_data", "pnl_labels", "val_data", "val_labels",
           "daily", "daily30", "timeline", "funding_per_day", "pnl_by_hour"}

http = httpx.Client(timeout=30, headers={"User-Agent": f"labelyx-mcp/{__version__}"})


def labelyx(path: str, tool: str) -> Any:
    """Store protocol, as static/js/hl-client.js drives it: POST {store};
    while the reply carries X-HL-Need, fetch exactly {need} from Hyperliquid
    (on this machine's IP), add it to the store and POST again."""
    store: list = []
    headers = {"X-LabelYX-Tool": tool}  # usage logging on the server, nothing else
    try:
        for _ in range(MAX_ROUNDS):
            r = http.post(BASE + path, json={"store": store}, headers=headers)
            r.raise_for_status()
            if not r.headers.get("X-HL-Need"):
                return r.json()
            for payload in r.json().get("need", []):
                hl = http.post(HL_URL, json=payload)
                hl.raise_for_status()
                store.append([payload, hl.json()])
    except httpx.HTTPError as e:  # ToolError: the model reads the message
        raise ToolError(f"request failed: {e}") from e
    raise ToolError("LabelYX kept asking for more Hyperliquid data; try again")


def public(path: str, tool: str) -> Any:
    """Cached site data (markets, leaderboard, vaults): a plain GET."""
    try:
        r = http.get(BASE + path, headers={"X-LabelYX-Tool": tool})
        r.raise_for_status()
        return r.json()
    except httpx.HTTPError as e:
        raise ToolError(f"request failed: {e}") from e


def _addr(wallet: str) -> str:
    wallet = wallet.strip()
    if not ADDRESS.match(wallet):
        raise ToolError("wallet must be a Hyperliquid address: 0x followed by 40 hex characters")
    return wallet.lower()


def _limit(n: Any) -> int:
    try:
        return max(1, min(int(n), 100))
    except (TypeError, ValueError):
        return MAX_ITEMS


def slim(v: Any, url: str | None = None) -> Any:
    """Round floats (cents above 1, six significant digits below, so a
    sub-cent price keeps its precision) and cap every list at MAX_ITEMS, so a
    result stays a few thousand tokens. A capped dict says so."""
    cut = 0

    def walk(x):
        nonlocal cut
        if isinstance(x, float):
            return round(x, 2) if abs(x) >= 1 else float(f"{x:.6g}")
        if isinstance(x, dict):
            return {k: walk(y) for k, y in x.items()}
        if isinstance(x, list):
            if len(x) > MAX_ITEMS:
                cut += len(x) - MAX_ITEMS
            return [walk(y) for y in x[:MAX_ITEMS]]
        return x

    out = walk(v)
    if isinstance(out, dict):
        if url:
            out["url"] = url
        if cut:
            out["note"] = f"lists capped at {MAX_ITEMS} items ({cut} omitted); the full view is at the url"
    return out


mcp = MCPServer(
    "labelyx",
    instructions=(
        "Read-only Hyperliquid analytics from labelyx.com. Wallet tools take a public address "
        "(0x + 40 hex); market tools take none. Numbers are live and time-sensitive; USD unless "
        "stated; funding rates are per hour (Hyperliquid pays funding hourly). Every result has a "
        "`url` field: give it to the user for the full view. This is analysis, not financial advice."
    ),
)


def tool(title: str):
    """Every tool only reads public data; the directories want that explicit."""
    return mcp.tool(title=title, annotations=ToolAnnotations(
        title=title, readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=True))


# ── Wallet tools ─────────────────────────────────────────────────────────────

@tool("Wallet performance overview")
def get_wallet_overview(wallet: str, days: int | None = None) -> dict[str, Any]:
    """Trading performance of a Hyperliquid wallet: period PnL and %, win rate,
    closed-trade count, average win/loss, expectancy, fees, best/worst day and
    market, long/short split, leverage, risk score and open positions.
    `days` limits the look-back window (omit for all time)."""
    w = _addr(wallet)
    q = f"?days={max(1, min(int(days), 3650))}" if days else ""
    data = labelyx(f"/{w}/api/overview{q}", "get_wallet_overview")
    return slim({k: v for k, v in data.items() if k not in _SERIES}, f"{SITE}/{w}")


@tool("Wallet open positions and risk")
def get_wallet_positions(wallet: str) -> dict[str, Any]:
    """Open positions on every Hyperliquid DEX (main and HIP-3 builder DEXs)
    with size, entry, mark, unrealised PnL, margin, leverage and liquidation
    price, plus the risk book: liquidation ladder, concentration and a
    price-move stress test."""
    w = _addr(wallet)
    return slim(labelyx(f"/{w}/positions?book=1", "get_wallet_positions"), f"{SITE}/{w}/positions_page")


@tool("Wallet net deposits")
def get_net_deposits(wallet: str) -> dict[str, Any]:
    """Net capital deposited into a Hyperliquid wallet (deposits minus
    withdrawals). `complete` is false when the ledger hit Hyperliquid's history
    cap and the figure is understated. Compare with all-time PnL for true ROI."""
    w = _addr(wallet)
    return slim(labelyx(f"/{w}/api/net_deposited", "get_net_deposits"), f"{SITE}/{w}/portfolio")


@tool("Wallet money flow")
def get_money_flow(wallet: str) -> dict[str, Any]:
    """Where a Hyperliquid wallet's money comes from and goes: counterparties
    ranked by transfer volume, labelled as bridge, sub-account, vault or known
    trader where LabelYX can tell."""
    w = _addr(wallet)
    return slim(labelyx(f"/{w}/api/flow", "get_money_flow"), f"{SITE}/{w}/flow")


# ── Market tools (served from LabelYX's cache, no Hyperliquid call) ──────────

@tool("Hyperliquid markets and funding")
def list_markets(coin: str | None = None, sort: str = "oi", limit: int = MAX_ITEMS) -> dict[str, Any]:
    """Hyperliquid perpetual markets: price, hourly funding rate and its APR,
    predicted next funding, open interest, 24h volume and change, max
    leverage, on the main DEX and HIP-3 builder DEXs (`dex:COIN`). `coin`
    returns one market; otherwise the top `limit` by `sort`: "oi" (open
    interest), "funding" (largest funding either way) or "volume"."""
    q = f"?sort={sort}&limit={_limit(limit)}" + (f"&coin={coin.strip()}" if coin else "")
    url = f"{SITE}/markets/{coin.strip().upper()}" if coin else f"{SITE}/markets"
    return slim(public(f"/api/markets{q}", "list_markets"), url)


@tool("Hyperliquid trader leaderboard")
def get_leaderboard(window: str = "week", limit: int = MAX_ITEMS) -> dict[str, Any]:
    """Top Hyperliquid traders by PnL over `window`: "day", "week", "month"
    or "allTime", with ROI, volume, account value and address. Vaults are
    excluded, so every row is a wallet the wallet tools can analyze."""
    if window not in WINDOWS:
        raise ToolError(f"window must be one of {', '.join(WINDOWS)}")
    return slim(public(f"/api/leaderboard?window={window}&limit={_limit(limit)}", "get_leaderboard"),
                f"{SITE}/leaderboard")


@tool("Hyperliquid vaults")
def list_vaults(limit: int = MAX_ITEMS) -> dict[str, Any]:
    """Hyperliquid vaults by TVL with APR, leader address and whether the
    vault is protocol-run (HLP) or user-run."""
    return slim(public(f"/api/vaults?limit={_limit(limit)}", "list_vaults"), f"{SITE}/vaults")


# ── Prompt ───────────────────────────────────────────────────────────────────

@mcp.prompt(title="Review a Hyperliquid wallet")
def review_wallet(wallet: str) -> str:
    """A structured performance and risk review of one wallet."""
    w = _addr(wallet)
    return (
        f"Review Hyperliquid wallet {w} with the LabelYX tools. Call get_wallet_overview twice "
        "(all time, and days=30), then get_wallet_positions and get_net_deposits.\n\n"
        "Write a short report with these sections:\n"
        "1. Headline: all-time PnL vs net deposited (true ROI), and the last 30 days.\n"
        "2. Edge: win rate, average win vs loss, expectancy, fees as a share of gross profit.\n"
        "3. Risk now: leverage, margin used, the positions closest to liquidation, concentration.\n"
        "4. Habits: best and worst markets, long/short bias, anything the data flags.\n"
        "5. Verdict in two sentences.\n\n"
        "Numbers are live USD snapshots; say so. This is analysis, not financial advice. "
        f"End with the dashboard link https://labelyx.com/{w}."
    )


def main() -> None:
    mcp.run()


if __name__ == "__main__":
    main()
