"""HostMT5 MCP for AI apps that run MCP servers locally (Claude Desktop, Cursor, Windsurf, Cline, LM Studio...).

It forwards every message to the HostMT5 remote MCP server (https://hostmt5.com/mcp), so the tools are always the current
full set: accounts, live data and history, orders, Expert Advisors (write / upload / compile / attach / inputs / logs),
stop and resume trading, copy trading, TradingView webhooks, alerts, statistics. Python 3.8+, no packages to install.

Apps that take a URL can skip this file: use https://hostmt5.com/mcp with header  Authorization: Bearer mc_...

Config (Claude Desktop: Settings > Developer > Edit config):
  "mcpServers": {"hostmt5": {"command": "python", "args": ["C:/path/to/mcp_server.py"],
                              "env": {"HOSTMT5_KEY": "mc_..."}}}
The key comes from Dashboard > AI & API. A read-only key shows only the read tools."""
import json, os, sys, urllib.error, urllib.request

URL = os.environ.get('HOSTMT5_URL', 'https://hostmt5.com').rstrip('/') + '/mcp'
KEY = os.environ.get('HOSTMT5_KEY', '')


def forward(raw):
    req = urllib.request.Request(URL, data=raw.encode(), method='POST', headers={
        'Authorization': f'Bearer {KEY}', 'Content-Type': 'application/json', 'Accept': 'application/json, text/event-stream',
        'User-Agent': 'hostmt5-mcp-bridge/1.0'})
    try:
        with urllib.request.urlopen(req, timeout=600) as r: return r.status, r.read().decode()
    except urllib.error.HTTPError as e: return e.code, e.read().decode()


def main():
    for line in sys.stdin:
        line = line.strip()
        if not line: continue
        try: msg = json.loads(line)
        except ValueError: continue
        try:
            if not KEY: raise RuntimeError('Set HOSTMT5_KEY (Dashboard > AI & API > New API key)')
            status, body = forward(line)
            if status == 202 or not body.strip(): continue        # a notification: nothing to answer
            out = body
        except Exception as e:
            if not isinstance(msg, dict) or msg.get('id') is None: continue
            out = json.dumps(dict(jsonrpc='2.0', id=msg.get('id'), error=dict(code=-32000, message=f'HostMT5: {e}')))
        sys.stdout.write(out.strip() + '\n'); sys.stdout.flush()


if __name__ == '__main__':
    main()
