"""MCP tool audit for social media servers (APIWings guide, MIT licence).

Reviews the tool definitions a social media MCP server declares before you connect it to Claude.
It never calls a tool and is not a security certification: see "disclaimer" in mcp-audit-rules.json.
Input: a tools/list result ({"tools": [...]}), a JSON-RPC response ({"result": {"tools": [...]}}),
a plain list of tools, or {"servers": [{"name": ..., "tools": [...]}]}.
Usage: python mcp_tool_audit.py tools.json [--json]
Python 3.9 or later, no dependencies. Reads mcp-audit-rules.json from the same folder.
"""

import json
import re
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
RULES = json.loads((HERE / "mcp-audit-rules.json").read_text(encoding="utf-8"))

TOOL_CHECKS = [
    "write_tool_marked_read_only",
    "secret_in_input",
    "publish_without_idempotency",
    "schedule_without_time",
    "publish_without_target",
    "remove_not_marked_destructive",
    "missing_description",
]


def words(name):
    """'createScheduledPost' -> ['create', 'scheduled', 'post']"""
    spaced = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", "" if name is None else str(name))
    spaced = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1 \2", spaced)
    return [w for w in re.split(r"[^a-z0-9]+", spaced.lower()) if w]


def kind_of(name, rules=RULES):
    w = words(name)
    v = rules["verbs"]

    def has(lst):
        return any(x in lst for x in w)

    if w and w[0] in v["read"]:
        return "read"
    if has(v["remove"]):
        return "remove"
    if has(v["draft"]):
        return "draft"
    if has(v["schedule"]):
        return "schedule"
    if has(v["publish"]):
        return "publish"
    return "other"


def field_names(schema, depth=0, out=None):
    """Every property name in the input schema, lowercased, down to 4 levels."""
    if out is None:
        out = set()
    if not isinstance(schema, dict) or depth > 4:
        return out
    props = schema.get("properties")
    if isinstance(props, dict):
        for key, sub in props.items():
            out.add(key.lower())
            field_names(sub, depth + 1, out)
    if schema.get("items"):
        field_names(schema["items"], depth + 1, out)
    return out


def _audit_tool(tool, rules):
    tool = tool if isinstance(tool, dict) else {}
    name = tool["name"] if isinstance(tool.get("name"), str) else ""
    kind = kind_of(name, rules)
    ann = tool.get("annotations") if isinstance(tool.get("annotations"), dict) else {}
    fields = field_names(tool.get("inputSchema"))

    def any_field(lst):
        return any(f in fields for f in lst)

    writes = kind in ("publish", "schedule")
    desc = tool["description"].strip(" \t\n\r") if isinstance(tool.get("description"), str) else ""
    hit = {
        "write_tool_marked_read_only": (writes or kind == "remove") and ann.get("readOnlyHint") is True,
        "secret_in_input": any_field(rules["fields"]["secret"]),
        "publish_without_idempotency": writes and not any_field(rules["fields"]["idempotency"]),
        "schedule_without_time": kind == "schedule" and not any_field(rules["fields"]["time"]),
        "publish_without_target": writes and not any_field(rules["fields"]["target"]),
        "remove_not_marked_destructive": kind == "remove" and ann.get("destructiveHint") is False,
        "missing_description": len(desc) < rules["min_description_length"],
    }
    return {"name": name, "kind": kind, "findings": [c for c in TOOL_CHECKS if hit[c]]}


def tools_from(data):
    if isinstance(data, list):
        return data
    if isinstance(data, dict) and isinstance(data.get("tools"), list):
        return data["tools"]
    if isinstance(data, dict) and isinstance(data.get("result"), dict) and isinstance(data["result"].get("tools"), list):
        return data["result"]["tools"]
    raise ValueError("No tools found: expected a list, {tools: [...]} or {result: {tools: [...]}}")


def audit(data, rules=RULES):
    raw = tools_from(data)
    tools = [_audit_tool(t, rules) for t in raw]
    kinds = {t["kind"] for t in tools}
    server_findings = []
    if "publish" in kinds or "schedule" in kinds:
        status_tool = any(
            kind_of(t.get("name") if isinstance(t, dict) else None, rules) == "read"
            and any(w in rules["status_words"] for w in words(t.get("name") if isinstance(t, dict) else None))
            for t in raw
        )
        if not status_tool:
            server_findings.append("no_status_tool")
        if "draft" not in kinds:
            server_findings.append("no_draft_or_preview")
        if "remove" not in kinds:
            server_findings.append("no_remove_tool")
    counts = {"high": 0, "medium": 0, "low": 0}
    for code in [c for t in tools for c in t["findings"]] + server_findings:
        counts[rules["findings"][code]["severity"]] += 1
    verdict = "fix_first" if counts["high"] else ("review" if counts["medium"] else "no_issues_found")
    return {"tool_count": len(tools), "tools": tools, "server_findings": server_findings, "counts": counts, "verdict": verdict}


def _report(name, r):
    c = r["counts"]
    lines = [f"{name + ': ' if name else ''}{r['tool_count']} tools, verdict {r['verdict'].upper()} ({c['high']} high, {c['medium']} medium, {c['low']} low)"]
    for t in r["tools"]:
        lines.append(f"  {t['name'] or '(no name)'} [{t['kind']}]{'' if t['findings'] else ' ok'}")
        for code in t["findings"]:
            f = RULES["findings"][code]
            lines.append(f"    - {f['severity']}: {code}. {f['message']}")
    for code in r["server_findings"]:
        f = RULES["findings"][code]
        lines.append(f"  server - {f['severity']}: {code}. {f['message']}")
    lines.append(f"  {RULES['verdicts'][r['verdict']]}")
    return "\n".join(lines)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python mcp_tool_audit.py tools.json [--json]", file=sys.stderr)
        sys.exit(2)
    data = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
    multi = isinstance(data, dict) and isinstance(data.get("servers"), list)
    servers = data["servers"] if multi else [{"name": "", "tools": tools_from(data)}]
    results = [{"name": s.get("name", ""), **audit(s["tools"])} for s in servers]
    if "--json" in sys.argv:
        print(json.dumps(results if multi else results[0], indent=2))
    else:
        print("\n\n".join(_report(r["name"], r) for r in results) + "\n\nNote: " + RULES["disclaimer"])
    sys.exit(1 if any(r["verdict"] == "fix_first" for r in results) else 0)
