plumbcheck 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
plumbcheck/__init__.py ADDED
@@ -0,0 +1,143 @@
1
+ """Standard-library Python client for PlumbCheck's fixture MCP server.
2
+
3
+ Only calls through this client are replayed. Agent Python itself is not isolated.
4
+ """
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import queue
9
+ import subprocess
10
+ import tempfile
11
+ import threading
12
+
13
+ __version__ = "1.3.0"
14
+
15
+
16
+ class ContractFailed(RuntimeError):
17
+ pass
18
+
19
+
20
+ def find_server():
21
+ """The fixture server script: $PLUMBCHECK_SERVER, the copy bundled in the pip package,
22
+ a source checkout, or `node_modules/plumbcheck` in the current directory."""
23
+ configured = os.environ.get("PLUMBCHECK_SERVER")
24
+ if configured:
25
+ return Path(configured)
26
+ here = Path(__file__).resolve().parent
27
+ for candidate in (
28
+ here / "_server" / "bin" / "plumbcheck-mcp.mjs",
29
+ here.parents[1] / "bin" / "plumbcheck-mcp.js",
30
+ Path.cwd() / "node_modules" / "plumbcheck" / "bin" / "plumbcheck-mcp.js",
31
+ ):
32
+ if candidate.exists():
33
+ return candidate
34
+ raise FileNotFoundError("PlumbCheck's fixture server was not found. Install with `pip install plumbcheck`, or pass server= / set PLUMBCHECK_SERVER to node_modules/plumbcheck/bin/plumbcheck-mcp.js.")
35
+
36
+
37
+ class ReplayClient:
38
+ def __init__(self, contract, case, *, node=None, server=None, out=None, timeout=30):
39
+ self._temporary = tempfile.TemporaryDirectory(prefix="plumbcheck-python-") if out is None else None
40
+ self.out = Path(out or self._temporary.name).resolve()
41
+ script = Path(server) if server else find_server()
42
+ self._queue = queue.Queue()
43
+ self._lock = threading.Lock()
44
+ self._id = 0
45
+ self._closed = False
46
+ self.timeout = timeout
47
+ self.report = None
48
+ runtime = node or os.environ.get("PLUMBCHECK_NODE", "node")
49
+ try:
50
+ self._process = subprocess.Popen(
51
+ [runtime, str(script), str(Path(contract).resolve()), case, "--out", str(self.out)],
52
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
53
+ text=True, encoding="utf-8", creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
54
+ )
55
+ except FileNotFoundError:
56
+ if self._temporary:
57
+ self._temporary.cleanup()
58
+ raise FileNotFoundError(f"Node.js 22+ is required to run PlumbCheck's fixture server and {runtime!r} was not found. Install Node.js, or pass node= / set PLUMBCHECK_NODE.") from None
59
+ threading.Thread(target=self._read, daemon=True).start()
60
+ try:
61
+ self._request("initialize", {"protocolVersion": "2025-11-25", "capabilities": {}, "clientInfo": {"name": "plumbcheck-python", "version": __version__}})
62
+ except Exception:
63
+ self.close(check=False)
64
+ raise
65
+
66
+ def _read(self):
67
+ try:
68
+ for line in self._process.stdout:
69
+ self._queue.put(json.loads(line))
70
+ except Exception as error:
71
+ self._queue.put(error)
72
+ finally:
73
+ self._queue.put(EOFError("Fixture server disconnected."))
74
+
75
+ def _request(self, method, params):
76
+ with self._lock:
77
+ if self._closed:
78
+ raise RuntimeError("Replay client is closed.")
79
+ self._id += 1
80
+ self._process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": self._id, "method": method, "params": params}) + "\n")
81
+ self._process.stdin.flush()
82
+ value = self._queue.get(timeout=self.timeout)
83
+ if isinstance(value, BaseException):
84
+ raise value
85
+ if value.get("id") != self._id:
86
+ raise RuntimeError("Unexpected response ID from fixture server.")
87
+ if "error" in value:
88
+ raise ContractFailed(value["error"]["message"])
89
+ return value["result"]
90
+
91
+ def call_tool(self, name, arguments=None):
92
+ result = self._request("tools/call", {"name": name, "arguments": arguments or {}})
93
+ if result.get("isError"):
94
+ raise ContractFailed("Tool replay failed. Inspect the saved report for evidence.")
95
+ return result.get("structuredContent", result)
96
+
97
+ def close(self, *, check=True):
98
+ if self._closed:
99
+ return self.report
100
+ self._closed = True
101
+ try:
102
+ self._process.stdin.close()
103
+ try:
104
+ code = self._process.wait(timeout=self.timeout)
105
+ except subprocess.TimeoutExpired:
106
+ self._process.kill()
107
+ self._process.wait()
108
+ raise TimeoutError("Fixture server did not shut down in time.")
109
+ report = self.out / "report.json"
110
+ if report.exists():
111
+ self.report = json.loads(report.read_text(encoding="utf-8"))
112
+ if check and (code != 0 or not self.report or not self.report.get("passed")):
113
+ raise ContractFailed("Agent execution failed the contract. Inspect client.report or the output directory.")
114
+ return self.report
115
+ finally:
116
+ if self._temporary:
117
+ self._temporary.cleanup()
118
+
119
+ def __enter__(self):
120
+ return self
121
+
122
+ def __exit__(self, error_type, error, traceback):
123
+ self.close(check=error is None)
124
+
125
+
126
+ class AsyncReplayClient:
127
+ """For async Python agents; each request uses the same serialized transport."""
128
+ def __init__(self, *args, **kwargs):
129
+ self._args, self._kwargs = args, kwargs
130
+ self.client = None
131
+
132
+ async def __aenter__(self):
133
+ import asyncio
134
+ self.client = await asyncio.to_thread(ReplayClient, *self._args, **self._kwargs)
135
+ return self
136
+
137
+ async def call_tool(self, name, arguments=None):
138
+ import asyncio
139
+ return await asyncio.to_thread(self.client.call_tool, name, arguments)
140
+
141
+ async def __aexit__(self, error_type, error, traceback):
142
+ import asyncio
143
+ await asyncio.to_thread(self.client.close, check=error is None)