#!/usr/bin/env python3
"""Zero-dependency Python 3 stdlib MCP Server for astral-sh/ruff.

Compiled by Clone-AnySaaS x MCPify-AnyRepo (https://clonesaas.fastmesh.dev)
Modes:
  python3 server.py --stdio          # Run JSON-RPC 2.0 MCP server over stdin/stdout
  python3 server.py --http --port 8765  # Run Streamable HTTP MCP server
  python3 server.py --self-check     # Verify metadata and compiled tool schemas
"""

from __future__ import annotations

import argparse
import json
import os
import shlex
import subprocess
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Dict, List

SERVER_SPEC: Dict[str, Any] = json.loads(r"""{
  "description": "An extremely fast Python linter and code formatter written in Rust.",
  "install_commands": [
    "pip install ruff",
    "uv tool install ruff"
  ],
  "server_name": "ruff-mcp",
  "source_repo": "https://github.com/astral-sh/ruff",
  "tools": [
    {
      "description": "Return architecture, install commands, and tool catalog for astral-sh/ruff.",
      "execution": {
        "handler": "repo_overview",
        "type": "builtin"
      },
      "inputSchema": {
        "properties": {},
        "required": [],
        "type": "object"
      },
      "name": "repo_overview",
      "source_kind": "builtin"
    },
    {
      "description": "Run lint rules across Python source files with optional auto-fix",
      "execution": {
        "binary": "ruff",
        "subcommand": "check",
        "type": "cli"
      },
      "inputSchema": {
        "properties": {
          "extra_args": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "target": {
            "description": "Target path, file, or URL",
            "type": "string"
          }
        },
        "required": [],
        "type": "object"
      },
      "name": "cli_check",
      "source_kind": "cli_subcommand"
    },
    {
      "description": "Format Python code deterministically to Ruff style rules",
      "execution": {
        "binary": "ruff",
        "subcommand": "format",
        "type": "cli"
      },
      "inputSchema": {
        "properties": {
          "extra_args": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "target": {
            "description": "Target path, file, or URL",
            "type": "string"
          }
        },
        "required": [],
        "type": "object"
      },
      "name": "cli_format",
      "source_kind": "cli_subcommand"
    },
    {
      "description": "Explain a specific Ruff lint rule code and rationale",
      "execution": {
        "binary": "ruff",
        "subcommand": "rule",
        "type": "cli"
      },
      "inputSchema": {
        "properties": {
          "extra_args": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "target": {
            "description": "Target path, file, or URL",
            "type": "string"
          }
        },
        "required": [],
        "type": "object"
      },
      "name": "cli_rule",
      "source_kind": "cli_subcommand"
    },
    {
      "description": "Inspect module imports and symbol graph across a repository",
      "execution": {
        "binary": "ruff",
        "subcommand": "analyze",
        "type": "cli"
      },
      "inputSchema": {
        "properties": {
          "extra_args": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "target": {
            "description": "Target path, file, or URL",
            "type": "string"
          }
        },
        "required": [],
        "type": "object"
      },
      "name": "cli_analyze",
      "source_kind": "cli_subcommand"
    }
  ],
  "version": "1.0.0"
}""")
TOOLS_BY_NAME: Dict[str, Dict[str, Any]] = {t["name"]: t for t in SERVER_SPEC["tools"]}


def _tool_list_payload() -> List[Dict[str, Any]]:
    return [
        {
            "name": t["name"],
            "description": t["description"],
            "inputSchema": t["inputSchema"],
        }
        for t in SERVER_SPEC["tools"]
    ]


def execute_tool(name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
    spec = TOOLS_BY_NAME.get(name)
    if spec is None:
        return {"ok": False, "error": f"Unknown tool: {name}"}
    exec_cfg = spec.get("execution") or {}
    exec_type = exec_cfg.get("type", "builtin")
    if exec_type == "builtin":
        return {
            "ok": True,
            "server": SERVER_SPEC["server_name"],
            "source_repo": SERVER_SPEC["source_repo"],
            "description": SERVER_SPEC["description"],
            "install_commands": SERVER_SPEC["install_commands"],
            "tool_names": [t["name"] for t in SERVER_SPEC["tools"]],
        }
    if exec_type == "cli":
        binary = str(exec_cfg.get("binary") or SERVER_SPEC["server_name"])
        subcmd = str(exec_cfg.get("subcommand") or "").strip()
        argv: List[str] = [binary]
        if subcmd:
            argv.extend(shlex.split(subcmd))
        for k, v in (arguments or {}).items():
            if k in ("args", "extra_args") and isinstance(v, list):
                argv.extend(str(item) for item in v)
            elif isinstance(v, bool) and v:
                argv.append(f"--{k.replace('_', '-')}")
            elif v is not None:
                argv.extend([f"--{k.replace('_', '-')}", str(v)])
        allow_exec = os.environ.get("MCP_ALLOW_EXEC", "0").strip() in ("1", "true", "yes")
        if not allow_exec:
            return {
                "ok": True,
                "mode": "dry_run_plan",
                "command": argv,
                "shell_preview": " ".join(shlex.quote(x) for x in argv),
                "hint": "Set MCP_ALLOW_EXEC=1 to execute local binaries.",
            }
        proc = subprocess.run(argv, capture_output=True, text=True, timeout=15)
        return {
            "ok": proc.returncode == 0,
            "mode": "executed",
            "command": argv,
            "returncode": proc.returncode,
            "stdout": proc.stdout[:16000],
            "stderr": proc.stderr[:4000],
        }
    return {
        "ok": True,
        "mode": "structured_plan",
        "tool": name,
        "execution": exec_cfg,
        "arguments": arguments,
    }


def handle_jsonrpc(req: Any) -> Dict[str, Any]:
    if not isinstance(req, dict) or req.get("jsonrpc") != "2.0":
        return {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid Request"}}
    req_id = req.get("id")
    method = req.get("method", "")
    params = req.get("params") or {}
    if method == "initialize":
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {
                "protocolVersion": "2024-11-05",
                "capabilities": {"tools": {"listChanged": False}},
                "serverInfo": {"name": SERVER_SPEC["server_name"], "version": SERVER_SPEC["version"]},
            },
        }
    if method == "notifications/initialized":
        return {"jsonrpc": "2.0", "id": req_id, "result": {"acknowledged": True}}
    if method == "ping":
        return {"jsonrpc": "2.0", "id": req_id, "result": {"ok": True}}
    if method == "tools/list":
        return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": _tool_list_payload()}}
    if method == "tools/call":
        tname = str(params.get("name") or "")
        targs = params.get("arguments") or {}
        res = execute_tool(tname, targs)
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {
                "content": [{"type": "text", "text": json.dumps(res, indent=2)}],
                "structuredContent": res,
                "isError": not bool(res.get("ok", True)),
            },
        }
    return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}}


class _McpHandler(BaseHTTPRequestHandler):
    def log_message(self, format: str, *args: Any) -> None:
        return

    def do_GET(self) -> None:
        if self.path == "/health":
            raw = json.dumps({"ok": True, "server": SERVER_SPEC["server_name"], "tools": len(SERVER_SPEC["tools"])}).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(raw)))
            self.end_headers()
            self.wfile.write(raw)
            return
        self.send_error(404)

    def do_POST(self) -> None:
        length = int(self.headers.get("Content-Length", "0") or "0")
        body = json.loads(self.rfile.read(length).decode("utf-8")) if length > 0 else {}
        resp = handle_jsonrpc(body)
        raw = json.dumps(resp).encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(raw)))
        self.end_headers()
        self.wfile.write(raw)


def main() -> int:
    parser = argparse.ArgumentParser(description=f"{SERVER_SPEC['server_name']} MCP server")
    parser.add_argument("--stdio", action="store_true", help="Serve JSON-RPC 2.0 on stdin/stdout")
    parser.add_argument("--http", action="store_true", help="Serve HTTP MCP endpoint")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=8765)
    parser.add_argument("--self-check", action="store_true", help="Print server diagnostics")
    args = parser.parse_args()
    if args.self_check:
        overview = execute_tool("repo_overview", {})
        print(json.dumps({"ok": True, "server": SERVER_SPEC["server_name"], "tool_count": len(SERVER_SPEC["tools"]), "overview": overview}, indent=2))
        return 0
    if args.stdio:
        for line in sys.stdin:
            stripped = line.strip()
            if not stripped:
                continue
            try:
                req = json.loads(stripped)
                resp = handle_jsonrpc(req)
            except Exception as exc:
                resp = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}}
            sys.stdout.write(json.dumps(resp) + "\n")
            sys.stdout.flush()
        return 0
    srv = ThreadingHTTPServer((args.host, args.port), _McpHandler)
    srv.serve_forever()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
