#!/usr/bin/env python3
"""Serveur MCP OpenProp (01/12/2026) — sans dépendance (Python 3.9+ seul).

Transport stdio :   OPENPROP_API_KEY=opk_... python3 openprop_mcp.py
                    OPENPROP_API_URL=https://<serveur OpenProp>/pf-api   (adresse affichée sur la page /agents/)
Transport HTTP streamable : servi par l'API elle-même sur POST /api/mcp (Authorization: Bearer opk_...),
                    qui appelle `traiter()` ci-dessous avec un accès direct à /api/v1.

Garde-fous dans les outils : place_order lit d'abord rules_status, refuse un ordre au-delà de la place restante sous
le plafond de position, exige confirm_size=true au-delà de 50 % de la taille max, et chaque réponse rappelle la
perte restante avant le plancher. Aucun outil de retrait, payout ou adresse : la clé ne le permet pas non plus.
"""
import json, os, sys, urllib.error, urllib.request

VERSION = "1.1.0"
PROTO = "2025-06-18"
URL = os.environ.get("OPENPROP_API_URL", "").rstrip("/")
SEUIL_CONFIRM = 0.5        # au-delà de 50 % de la place disponible : confirmation explicite

INSTRUCTIONS = (
    "You trade ONE OpenProp account (evaluation, funded or free practice) through an API key. "
    "Before any order, call get_rules_status: never let equity reach the floor (the account ends). "
    "Long + short notional per market is capped; reducing or closing is always allowed. "
    "Always tell the user the remaining loss before the floor after each trade. "
    "Ask the user before large orders. You cannot withdraw, request payouts or change addresses. "
    "get_evaluation gives the rules this account was bought with; get_pricing gives today's prices (read-only).")

S_POS = {"type": "string", "description": "Position key: 'BTC:long' or 'BTC:short' (hedge mode)."}
OUTILS = [
    {"name": "get_account", "description": "Account summary: size, equity, balance, net P&L, floor, target, remaining loss before the floor.",
     "inputSchema": {"type": "object", "properties": {}}, "annotations": {"readOnlyHint": True}},
    {"name": "get_rules_status", "description": "Rule status: remaining loss before the floor, remaining gain to the target, max position per market and room left.",
     "inputSchema": {"type": "object", "properties": {}}, "annotations": {"readOnlyHint": True}},
    {"name": "get_evaluation", "description": "The rules this account was bought with: size, risk level, max loss, profit target, "
     "your share of gains and the price paid (locked). They never change for this account.",
     "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}, "annotations": {"readOnlyHint": True}},
    {"name": "get_pricing", "description": "Today's evaluation prices (read-only): live multiplier, displayed pass rate, price per size and split, "
     "and per risk level when configurable evaluations are open. Prices are locked at purchase.",
     "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}, "annotations": {"readOnlyHint": True}},
    {"name": "get_positions", "description": "Open positions (hedge mode: BTC:long and BTC:short are separate) and open orders.",
     "inputSchema": {"type": "object", "properties": {}}, "annotations": {"readOnlyHint": True}},
    {"name": "get_markets", "description": "Tradable markets with last price, size decimals, minimum size and fees.",
     "inputSchema": {"type": "object", "properties": {}}, "annotations": {"readOnlyHint": True}},
    {"name": "get_history", "description": "Last 50 fills and account events (newest first).",
     "inputSchema": {"type": "object", "properties": {}}, "annotations": {"readOnlyHint": True}},
    {"name": "place_order", "description": (
        "Place an order on the account. Give size_usd (notional in USD) OR size (in coin). "
        "Types: market, limit (price), stop (trigger_price), stop_limit (both). Optional take_profit / stop_loss prices. "
        "Orders above 50% of the room left under the position cap need confirm_size=true, after asking the user. "
        "Orders above the cap are refused."),
     "inputSchema": {"type": "object", "required": ["market", "side"], "properties": {
         "market": {"type": "string", "description": "e.g. BTC"},
         "side": {"type": "string", "enum": ["buy", "sell"], "description": "buy opens/increases the long, sell opens/increases the short"},
         "type": {"type": "string", "enum": ["market", "limit", "stop", "stop_limit"], "default": "market"},
         "size_usd": {"type": "number", "description": "Notional in USD"},
         "size": {"type": "number", "description": "Size in coin (e.g. 0.01 BTC)"},
         "leverage": {"type": "number", "description": "Optional check: refused if above the account maximum"},
         "price": {"type": "number"}, "trigger_price": {"type": "number"},
         "take_profit": {"type": "number"}, "stop_loss": {"type": "number"},
         "reduce_only": {"type": "boolean"}, "position": S_POS,
         "client_order_id": {"type": "string", "description": "Idempotency key: retrying with the same id never sends a second order"},
         "confirm_size": {"type": "boolean", "description": "Set true only after the user confirmed a large order"}}},
     "annotations": {"destructiveHint": True}},
    {"name": "close_position", "description": "Close a position at market (fully, or partly with size). Use position 'BTC:long', or market 'BTC' / 'all'.",
     "inputSchema": {"type": "object", "properties": {"position": S_POS, "market": {"type": "string"},
                                                      "size": {"type": "number"}, "client_order_id": {"type": "string"}}},
     "annotations": {"destructiveHint": True}},
    {"name": "cancel_order", "description": "Cancel an open order by order_id, or every open order with order_id='all' (optionally for one market).",
     "inputSchema": {"type": "object", "required": ["order_id"], "properties": {"order_id": {"type": ["string", "integer"]},
                                                                               "market": {"type": "string"}}},
     "annotations": {"destructiveHint": True}},
    {"name": "set_tpsl", "description": "Set or clear (null) take profit / stop loss on an open position.",
     "inputSchema": {"type": "object", "required": ["position"], "properties": {"position": S_POS,
                     "take_profit": {"type": ["number", "null"]}, "stop_loss": {"type": ["number", "null"]}}},
     "annotations": {"destructiveHint": True}},
]


def appel_http(methode, chemin, corps=None):
    cle = os.environ.get("OPENPROP_API_KEY", "")
    if not cle:
        return 401, {"error": "OPENPROP_API_KEY is not set. Create a key in the OpenProp dashboard (API & Agents)."}
    if not URL.startswith(("https://", "http://127.0.0.1", "http://localhost")):
        return 400, {"error": "OPENPROP_API_URL is not set (https://.../pf-api, shown on the OpenProp /agents/ page)."}
    r = urllib.request.Request(URL + "/v1/" + chemin.lstrip("/"), method=methode,
                               data=json.dumps(corps).encode() if corps is not None else None,
                               headers={"Authorization": "Bearer " + cle, "Content-Type": "application/json",
                                        "User-Agent": "openprop-mcp/" + VERSION})
    try:
        with urllib.request.urlopen(r, timeout=20) as x:
            return x.status, json.loads(x.read() or b"{}")
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read() or b"{}")
        except ValueError:
            return e.code, {"error": f"HTTP {e.code}"}
    except (urllib.error.URLError, TimeoutError) as e:
        return 503, {"error": f"OpenProp API unreachable: {e}"}


def _rappel(api):
    s, r = api("GET", "rules_status")
    if s != 200:
        return None, ""
    reste = r.get("remaining_loss_before_floor")
    t = f"Remaining loss before the floor: ${reste:,.2f}" if isinstance(reste, (int, float)) else ""
    if isinstance(r.get("remaining_to_target"), (int, float)):
        t += f" · Remaining to target: ${r['remaining_to_target']:,.2f}"
    return r, t


def outil(nom, a, api):
    """Exécute un outil ; renvoie (texte, erreur?)."""
    a = a or {}
    if nom == "get_account":
        s, d = api("GET", "account")
    elif nom == "get_rules_status":
        s, d = api("GET", "rules_status")
    elif nom == "get_positions":
        s, d = api("GET", "positions")
        if s == 200:
            s2, o = api("GET", "orders")
            d["orders"] = o.get("orders", []) if s2 == 200 else o
    elif nom == "get_evaluation":
        s, d = api("GET", "evaluation")
    elif nom == "get_pricing":
        s, d = api("GET", "pricing")
    elif nom == "get_markets":
        s, d = api("GET", "markets")
    elif nom == "get_history":
        s, d = api("GET", "history")
    elif nom == "place_order":
        R, rappel = _rappel(api)
        if R is None:
            return "Could not read the account rules; no order sent.", True
        if R.get("status") not in (None, "active"):
            return f"The account is {R.get('status')}: no order sent.", True
        if not a.get("reduce_only"):
            m = str(a.get("market", "")).upper()
            libre = (R.get("available_notional_usd") or {}).get(m)
            usd = a.get("size_usd")
            if usd is None and a.get("size") is not None:
                px = a.get("price") or a.get("trigger_price")
                if not px:
                    s0, mk = api("GET", "markets")
                    px = next((x.get("price") for x in mk.get("markets", []) if x.get("market") == m), None) if s0 == 200 else None
                usd = float(a["size"]) * float(px) if px else None
            if libre is not None and usd is not None:
                if usd > libre + 1e-6:
                    return (f"Refused before sending: ${usd:,.0f} is above the room left under the {m} position cap "
                            f"(${libre:,.0f} available, cap ${(R.get('max_position_usd') or {}).get(m, 0):,.0f}). {rappel}"), True
                if usd > SEUIL_CONFIRM * libre and not a.get("confirm_size"):
                    return (f"Confirmation needed: ${usd:,.0f} is {usd / libre * 100:.0f}% of the room left on {m} (${libre:,.0f}). "
                            f"{rappel}. Ask the user, then call again with confirm_size=true."), True
        corps = {k: v for k, v in a.items() if k != "confirm_size" and v is not None}
        s, d = api("POST", "orders", corps)
    elif nom == "close_position":
        s, d = api("POST", "positions/close", {k: v for k, v in a.items() if v is not None})
    elif nom == "cancel_order":
        corps = {"order_id": a.get("order_id")}
        if a.get("market"):
            corps["market"] = a["market"]
        s, d = api("POST", "orders/cancel", corps)
    elif nom == "set_tpsl":
        s, d = api("POST", "positions/tpsl", a)
    else:
        return f"Unknown tool: {nom}", True
    if s >= 400:                                  # chantier 4 : erreur lisible en une ou deux phrases
        return lisible(nom, s, d), True
    texte = json.dumps(d, indent=1, default=str)
    if nom in ("place_order", "close_position", "cancel_order", "set_tpsl"):
        _, rappel = _rappel(api)
        if rappel:
            texte += "\n" + rappel
    return texte, s >= 400


def lisible(nom, s, d):
    d = d if isinstance(d, dict) else {}
    if s == 404 and nom in ("get_evaluation", "get_pricing"):
        return f"{nom} is not available on this OpenProp server yet. Use get_account and get_rules_status instead."
    t = f"{nom} failed: {d.get('error') or 'HTTP ' + str(s)}."
    if d.get("hint"):
        t += " " + d["hint"]
    elif s == 401:
        t += " Check OPENPROP_API_KEY (create a key in the OpenProp dashboard, section API & Agents)."
    elif s == 429:
        t += " Wait one second and try again."
    elif s in (503, 504):
        t += " The server is busy or unreachable; read get_positions before retrying an order."
    return t


def traiter(msg, api=appel_http):
    """Un message JSON-RPC MCP -> réponse (ou None pour une notification)."""
    if not isinstance(msg, dict):
        return {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "invalid request"}}
    i, m, p = msg.get("id"), msg.get("method"), msg.get("params") or {}
    if i is None:
        return None
    try:
        if m == "initialize":
            r = {"protocolVersion": p.get("protocolVersion") or PROTO, "capabilities": {"tools": {"listChanged": False}},
                 "serverInfo": {"name": "openprop", "title": "OpenProp", "version": VERSION}, "instructions": INSTRUCTIONS}
        elif m == "ping":
            r = {}
        elif m == "tools/list":
            r = {"tools": OUTILS}
        elif m == "tools/call":
            t, err = outil(p.get("name"), p.get("arguments"), api)
            r = {"content": [{"type": "text", "text": t}], "isError": bool(err)}
        elif m in ("resources/list", "prompts/list"):
            r = {m.split("/")[0]: []}
        else:
            return {"jsonrpc": "2.0", "id": i, "error": {"code": -32601, "message": f"method not found: {m}"}}
    except Exception as e:      # jamais de trace au client
        return {"jsonrpc": "2.0", "id": i, "error": {"code": -32603, "message": f"internal error: {e.__class__.__name__}"}}
    return {"jsonrpc": "2.0", "id": i, "result": r}


def main():
    for ligne in sys.stdin:
        ligne = ligne.strip()
        if not ligne:
            continue
        try:
            msg = json.loads(ligne)
        except ValueError:
            rep = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}}
        else:
            rep = [x for x in (traiter(y) for y in msg) if x] if isinstance(msg, list) else traiter(msg)
        if rep:
            sys.stdout.write(json.dumps(rep) + "\n")
            sys.stdout.flush()


if __name__ == "__main__":
    main()
