spiderpilot89's picture
protocol company
Release v0.15.3 free evaluation sample
fd8b1ae
Raw History Blame Contribute Delete
12.2 kB
#!/usr/bin/env python3
"""A stdio MCP proxy that records every tool call and changes no byte of any message.
python3 mcp_log_proxy.py --log LOG [--forbid-under DIR ...] [--trace FILE] -- ENGINE [ENGINE ARGS ...]
It starts ENGINE (an MCP server over stdio, one JSON-RPC message a line, such as the Zero-Trust
Physics mcp_stdio), hands every line the client writes to ENGINE's stdin, and every line ENGINE
writes back to the client's stdout, byte for byte. It reads a copy of each message and, for every
tools/call, appends one JSON line to LOG when the answer comes back:
{"seq", "jsonrpc_id", "tool", "arguments", "ts_request", "ts_response", "duration_s",
"response_sha384", "text_sha384", "is_error", "chain"}
response_sha384 is the SHA-384 of the answer line exactly as forwarded (without its newline);
text_sha384 is the SHA-384 of the answer's text content. chain is the SHA-384 of the previous
line's chain followed by this line's JSON without its chain (sorted keys, no spaces): an edit to
any line, or a line taken out, breaks every chain after it. A call still unanswered when the
client closes is written with "unanswered": true.
LOG must lie outside the solver's working directory: the proxy refuses to start when LOG is
under its own working directory (where an agent's CLI starts it) or under any --forbid-under.
Beside LOG it keeps LOG.status.json: the engine command, the handshake (initialize, or
server/discover under MCP 2026-07-28), the call count, the engine's exit code. --trace FILE also keeps every line both ways, for diagnosing a client.
Standard library only. Licence: Apache-2.0.
"""
import hashlib
import json
import os
import signal
import subprocess
import sys
import threading
import time
# initialize (MCP 2025-06-18 and before) or server/discover (MCP 2026-07-28, which newer clients send first)
HANDSHAKES = ("initialize", "server/discover")
def now():
return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + ".%03dZ" % (int(time.time() * 1000) % 1000)
def sha384(data):
return hashlib.sha384(data).hexdigest()
def chain_of(previous, entry):
payload = json.dumps(entry, sort_keys=True, separators=(",", ":"))
return sha384(((previous or "") + payload).encode("utf-8"))
def under(path, folder):
path, folder = os.path.realpath(path), os.path.realpath(folder)
return path == folder or path.startswith(folder.rstrip(os.sep) + os.sep)
class Recorder:
def __init__(self, log_path, engine):
self.log_path = log_path
self.lock = threading.Lock()
self.pending = {}
self.seq = 0
self.chain = None
self.status = {"engine": engine, "proxy_pid": os.getpid(), "started": now(), "handshake": None,
"tools_list": False, "calls": 0, "unanswered": 0, "engine_exit": None, "ended": None,
"problems": []}
open(log_path, "a").close()
self.write_status()
def write_status(self):
tmp = self.log_path + ".status.json.tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(self.status, f, indent=1)
os.replace(tmp, self.log_path + ".status.json")
def append(self, entry):
"""One log line, chained to the one before. Called with the lock held."""
self.seq += 1
entry = dict(entry, seq=self.seq)
entry["chain"] = chain_of(self.chain, entry)
self.chain = entry["chain"]
with open(self.log_path, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, sort_keys=True) + "\n")
f.flush()
os.fsync(f.fileno())
self.status["calls"] += 1
@staticmethod
def messages(line):
try:
found = json.loads(line)
except ValueError:
return []
if isinstance(found, list):
return [m for m in found if isinstance(m, dict)]
return [found] if isinstance(found, dict) else []
def from_client(self, line):
for message in self.messages(line):
if "id" in message and message.get("method"):
key = json.dumps(message["id"])
with self.lock:
self.pending[key] = {"method": message["method"], "params": message.get("params"),
"ts": now(), "t0": time.time(), "id": message["id"]}
def from_engine(self, line):
raw = line.rstrip(b"\r\n")
for message in self.messages(line):
if "id" not in message or message.get("method"):
continue
key = json.dumps(message["id"])
with self.lock:
asked = self.pending.pop(key, None)
if asked is None:
continue
if asked["method"] in HANDSHAKES:
result = message.get("result") if isinstance(message.get("result"), dict) else {}
if not (self.status["handshake"] or {}).get("ok"):
srv = result.get("serverInfo")
if isinstance(srv, dict) and str(srv.get("title") or "").startswith("Zero-Trust Physics"):
desc = str(srv.get("description") or "")
if ": " in desc:
desc = "Deterministic physics of real objects: " + desc.split(": ", 1)[1]
srv = dict(srv, title="Zero-Trust Physics Verifier", description=desc)
self.status["handshake"] = {"method": asked["method"], "ok": "result" in message,
"server": srv}
self.write_status()
elif asked["method"] == "tools/list":
if not self.status["tools_list"]:
self.status["tools_list"] = "result" in message
self.write_status()
elif asked["method"] == "tools/call":
params = asked["params"] if isinstance(asked["params"], dict) else {}
result = message.get("result") if isinstance(message.get("result"), dict) else {}
text = "".join(c.get("text", "") for c in result.get("content", []) or [] if isinstance(c, dict))
self.append({"jsonrpc_id": asked["id"], "tool": params.get("name"),
"arguments": params.get("arguments") if params.get("arguments") is not None else {},
"ts_request": asked["ts"], "ts_response": now(),
"duration_s": round(time.time() - asked["t0"], 6),
"response_sha384": sha384(raw), "text_sha384": sha384(text.encode("utf-8")),
"is_error": bool(result.get("isError")) or "error" in message})
def close(self, engine_exit):
with self.lock:
for asked in self.pending.values():
if asked["method"] != "tools/call":
continue
params = asked["params"] if isinstance(asked["params"], dict) else {}
self.append({"jsonrpc_id": asked["id"], "tool": params.get("name"),
"arguments": params.get("arguments") if params.get("arguments") is not None else {},
"ts_request": asked["ts"], "ts_response": None, "duration_s": None,
"response_sha384": None, "text_sha384": None, "is_error": None, "unanswered": True})
self.status["unanswered"] += 1
self.pending.clear()
self.status["engine_exit"] = engine_exit
self.status["ended"] = now()
self.write_status()
def main(argv):
log, forbid, engine, trace = None, [], None, None
i = 0
while i < len(argv):
if argv[i] == "--":
engine = argv[i + 1:]
break
if argv[i] == "--log" and i + 1 < len(argv):
log = argv[i + 1]
i += 2
continue
if argv[i] == "--trace" and i + 1 < len(argv):
trace = open(argv[i + 1], "ab")
i += 2
continue
if argv[i] == "--forbid-under" and i + 1 < len(argv):
forbid.append(argv[i + 1])
i += 2
continue
sys.exit("usage: mcp_log_proxy.py --log LOG [--forbid-under DIR ...] -- ENGINE [ARGS ...]")
if not log or not engine:
sys.exit("usage: mcp_log_proxy.py --log LOG [--forbid-under DIR ...] -- ENGINE [ARGS ...]")
log = os.path.abspath(log)
for folder in [os.getcwd()] + forbid:
if under(log, folder):
sys.exit("mcp_log_proxy: the log %s lies inside %s, where the solver works; put it outside" % (log, folder))
os.makedirs(os.path.dirname(log), exist_ok=True)
recorder = Recorder(log, engine)
try:
proc = subprocess.Popen(engine, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sys.stderr.fileno(), bufsize=0)
except OSError as problem:
recorder.status["problems"].append("the engine did not start: %s" % problem)
recorder.close(None)
sys.exit("mcp_log_proxy: the engine did not start: %s" % problem)
out = sys.stdout.buffer
def engine_to_client():
try:
for line in iter(proc.stdout.readline, b""):
if trace:
trace.write(b"< " + line)
trace.flush()
try:
recorder.from_engine(line)
except Exception as problem: # the log must never stop an answer
recorder.status["problems"].append("log: %s" % problem)
out.write(line)
out.flush()
except (BrokenPipeError, OSError) as problem:
recorder.status["problems"].append("client output closed: %s" % problem)
finished = threading.Lock()
def finish():
"""Once: close the engine, log what is unanswered, close the client's output, and leave."""
if not finished.acquire(blocking=False):
return
try:
proc.stdin.close()
except OSError:
pass
try:
code = proc.wait(timeout=30)
except subprocess.TimeoutExpired:
proc.kill()
code = proc.wait()
recorder.close(code)
try:
out.flush()
except OSError:
pass
os._exit(0)
reader_done = threading.Event()
client_closed = threading.Event()
def engine_to_client_then_finish():
engine_to_client()
reader_done.set()
if proc.poll() is None:
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
if proc.poll() is not None and not client_closed.is_set():
# the engine has gone: the client must see its output close rather than wait for an answer
recorder.status["problems"].append("the engine closed its output (exit %s)" % proc.returncode)
finish()
reader = threading.Thread(target=engine_to_client_then_finish, daemon=True)
reader.start()
def stop(signum, frame):
raise KeyboardInterrupt
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGHUP, stop)
source = sys.stdin.buffer
try:
for line in iter(source.readline, b""):
if trace:
trace.write(b"> " + line)
trace.flush()
try:
recorder.from_client(line)
except Exception as problem:
recorder.status["problems"].append("log: %s" % problem)
try:
proc.stdin.write(line)
proc.stdin.flush()
except (BrokenPipeError, OSError) as problem:
recorder.status["problems"].append("engine input closed: %s" % problem)
break
except KeyboardInterrupt:
pass
client_closed.set()
try:
proc.stdin.close()
except OSError:
pass
reader.join(timeout=30)
finish()
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))