spiderpilot89's picture
Update
a5cf2dd verified
Raw History Blame Contribute Delete
8.54 kB
"""A small Model Context Protocol client for the Zero-Trust Physics verifier.
Standard library only. It speaks MCP two ways:
stdio to a verifier built from the public source and started here as a program
(target/release/mcp_stdio): one JSON-RPC message a line, no network.
HTTP to an MCP address (JSON-RPC in a POST), such as
https://mcp.zerotrustphysics.com/mcp/open Open to any agent.
The open address gives each network address one place in the physics pool at a
time and answers "Too many concurrent physics tasks." or HTTP 429 when it is
busy; nothing waits on the server, so this client sends one request at a time
and, when it is told to come back, waits and sends the same request again.
Licence: Apache-2.0.
"""
import json
import select
import shlex
import subprocess
import time
import urllib.error
import urllib.request
OPEN_ADDRESS = "https://mcp.zerotrustphysics.com/mcp/open"
BUSY = "Too many concurrent physics tasks."
class McpError(RuntimeError):
pass
class Verifier:
"""One MCP endpoint. call(tool, arguments) returns (text, is_error)."""
def __init__(self, url=OPEN_ADDRESS, timeout_s=90, patience_s=600, pause_s=0.0, headers=None, quiet=True):
self.url = url
self.timeout_s = timeout_s
self.patience_s = patience_s # how long to keep asking politely before giving up on one request
self.pause_s = pause_s # a fixed pause after every request, for a shared address
self.headers = dict(headers or {})
self.quiet = quiet
self.session = None
self.server = None
self.requests_sent = 0
self.times_asked_to_wait = 0
self._id = 0
# -- transport -------------------------------------------------------------------------
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-environments/1.0", **self.headers}
if self.session:
headers["Mcp-Session-Id"] = self.session
request = urllib.request.Request(self.url, data=body, headers=headers, method="POST")
self.requests_sent += 1
with urllib.request.urlopen(request, timeout=self.timeout_s) as response:
session = response.headers.get("Mcp-Session-Id")
if session:
self.session = session
raw = response.read().decode("utf-8")
kind = response.headers.get("Content-Type", "")
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
raise McpError("the event stream held no answer to the request")
return json.loads(raw) if raw.strip() else {}
def _ask(self, method, params=None):
"""Send one request; on 429, a busy pool, a 5xx or a dropped connection, wait and send it again."""
self._id += 1
message = {"jsonrpc": "2.0", "id": self._id, "method": method}
if params is not None:
message["params"] = params
started, wait = time.time(), 2.0
while True:
reason = None
try:
answer = self._post(message)
if "error" in answer:
raise McpError("protocol error: %s" % json.dumps(answer["error"])[:300])
result = answer.get("result", {})
text = "".join(c.get("text", "") for c in result.get("content", []) or [])
if method == "tools/call" and BUSY in text and len(text) < 400:
reason = "the physics pool is busy"
else:
if self.pause_s:
time.sleep(self.pause_s)
return result
except urllib.error.HTTPError as problem:
if problem.code == 429 or problem.code >= 500:
after = problem.headers.get("Retry-After")
reason = "HTTP %d" % problem.code
if after and after.isdigit():
wait = max(wait, float(after))
else:
raise McpError("HTTP %d: %s" % (problem.code, problem.read().decode("utf-8", "replace")[:300]))
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as problem:
reason = "no connection (%s)" % problem
self.times_asked_to_wait += 1
if time.time() - started + wait > self.patience_s:
raise McpError("gave up after %d s: %s" % (self.patience_s, reason))
if not self.quiet:
print(" %s; asking again in %.0f s" % (reason, wait), flush=True)
time.sleep(wait)
wait = min(wait * 1.6, 30.0)
# -- protocol --------------------------------------------------------------------------
def connect(self):
result = self._ask("initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "zero-trust-physics-environments", "version": "1.0"}})
self.server = result.get("serverInfo")
try:
self._post({"jsonrpc": "2.0", "method": "notifications/initialized"})
except Exception: # a notification has no answer; some servers close without one
pass
return result
def tools(self):
"""The tool declarations exactly as the endpoint gives them."""
return self._ask("tools/list").get("tools", [])
def call(self, tool, arguments=None):
"""Call one tool. Returns (text, is_error): the text of the answer and the MCP isError flag."""
result = self._ask("tools/call", {"name": tool, "arguments": arguments or {}})
text = "".join(c.get("text", "") for c in result.get("content", []) or [])
return text, bool(result.get("isError"))
def call_json(self, tool, arguments=None):
"""Call one tool. Returns (body, is_error): the parsed JSON, or the text when it is not JSON."""
text, is_error = self.call(tool, arguments)
try:
return json.loads(text), is_error
except ValueError:
return text, is_error
class StdioVerifier(Verifier):
"""The same interface over MCP stdio: a program started here that speaks JSON-RPC, one message a line.
For anyone who holds an MCP server as a program; the open address needs none of this."""
def __init__(self, command, timeout_s=600, **kwargs):
super().__init__(url="stdio: " + (command if isinstance(command, str) else " ".join(command)), timeout_s=timeout_s, **kwargs)
self.proc = subprocess.Popen(shlex.split(command) if isinstance(command, str) else command,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
def _post(self, message):
self.requests_sent += 1
try:
self.proc.stdin.write((json.dumps(message) + "\n").encode())
self.proc.stdin.flush()
except OSError: # a program that has stopped reading will not start again
try:
self.proc.stdin.close()
except OSError:
pass
raise McpError("the program stopped reading")
if "id" not in message:
return {}
while True:
ready, _, _ = select.select([self.proc.stdout], [], [], self.timeout_s)
if not ready:
raise McpError("no answer in %d s" % self.timeout_s)
line = self.proc.stdout.readline()
if not line:
raise McpError("the program closed its output")
found = json.loads(line)
if found.get("id") == message["id"]:
return found
def close(self):
self.proc.terminate()
try:
self.proc.wait(timeout=5)
except subprocess.TimeoutExpired:
self.proc.kill()
def connect(endpoint=OPEN_ADDRESS, **kwargs):
"""A connected verifier: an http(s) address, or "stdio:<command>" for a program."""
verifier = StdioVerifier(endpoint[len("stdio:"):].strip(), **kwargs) if endpoint.startswith("stdio:") else Verifier(endpoint, **kwargs)
verifier.connect()
return verifier