File size: 12,193 Bytes
2acc35c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#!/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:]))