File size: 5,046 Bytes
fd8b1ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The open address as a stdio MCP server: every JSON-RPC line read on stdin is posted, unchanged, to the verifier's
MCP address, and its answer written back on stdout, one line each. Standard library only.

    python3 ztp_open_bridge.py [URL]          URL defaults to https://mcp.zerotrustphysics.com/mcp

It is for a client that starts its MCP server as a program (an MCP config's command and args, a Harbor task's stdio
server, the harness's logging proxy in front of it) when the verifier it is to use is the served one. The bridge adds
nothing and drops nothing: a request goes out byte for byte as JSON, its answer comes back as the address gave it; a
notification (no id) is posted and answered by nothing. The session the address opens (Mcp-Session-Id) is kept for
every later message. On HTTP 429, a 5xx, a busy physics pool or a dropped connection it waits and posts the same
message again, as ztp_mcp.Verifier does, so a client sees one answer per request.

Optional: ZTP_API_KEY in the environment sends "Authorization: Bearer <key>" on every post, for a keyed door. With no
key set the bridge sends what it always sent. No key is ever written into a pack, a task or an image.

Licence: Apache-2.0.
"""
import json
import os
import sys
import time
import urllib.error
import urllib.request

OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp"
BUSY = "Too many concurrent physics tasks."
PATIENCE_S = float(os.environ.get("ZTP_BRIDGE_PATIENCE_S", "900"))
API_KEY = os.environ.get("ZTP_API_KEY") or None


class Bridge:
    def __init__(self, url):
        self.url = url
        self.session = None
        self.extra_headers = {}

    def post(self, message):
        body = json.dumps(message).encode()
        headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
                   "User-Agent": "zero-trust-physics-bridge/1.0"}
        if self.session:
            headers["Mcp-Session-Id"] = self.session
        if API_KEY:
            headers["Authorization"] = "Bearer " + API_KEY
        headers.update(self.extra_headers)
        request = urllib.request.Request(self.url, data=body, headers=headers, method="POST")
        with urllib.request.urlopen(request, timeout=600) as response:
            if response.headers.get("Mcp-Session-Id"):
                self.session = response.headers["Mcp-Session-Id"]
            raw = response.read().decode("utf-8")
            kind = response.headers.get("Content-Type", "")
        if "id" not in message:
            return None
        if "text/event-stream" in kind:
            for line in raw.splitlines():
                if line.startswith("data:"):
                    found = json.loads(line[5:].strip())
                    if found.get("id") == message.get("id"):
                        return found
            return {"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32603, "message": "the address's event stream held no answer"}}
        return json.loads(raw) if raw.strip() else None

    def forward(self, message):
        started, wait = time.time(), 2.0
        while True:
            try:
                answer = self.post(message)
                text = ""
                if isinstance(answer, dict) and isinstance(answer.get("result"), dict):
                    text = "".join(c.get("text", "") for c in answer["result"].get("content", []) or [] if isinstance(c, dict))
                if not (BUSY in text and len(text) < 400):
                    return answer
            except urllib.error.HTTPError as problem:
                if not (problem.code == 429 or problem.code >= 500):
                    if "id" not in message:
                        return None
                    return {"jsonrpc": "2.0", "id": message.get("id"),
                            "error": {"code": -32603, "message": "HTTP %d from the verifier's address" % problem.code}}
                after = problem.headers.get("Retry-After")
                if after and after.isdigit():
                    wait = max(wait, float(after))
            except (urllib.error.URLError, TimeoutError, ConnectionError, OSError):
                pass
            if time.time() - started + wait > PATIENCE_S:
                if "id" not in message:
                    return None
                return {"jsonrpc": "2.0", "id": message.get("id"),
                        "error": {"code": -32603, "message": "the verifier's address did not answer in %d s" % PATIENCE_S}}
            time.sleep(wait)
            wait = min(wait * 1.6, 30.0)


def main():
    bridge = Bridge(sys.argv[1] if len(sys.argv) > 1 else OPEN_ADDRESS)
    for line in sys.stdin:
        if not line.strip():
            continue
        try:
            message = json.loads(line)
        except ValueError:
            continue
        answer = bridge.forward(message)
        if answer is not None:
            sys.stdout.write(json.dumps(answer, separators=(",", ":")) + "\n")
            sys.stdout.flush()


if __name__ == "__main__":
    main()