plumbcheck 1.3.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Plumbnote
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: plumbcheck
3
+ Version: 1.3.0
4
+ Summary: Test what your AI automation does before it does it. Local tool-call contracts, fixture replay, and CI reports. Python client and agent-framework adapters.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/stepan4002/plumbcheck
7
+ Project-URL: Documentation, https://github.com/stepan4002/plumbcheck/blob/main/docs/FRAMEWORKS.md
8
+ Project-URL: Changelog, https://github.com/stepan4002/plumbcheck/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/stepan4002/plumbcheck/issues
10
+ Project-URL: Playground, https://stepan4002.github.io/plumbcheck/playground/
11
+ Keywords: ai,agents,mcp,testing,llm,tool-calling,langchain,crewai,autogen,pydantic-ai
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ # PlumbCheck for Python
22
+
23
+ Test what your Python agent *does*: every tool call is answered from fixtures and checked against a contract (allowed tools, forbidden tools, arguments, approvals). No live tools run, no API keys are needed in CI, and a failing run leaves an HTML/JSON/JUnit report with the evidence.
24
+
25
+ ```bash
26
+ pip install plumbcheck
27
+ ```
28
+
29
+ Needs Python 3.9+ and Node.js 22+ on `PATH`. The fixture server ships inside the package, so there is no npm install. There are no Python dependencies.
30
+
31
+ ```python
32
+ from plumbcheck import ReplayClient
33
+
34
+ with ReplayClient("contract.json", "Read-only order lookup", out="reports/python") as client:
35
+ order = client.call_tool("orders.lookup", {"orderId": "ORD-1042"})
36
+ # Your real agent decides what to call next using these fixture responses.
37
+
38
+ assert client.report["passed"]
39
+ ```
40
+
41
+ ## Your framework, unchanged
42
+
43
+ Wrap the tools once; the model sees the same names, descriptions and argument schemas as in production:
44
+
45
+ ```python
46
+ from plumbcheck import ReplayClient
47
+ from plumbcheck_frameworks import replay_tools
48
+
49
+ with ReplayClient("contract.json", "Look up") as client:
50
+ agent = Agent(model, tools=replay_tools([orders_lookup, orders_delete], client))
51
+ agent.run_sync("Where is ORD-1042?")
52
+ ```
53
+
54
+ `replay_tools` works with LangChain / LangGraph, the OpenAI Agents SDK, Pydantic AI, smolagents, LlamaIndex, CrewAI and AutoGen (0.4+). Each one is checked in CI inside the real framework's own agent loop. See [docs/FRAMEWORKS.md](https://github.com/stepan4002/plumbcheck/blob/main/docs/FRAMEWORKS.md).
55
+
56
+ ## Record a contract from a real run
57
+
58
+ Write the agent once as `run(client, input)`. Recording runs the real tools one time and saves what they returned; the same function then replays offline:
59
+
60
+ ```python
61
+ from plumbcheck_frameworks import record_agent, replay_tools
62
+
63
+ def run(client, input):
64
+ agent = Agent(model, tools=replay_tools(tools, client))
65
+ return agent.run_sync(input["message"]).output
66
+
67
+ record_agent(run, tools, input={"message": "Where is ORD-1042?"}, name="Look up", out="plumbcheck/contract.json")
68
+ ```
69
+
70
+ Every recorded tool is allowed. Add `deny`, `requireApproval` and `expect.never` rules afterwards, and review the fixtures for secrets or personal data before committing. Recording calls real tools: use test accounts and synthetic data. `append=True` adds a case to an existing contract.
71
+
72
+ ## Details
73
+
74
+ - `ContractFailed` is raised on a failed tool replay, or at clean close when the contract failed (including when the agent swallowed an earlier tool error). The report stays in `client.report`; an explicit `out` keeps the HTML/JSON/JUnit files.
75
+ - Async agents: `async with AsyncReplayClient(...) as client` and `await client.call_tool(...)`. Async frameworks can also take the synchronous client; calls run in a worker thread.
76
+ - The fixture server is found in this order: `server=`, `$PLUMBCHECK_SERVER`, the copy inside the pip package, a source checkout, then `node_modules/plumbcheck` in the current directory. `node=` or `$PLUMBCHECK_NODE` picks the Node.js runtime.
77
+ - Without pip: `plumbcheck.py` and `plumbcheck_frameworks.py` are plain files in the npm package (`node_modules/plumbcheck/adapters/python`); put that directory on `PYTHONPATH`.
78
+ - Only calls routed through the client are replayed. Python imports, network access, subprocesses and other clients are not isolated. The Python path checks tool-call evidence; it does not assert your function's return value.
79
+
80
+ The API is covered by the [stability policy](https://github.com/stepan4002/plumbcheck/blob/main/docs/STABILITY.md). MIT licensed.
@@ -0,0 +1,60 @@
1
+ # PlumbCheck for Python
2
+
3
+ Test what your Python agent *does*: every tool call is answered from fixtures and checked against a contract (allowed tools, forbidden tools, arguments, approvals). No live tools run, no API keys are needed in CI, and a failing run leaves an HTML/JSON/JUnit report with the evidence.
4
+
5
+ ```bash
6
+ pip install plumbcheck
7
+ ```
8
+
9
+ Needs Python 3.9+ and Node.js 22+ on `PATH`. The fixture server ships inside the package, so there is no npm install. There are no Python dependencies.
10
+
11
+ ```python
12
+ from plumbcheck import ReplayClient
13
+
14
+ with ReplayClient("contract.json", "Read-only order lookup", out="reports/python") as client:
15
+ order = client.call_tool("orders.lookup", {"orderId": "ORD-1042"})
16
+ # Your real agent decides what to call next using these fixture responses.
17
+
18
+ assert client.report["passed"]
19
+ ```
20
+
21
+ ## Your framework, unchanged
22
+
23
+ Wrap the tools once; the model sees the same names, descriptions and argument schemas as in production:
24
+
25
+ ```python
26
+ from plumbcheck import ReplayClient
27
+ from plumbcheck_frameworks import replay_tools
28
+
29
+ with ReplayClient("contract.json", "Look up") as client:
30
+ agent = Agent(model, tools=replay_tools([orders_lookup, orders_delete], client))
31
+ agent.run_sync("Where is ORD-1042?")
32
+ ```
33
+
34
+ `replay_tools` works with LangChain / LangGraph, the OpenAI Agents SDK, Pydantic AI, smolagents, LlamaIndex, CrewAI and AutoGen (0.4+). Each one is checked in CI inside the real framework's own agent loop. See [docs/FRAMEWORKS.md](https://github.com/stepan4002/plumbcheck/blob/main/docs/FRAMEWORKS.md).
35
+
36
+ ## Record a contract from a real run
37
+
38
+ Write the agent once as `run(client, input)`. Recording runs the real tools one time and saves what they returned; the same function then replays offline:
39
+
40
+ ```python
41
+ from plumbcheck_frameworks import record_agent, replay_tools
42
+
43
+ def run(client, input):
44
+ agent = Agent(model, tools=replay_tools(tools, client))
45
+ return agent.run_sync(input["message"]).output
46
+
47
+ record_agent(run, tools, input={"message": "Where is ORD-1042?"}, name="Look up", out="plumbcheck/contract.json")
48
+ ```
49
+
50
+ Every recorded tool is allowed. Add `deny`, `requireApproval` and `expect.never` rules afterwards, and review the fixtures for secrets or personal data before committing. Recording calls real tools: use test accounts and synthetic data. `append=True` adds a case to an existing contract.
51
+
52
+ ## Details
53
+
54
+ - `ContractFailed` is raised on a failed tool replay, or at clean close when the contract failed (including when the agent swallowed an earlier tool error). The report stays in `client.report`; an explicit `out` keeps the HTML/JSON/JUnit files.
55
+ - Async agents: `async with AsyncReplayClient(...) as client` and `await client.call_tool(...)`. Async frameworks can also take the synchronous client; calls run in a worker thread.
56
+ - The fixture server is found in this order: `server=`, `$PLUMBCHECK_SERVER`, the copy inside the pip package, a source checkout, then `node_modules/plumbcheck` in the current directory. `node=` or `$PLUMBCHECK_NODE` picks the Node.js runtime.
57
+ - Without pip: `plumbcheck.py` and `plumbcheck_frameworks.py` are plain files in the npm package (`node_modules/plumbcheck/adapters/python`); put that directory on `PYTHONPATH`.
58
+ - Only calls routed through the client are replayed. Python imports, network access, subprocesses and other clients are not isolated. The Python path checks tool-call evidence; it does not assert your function's return value.
59
+
60
+ The API is covered by the [stability policy](https://github.com/stepan4002/plumbcheck/blob/main/docs/STABILITY.md). MIT licensed.
@@ -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)