"""Pin your MCP server's tool definitions after a person reviews them, then block any change, as lesson 4.1 does.

    python3 -m pip install mcp
    python3 pin_mcp_tools.py pin   -- python3 my_server.py          # a server you start over stdio
    python3 pin_mcp_tools.py check -- python3 my_server.py          # exit 1 if any tool changed
    python3 pin_mcp_tools.py pin   --url http://localhost:8000/mcp  # a server over streamable HTTP

`pin` lists the server's tools and writes the SHA-256 of each definition (name, description, input schema) to
mcp-pins.json, to commit next to your code after someone has read them. `check` lists them again and blocks any
tool whose definition changed, any new tool, and reports any that disappeared.
A pin makes review count: it can't judge a description that was already malicious when someone reviewed it, and it
runs when you run it (at registration, in CI), not between runs. Python 3.10 or later.
"""
# From lesson 4.1 of Cohorte's AI Security Engineering (cohorte.co/security-engineering).
import argparse
import asyncio
import hashlib
import json
import sys
from pathlib import Path

from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client

try:                                                  # the official Python SDK, 1.x or 2.x
    from mcp.client.streamable_http import streamable_http_client as http_client
except ImportError:
    from mcp.client.streamable_http import streamablehttp_client as http_client


def digest(tool) -> str:
    """One hash per definition: everything the model reads about the tool."""
    d = tool.model_dump(by_alias=True, mode="json")
    body = {"name": d["name"], "description": d.get("description") or "", "inputSchema": d.get("inputSchema")}
    return hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":")).encode()).hexdigest()


async def list_tools(command: list, url: str) -> dict:
    async def read(session: ClientSession) -> dict:
        await session.initialize()
        tools, cursor = [], None
        while True:
            if not cursor:
                page = await session.list_tools()
            else:
                try:
                    page = await session.list_tools(params=types.PaginatedRequestParams(cursor=cursor))
                except TypeError:
                    page = await session.list_tools(cursor)
            tools += page.tools
            cursor = getattr(page, "next_cursor", None) or getattr(page, "nextCursor", None)
            if not cursor:
                return {t.name: digest(t) for t in tools}
    if url:
        async with http_client(url) as streams:
            async with ClientSession(streams[0], streams[1]) as session:
                return await read(session)
    params = StdioServerParameters(command=command[0], args=command[1:])
    async with stdio_client(params) as (r, w):
        async with ClientSession(r, w) as session:
            return await read(session)


def main() -> None:
    ap = argparse.ArgumentParser(description="Pin MCP tool definitions by hash, then block changes.",
                                 usage="%(prog)s {pin,check} [--pins FILE] (--url URL | -- COMMAND ...)")
    ap.add_argument("action", choices=["pin", "check"])
    ap.add_argument("--url", help="streamable HTTP endpoint instead of a command")
    ap.add_argument("--pins", default="mcp-pins.json", help="pin file (default: mcp-pins.json)")
    argv = sys.argv[1:]
    command = argv[argv.index("--") + 1:] if "--" in argv else []      # after --: the command that starts your server
    a = ap.parse_args(argv[:argv.index("--")] if "--" in argv else argv)
    if not a.url and not command:
        ap.error("give --url, or -- followed by the command that starts your server")
    try:
        now = asyncio.run(list_tools(command, a.url))
    except Exception as e:                                       # a server that won't start or answer
        sys.exit(f"Could not list tools: {type(e).__name__}: {e}")
    pins = Path(a.pins)
    if a.action == "pin":
        pins.write_text(json.dumps(now, indent=2, sort_keys=True) + "\n")
        print(f"pinned {len(now)} tools in {pins}. Commit it once someone has read every description.")
        return
    if not pins.exists():
        sys.exit(f"No {pins}: run `pin` first, after a review.")
    old = json.loads(pins.read_text())
    blocked = 0
    for name in sorted(set(old) | set(now)):
        if name not in now:
            print(f"GONE     {name}  (pinned {old[name][:12]})")
        elif name not in old:
            print(f"BLOCK new      {name}  {now[name][:12]}, never reviewed")
            blocked += 1
        elif old[name] != now[name]:
            print(f"BLOCK changed  {name}  pinned {old[name][:12]}, now {now[name][:12]}")
            blocked += 1
        else:
            print(f"ok       {name}  {now[name][:12]}")
    print(f"{blocked} blocked" if blocked else "no change since the review")
    sys.exit(1 if blocked else 0)


if __name__ == "__main__":
    main()
