#!/usr/bin/env python3
"""Toolmark pre-install hook for Claude Code (https://toolmark.dev).

At the start of a session it reads this project's .mcp.json, asks Toolmark's public record
about each npm MCP server at its exact version, and prints what the record shows. It only reads:
it never blocks, installs or runs anything, and it sends nothing but the package name.

Read this file, save it as ~/.claude/toolmark_hook.py, then add to .claude/settings.json:
  {"hooks": {"SessionStart": [{"hooks": [{"type": "command",
    "command": "python3 ~/.claude/toolmark_hook.py"}]}]}}
Python 3.9 or newer, standard library only.
"""

import json
import re
import sys
import urllib.request
from pathlib import Path

BASE = "https://toolmark.dev/registry/npm/"
NAME = re.compile(r"(?:@[a-z0-9~][a-z0-9._~-]*/)?[a-z0-9~][a-z0-9._~-]*")
VERSION = re.compile(r"[0-9A-Za-z.+-]{1,64}")  # anything else is never printed
DAY = re.compile(r"\d{4}-\d{2}-\d{2}")
KINDS = (
    ("programs", "programs started or tried"),
    ("connections", "connections tried"),
    ("dns_names", "names looked up"),
    ("sensitive_files", "key files it tried to open"),
    ("written_files", "files opened for writing outside the usual places"),
)


def record_url(name):
    return BASE + name + ".json"


def fetch(url):
    request = urllib.request.Request(url, headers={"User-Agent": "toolmark-hook"})  # noqa: S310
    with urllib.request.urlopen(request, timeout=5) as answer:  # noqa: S310 - fixed https host (BASE)
        return json.loads(answer.read(1_000_000))


def servers(root):
    """(name, version) of each npm package started with npx in the project's .mcp.json."""
    try:
        config = json.loads((Path(root) / ".mcp.json").read_text())
    except (OSError, ValueError):
        return []
    entries = config.get("mcpServers") if isinstance(config, dict) else None
    found = []
    for server in entries.values() if isinstance(entries, dict) else []:
        if not isinstance(server, dict) or server.get("command") != "npx":
            continue
        raw = server.get("args")
        args = [a for a in raw if isinstance(a, str)] if isinstance(raw, list) else []
        package = next((a for a in args if not a.startswith("-")), "")
        at = package.rfind("@")
        name, version = (package[:at], package[at + 1 :]) if at > 0 else (package, "")
        if NAME.fullmatch(name) and (not version or VERSION.fullmatch(version)):
            found.append((name, version))
    return found


def describe(name, version, data):
    """One line of facts; every value from the server is checked before it is printed."""
    label = f"{name}@{version}" if version else name
    runs = data.get("versions") if isinstance(data, dict) else None
    recorded = [
        (v.get("version"), v.get("run_day"))
        for v in (runs if isinstance(runs, list) else [])
        if isinstance(v, dict)
        and isinstance(v.get("version"), str)
        and VERSION.fullmatch(v["version"])
    ]
    names = [v for v, _ in recorded]
    if not recorded:
        return f"toolmark: {label}: not in the record"
    if version and version != names[0]:
        if version in names:
            return (
                f"toolmark: {label}: recorded, but not the latest (latest {names[0]}). {BASE}{name}"
            )
        return f"toolmark: {label}: not in the record (recorded: {', '.join(names[:3])})"
    day = (
        recorded[0][1] if isinstance(recorded[0][1], str) and DAY.fullmatch(recorded[0][1]) else "?"
    )
    behaviour = data.get("behaviour")
    if not isinstance(behaviour, dict):  # a run that recorded nothing is never shown as zeros
        note = "no behaviour record (not tested, or not readable)"
        return f"toolmark: {label}: run {day}, {note}. {BASE}{name}"
    seen = ", ".join(
        f"{text} {len(behaviour[key]) if isinstance(behaviour.get(key), list) else 0}"
        for key, text in KINDS
    )
    return f"toolmark: {label}: recorded {day}: {seen}. {BASE}{name}"


def report(root, get=fetch):
    lines = []
    for name, version in servers(root):
        try:
            data = get(record_url(name))
            line = describe(name, version, data)
        except Exception:  # an unreachable or odd record must never stop the session
            line = f"toolmark: {name}: not in the record"
        lines.append(line)
    return lines


if __name__ == "__main__":
    for line in report(Path.cwd()):
        print(line)
    sys.exit(0)
