#!/usr/bin/env python3 """mcp-tool-drift.py: notice when an MCP server changes how its tools are called. Takes a snapshot of tools/list (names, properties, required fields, enums), compares it with the last snapshot you saved and prints what changed. With --grep it also searches your agent's memory files for fields that were removed or renamed, so the old way of calling the tool doesn't stay in memory. Python 3.9+, standard library only. # HTTP server (streamable HTTP) python3 mcp-tool-drift.py --url https://example.com/mcp --snapshot cal.json # stdio server python3 mcp-tool-drift.py --snapshot cal.json -- npx -y some-mcp-server # also look for removed fields in memory files python3 mcp-tool-drift.py --url ... --snapshot cal.json --grep CLAUDE.md --grep .agent/memory Exit codes: 0 no change (or first snapshot), 1 something changed, 2 error. Headers for HTTP (auth): --header "Authorization: Bearer $TOKEN". """ import argparse, json, os, queue, re, subprocess, sys, threading, urllib.request PROTOCOL = "2025-06-18" # what we ask for; the server's answer is what we use after initialize TIMEOUT = 30 class HttpClient: def __init__(self, url, headers): self.url, self.headers, self.session, self.protocol = url, headers, None, None def _post(self, msg): h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", **self.headers} if self.protocol: h["MCP-Protocol-Version"] = self.protocol if self.session: h["Mcp-Session-Id"] = self.session req = urllib.request.Request(self.url, json.dumps(msg).encode(), h, method="POST") with urllib.request.urlopen(req, timeout=TIMEOUT) as r: self.session = r.headers.get("Mcp-Session-Id") or self.session body = r.read().decode() ctype = r.headers.get("Content-Type", "") if "id" not in msg or not body.strip(): return None if "text/event-stream" in ctype: for line in body.splitlines(): if line.startswith("data:"): m = json.loads(line[5:].strip()) if m.get("id") == msg["id"]: return m raise RuntimeError("no response in event stream") return json.loads(body) def request(self, i, method, params): return self._post({"jsonrpc": "2.0", "id": i, "method": method, "params": params}) def notify(self, method): self._post({"jsonrpc": "2.0", "method": method}) def close(self): pass class StdioClient: def __init__(self, cmd): self.protocol = None self.p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) self.lines = queue.Queue() threading.Thread(target=self._read, daemon=True).start() def _read(self): for line in self.p.stdout: self.lines.put(line) self.lines.put(None) def _send(self, msg): self.p.stdin.write(json.dumps(msg) + "\n") self.p.stdin.flush() def request(self, i, method, params): self._send({"jsonrpc": "2.0", "id": i, "method": method, "params": params}) while True: try: line = self.lines.get(timeout=TIMEOUT) except queue.Empty: raise RuntimeError(f"no answer to {method} in {TIMEOUT}s") if line is None: raise RuntimeError("server closed stdout") try: m = json.loads(line) except ValueError: continue if isinstance(m, dict) and m.get("id") == i and "method" not in m: return m def notify(self, method): self._send({"jsonrpc": "2.0", "method": method}) def close(self): self.p.terminate() try: self.p.wait(timeout=5) except subprocess.TimeoutExpired: self.p.kill() def fetch_tools(client): r = client.request(1, "initialize", {"protocolVersion": PROTOCOL, "capabilities": {}, "clientInfo": {"name": "mcp-tool-drift", "version": "1"}}) if "error" in r: raise RuntimeError(f"initialize: {r['error']}") server = r["result"].get("serverInfo", {}) client.protocol = r["result"].get("protocolVersion") or PROTOCOL client.notify("notifications/initialized") tools, cursor, i = [], None, 2 while True: r = client.request(i, "tools/list", {"cursor": cursor} if cursor else {}) if "error" in r: raise RuntimeError(f"tools/list: {r['error']}") tools += r["result"].get("tools", []) cursor, i = r["result"].get("nextCursor"), i + 1 if not cursor: return server, tools def type_of(schema): """Type of a field, ignoring the "or null" that Python SDKs add to optional fields.""" t = schema.get("type") if t is None: alts = [s.get("type") for k in ("anyOf", "oneOf") for s in schema.get(k, []) if isinstance(s, dict)] alts = [x for x in alts if x and x != "null"] t = alts[0] if len(alts) == 1 else (sorted(alts) or None) if isinstance(t, list): t = [x for x in t if x != "null"] t = t[0] if len(t) == 1 else sorted(t) return t def resolve(schema, defs, seen): """Follow a local $ref (#/$defs/X or #/definitions/X). Returns (schema, seen); None on a loop.""" ref = schema.get("$ref") if isinstance(schema, dict) else None if not isinstance(ref, str) or not ref.startswith(("#/$defs/", "#/definitions/")): return schema, seen if ref in seen: return None, seen return defs.get(ref.split("/")[-1], {}), seen | {ref} def walk(schema, path, out, defs, seen=frozenset()): """Flatten a JSON Schema into {path: description} with type, enum, required.""" schema, seen = resolve(schema, defs, seen) if not isinstance(schema, dict): return for key in ("anyOf", "oneOf", "allOf"): for sub in schema.get(key) or []: if isinstance(sub, dict) and sub.get("type") != "null": walk(sub, path, out, defs, seen) req = set(schema.get("required") or []) for name, sub in (schema.get("properties") or {}).items(): p = f"{path}.{name}" if path else name sub_r, sub_seen = resolve(sub, defs, seen) if not isinstance(sub_r, dict): # recursive type: record the field, stop there out[p] = {"type": "object", "required": name in req} continue out[p] = {"type": type_of(sub_r), "required": name in req} if "enum" in sub_r: out[p]["enum"] = sub_r["enum"] walk(sub_r, p, out, defs, sub_seen) if isinstance(schema.get("items"), dict): walk(schema["items"], path + "[]", out, defs, seen) def normalize(server, tools): snap = {"server": {"name": server.get("name"), "version": server.get("version")}, "tools": {}} for t in tools: s = t.get("inputSchema") or {} fields = {} walk(s, "", fields, {**(s.get("definitions") or {}), **(s.get("$defs") or {})}) snap["tools"][t["name"]] = {"fields": fields, "closed": s.get("additionalProperties") is False} return snap def diff(old, new): changes, removed_fields = [], set() ot, nt = old["tools"], new["tools"] for name in sorted(set(ot) - set(nt)): changes.append(f"- tool removed: {name}") removed_fields.add(name) for name in sorted(set(nt) - set(ot)): changes.append(f"+ tool added: {name}") for name in sorted(set(ot) & set(nt)): of, nf = ot[name]["fields"], nt[name]["fields"] for f in sorted(set(of) - set(nf)): changes.append(f"- {name}: field removed: {f}") removed_fields.add(f.split(".")[-1].rstrip("[]")) for f in sorted(set(nf) - set(of)): changes.append(f"+ {name}: field added: {f}" + (" (required)" if nf[f]["required"] else "")) for f in sorted(set(of) & set(nf)): a, b = of[f], nf[f] if a.get("type") != b.get("type"): changes.append(f"~ {name}.{f}: type {a.get('type')} -> {b.get('type')}") if a.get("enum") != b.get("enum"): changes.append(f"~ {name}.{f}: values {a.get('enum')} -> {b.get('enum')}") # removed string values only: a removed number (4) or a one-letter value would match everywhere removed_fields.update(v for v in (a.get("enum") or []) if v not in (b.get("enum") or []) and isinstance(v, str) and len(v) > 1 and not v.isdigit()) if a["required"] != b["required"]: changes.append(f"~ {name}.{f}: required {a['required']} -> {b['required']}") if old["server"] != new["server"]: changes.append(f"~ server: {old['server']} -> {new['server']}") return changes, removed_fields def grep(paths, words): hits = [] pattern = re.compile(r"\b(" + "|".join(re.escape(w) for w in sorted(words)) + r")\b") files = [] for p in paths: if os.path.isdir(p): for root, _, names in os.walk(p): files += [os.path.join(root, n) for n in names] elif os.path.exists(p): files.append(p) for f in files: try: with open(f, encoding="utf-8", errors="ignore") as fh: for n, line in enumerate(fh, 1): if pattern.search(line): hits.append(f"{f}:{n}: {line.strip()[:160]}") except OSError: pass return hits def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--url") ap.add_argument("--header", action="append", default=[]) ap.add_argument("--snapshot", required=True, help="JSON file with the last snapshot (created if missing)") ap.add_argument("--grep", action="append", default=[], help="memory file or folder to search for removed fields") ap.add_argument("--no-save", action="store_true", help="compare only, keep the old snapshot") ap.add_argument("cmd", nargs="*", help="stdio server command (after --)") a = ap.parse_args() if bool(a.url) == bool(a.cmd): ap.error("give either --url or a stdio command after --") headers = {} for h in a.header: k, sep, v = h.partition(":") if not sep or not k.strip(): ap.error(f'--header needs "Name: value", got {h!r}') headers[k.strip()] = v.strip() client = None try: client = HttpClient(a.url, headers) if a.url else StdioClient(a.cmd) server, tools = fetch_tools(client) except Exception as e: print(f"error: {e}", file=sys.stderr) return 2 finally: if client: client.close() new = normalize(server, tools) if not os.path.exists(a.snapshot): save(a.snapshot, new) print(f"first snapshot: {len(new['tools'])} tools saved to {a.snapshot}") return 0 with open(a.snapshot) as fh: old = json.load(fh) changes, removed = diff(old, new) if not changes: print(f"no change in {len(new['tools'])} tools") return 0 print("\n".join(changes)) if removed and a.grep: hits = grep(a.grep, removed) print(f"\nmemory still mentions removed names {sorted(removed)}: {len(hits)} line(s)") print("\n".join(hits)) if not a.no_save: save(a.snapshot, new) return 1 def save(path, snap): os.makedirs(os.path.dirname(path) or ".", exist_ok=True) with open(path, "w") as fh: json.dump(snap, fh, indent=2, sort_keys=True) fh.write("\n") if __name__ == "__main__": try: sys.exit(main()) except (OSError, ValueError, KeyError) as e: # unreadable snapshot, unwritable folder: not a "change" print(f"error: {e}", file=sys.stderr) sys.exit(2)