chronos-gateway 0.1.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,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: chronos-gateway
3
+ Version: 0.1.0
4
+ Summary: Client for Chronos Gateway: AI agents change your Postgres only through checked, approved merges
5
+ License-Expression: BUSL-1.1
6
+ Project-URL: Homepage, https://chronos.2090.tech
7
+ Keywords: postgres,ai-agents,mcp,chronos,approvals
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Framework :: Pytest
10
+ Classifier: Topic :: Database
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+
14
+ # chronos-gateway
15
+
16
+ The Python client for Chronos Gateway: AI agents change your Postgres only through checked, approved merges. Each
17
+ agent task is a run for one tenant, working in its own copy of your data; its merge lands when your rules allow it,
18
+ or waits for a person to approve it. Standard library only, Python 3.9+.
19
+
20
+ ```bash
21
+ pip install chronos-gateway
22
+ ```
23
+
24
+ ```python
25
+ from chronos_gateway import Gateway
26
+
27
+ gw = Gateway("https://gateway.example.com", key=os.environ["CHRONOS_GATEWAY_KEY"])
28
+ with gw.run(tenant=user.org_id, intent="clean up duplicate leads", end_user=user.id) as run:
29
+ agent.tools = run.openai_tools() # or run.mcp_server() for MCP clients
30
+ agent.invoke(task)
31
+ result = run.propose()
32
+ if result.held:
33
+ link = gw.approval(run.id, end_user=user.id) # show link.html (the <chronos-approve> widget) to the user
34
+ ```
35
+
36
+ - `AsyncGateway` runs the same calls for asyncio code.
37
+ - `chronos_gateway.adapters`: the run's tools for LangChain and LangGraph, the Claude Agent SDK and the OpenAI Agents
38
+ SDK (each needs its framework installed).
39
+ - A pytest fixture, `chronos_run`: a run discarded after the test (set `CHRONOS_GATEWAY_URL`, `CHRONOS_GATEWAY_KEY`
40
+ and `CHRONOS_GATEWAY_TENANT`).
41
+ - `verify_signature` checks a webhook delivery's `Chronos-Signature`.
42
+
43
+ The gateway itself is chronos-gateway, which you run beside your Postgres (or link to Chronos Cloud).
@@ -0,0 +1,30 @@
1
+ # chronos-gateway
2
+
3
+ The Python client for Chronos Gateway: AI agents change your Postgres only through checked, approved merges. Each
4
+ agent task is a run for one tenant, working in its own copy of your data; its merge lands when your rules allow it,
5
+ or waits for a person to approve it. Standard library only, Python 3.9+.
6
+
7
+ ```bash
8
+ pip install chronos-gateway
9
+ ```
10
+
11
+ ```python
12
+ from chronos_gateway import Gateway
13
+
14
+ gw = Gateway("https://gateway.example.com", key=os.environ["CHRONOS_GATEWAY_KEY"])
15
+ with gw.run(tenant=user.org_id, intent="clean up duplicate leads", end_user=user.id) as run:
16
+ agent.tools = run.openai_tools() # or run.mcp_server() for MCP clients
17
+ agent.invoke(task)
18
+ result = run.propose()
19
+ if result.held:
20
+ link = gw.approval(run.id, end_user=user.id) # show link.html (the <chronos-approve> widget) to the user
21
+ ```
22
+
23
+ - `AsyncGateway` runs the same calls for asyncio code.
24
+ - `chronos_gateway.adapters`: the run's tools for LangChain and LangGraph, the Claude Agent SDK and the OpenAI Agents
25
+ SDK (each needs its framework installed).
26
+ - A pytest fixture, `chronos_run`: a run discarded after the test (set `CHRONOS_GATEWAY_URL`, `CHRONOS_GATEWAY_KEY`
27
+ and `CHRONOS_GATEWAY_TENANT`).
28
+ - `verify_signature` checks a webhook delivery's `Chronos-Signature`.
29
+
30
+ The gateway itself is chronos-gateway, which you run beside your Postgres (or link to Chronos Cloud).
@@ -0,0 +1,298 @@
1
+ """Chronos Gateway client: run AI agents against your Postgres through checked, approved merges.
2
+
3
+ from chronos_gateway import Gateway
4
+
5
+ gw = Gateway("https://gateway.example.com", key=os.environ["CHRONOS_GATEWAY_KEY"])
6
+ with gw.run(tenant=user.org_id, intent="clean up duplicate leads", end_user=user.id) as run:
7
+ agent.tools = run.openai_tools() # or run.mcp_server() for MCP clients
8
+ agent.invoke(task)
9
+ result = run.propose()
10
+ if result.held:
11
+ link = gw.approval(run.id, end_user=user.id) # show link.html (the <chronos-approve> widget) to the user
12
+
13
+ A run that leaves its `with` block without proposing is discarded. Nothing here needs a package beyond the
14
+ standard library; `AsyncGateway` runs the same calls on a thread for asyncio code.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import hashlib
21
+ import hmac
22
+ import json
23
+ import time
24
+ import urllib.error
25
+ import urllib.request
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Callable, Optional
28
+
29
+ __all__ = ["Gateway", "AsyncGateway", "Run", "Proposal", "Approval", "GatewayError", "verify_signature"]
30
+ __version__ = "0.1.0"
31
+
32
+
33
+ class GatewayError(Exception):
34
+ """An error the gateway (or the engine behind it) answered: `status`, `code` (a SQLSTATE or the gateway's own,
35
+ such as "held", "conflict", "expired", "stale"), and the `body`."""
36
+
37
+ def __init__(self, status: int, message: str, code: Optional[str] = None, body: Any = None):
38
+ super().__init__(message)
39
+ self.status, self.code, self.body = status, code, body
40
+
41
+
42
+ def _settle(by_columns: bool, resolve: Optional[str], rows: Optional[dict], target: Optional[int]) -> dict:
43
+ """How a merge settles rows both the run and main changed, as the gateway takes it (see Run.propose)."""
44
+ out: dict = {}
45
+ if by_columns:
46
+ out["by_columns"] = True
47
+ for k, v in (("resolve", resolve), ("rows", rows), ("target", target)):
48
+ if v is not None:
49
+ out[k] = v
50
+ return out
51
+
52
+
53
+ def _request(method: str, url: str, token: str, body: Any = None, timeout: float = 120) -> tuple[int, Any]:
54
+ data = None if body is None else json.dumps(body).encode()
55
+ req = urllib.request.Request(url, data=data, method=method)
56
+ req.add_header("Authorization", f"Bearer {token}")
57
+ if data is not None:
58
+ req.add_header("Content-Type", "application/json")
59
+ try:
60
+ with urllib.request.urlopen(req, timeout=timeout) as res:
61
+ text = res.read().decode()
62
+ return res.status, (json.loads(text) if text else None)
63
+ except urllib.error.HTTPError as e:
64
+ text = e.read().decode()
65
+ try:
66
+ payload = json.loads(text)
67
+ except ValueError:
68
+ payload = {"error": text}
69
+ err = payload.get("error") if isinstance(payload, dict) else None
70
+ message = err.get("message") if isinstance(err, dict) else (err or f"HTTP {e.code}")
71
+ code = err.get("code") if isinstance(err, dict) else None
72
+ raise GatewayError(e.code, message, code, payload) from None
73
+
74
+
75
+ @dataclass
76
+ class Proposal:
77
+ """How a run's merge ended: `status` is "merged", "held" (waiting for a person, `reasons` say why) or, raised as
78
+ a GatewayError instead, "conflict" / "expired"."""
79
+
80
+ status: str
81
+ merged: Optional[int] = None
82
+ reasons: Any = None
83
+ raw: dict = field(default_factory=dict)
84
+
85
+ @property
86
+ def held(self) -> bool:
87
+ return self.status == "held"
88
+
89
+ @property
90
+ def landed(self) -> bool:
91
+ return self.status == "merged"
92
+
93
+
94
+ @dataclass
95
+ class Approval:
96
+ token: str
97
+ expires: int
98
+ html: str
99
+ script: str
100
+ raw: dict = field(default_factory=dict)
101
+
102
+
103
+ class Run:
104
+ """One agent task for one tenant: SQL and MCP in its own world, then `propose`."""
105
+
106
+ def __init__(self, gw: "Gateway", data: dict):
107
+ self._gw = gw
108
+ self.data = data
109
+ self.id: str = data["id"]
110
+ self.token: str = data["token"]
111
+ self.sql_url: str = data["sql_url"]
112
+ self.mcp_url: str = data["mcp_url"]
113
+ self.proposed: Optional[Proposal] = None
114
+
115
+ # ---- what the agent does
116
+
117
+ def sql(self, query: str, params: Optional[list] = None) -> list[dict]:
118
+ """Runs SQL as the run's agent in its world (its tenant's rows only); the last statement's rows."""
119
+ _, v = _request("POST", self.sql_url, self.token, {"sql": query, "params": params or []})
120
+ results = v.get("results") or []
121
+ return results[-1].get("rows", []) if results else []
122
+
123
+ def execute(self, query: str, params: Optional[list] = None) -> dict:
124
+ """`sql`, returning the whole reply (every statement's command, columns and rows)."""
125
+ _, v = _request("POST", self.sql_url, self.token, {"sql": query, "params": params or []})
126
+ return v
127
+
128
+ def mcp_server(self, name: str = "chronos") -> dict:
129
+ """MCP over HTTP for this run, as Claude Code / the Claude Agent SDK take a server's config."""
130
+ return {name: {"type": "http", "url": self.mcp_url, "headers": {"Authorization": f"Bearer {self.token}"}}}
131
+
132
+ def openai_tools(self) -> list[dict]:
133
+ """Function tools (OpenAI / Anthropic tool-use shape) for this run: `query` and `changes`. Call
134
+ `run.call_tool(name, arguments)` with what the model asks for."""
135
+ return [
136
+ {
137
+ "type": "function",
138
+ "function": {
139
+ "name": "query",
140
+ "description": "Run SQL (Postgres dialect) on the database. Reads see only the rows this task may "
141
+ "touch; writes are made in a private copy and only reach the real database once approved.",
142
+ "parameters": {
143
+ "type": "object",
144
+ "properties": {"sql": {"type": "string"}, "params": {"type": "array", "items": {}}},
145
+ "required": ["sql"],
146
+ },
147
+ },
148
+ },
149
+ {
150
+ "type": "function",
151
+ "function": {
152
+ "name": "changes",
153
+ "description": "List the changes this task has made so far, in plain words.",
154
+ "parameters": {"type": "object", "properties": {}},
155
+ },
156
+ },
157
+ ]
158
+
159
+ def call_tool(self, name: str, arguments: dict | str) -> str:
160
+ """Runs one of `openai_tools()` as the model asked; the result as JSON text for the model."""
161
+ args = json.loads(arguments) if isinstance(arguments, str) else (arguments or {})
162
+ try:
163
+ if name == "query":
164
+ return json.dumps(self.execute(args["sql"], args.get("params")), default=str)
165
+ if name == "changes":
166
+ return json.dumps([c["text"] for c in self.changes().get("changes", [])])
167
+ return json.dumps({"error": f"no tool {name}"})
168
+ except GatewayError as e:
169
+ return json.dumps({"error": str(e), "code": e.code})
170
+
171
+ # ---- what your backend does
172
+
173
+ def changes(self, limit: int = 200) -> dict:
174
+ _, v = _request("GET", f"{self._gw.url}/v1/runs/{self.id}/changes?limit={limit}", self._gw.key)
175
+ return v
176
+
177
+ def propose(self, confirm_deletes: Optional[int] = None, by_columns: bool = False,
178
+ resolve: Optional[str] = None, rows: Optional[dict] = None,
179
+ target: Optional[int] = None) -> Proposal:
180
+ """The run's merge. On a 409 conflict (rows main changed too), propose again settled, safest
181
+ first: by_columns=True combines rows where the sides changed different columns, and with
182
+ resolve="ours" or "theirs" too picks that side only for the columns both changed; rows
183
+ ({"table/id": "ours" | "theirs" | "delete" | row dict}) settles single rows; resolve alone
184
+ takes whole rows, overwriting main's changes to other columns."""
185
+ body = _settle(by_columns, resolve, rows, target)
186
+ if confirm_deletes is not None:
187
+ body["confirm_deletes"] = confirm_deletes
188
+ status, v = _request("POST", f"{self._gw.url}/v1/runs/{self.id}/propose", self._gw.key, body)
189
+ self.proposed = Proposal(v.get("status"), v.get("merged"), v.get("reasons"), v)
190
+ return self.proposed
191
+
192
+ def discard(self) -> None:
193
+ _request("DELETE", f"{self._gw.url}/v1/runs/{self.id}", self._gw.key)
194
+
195
+ def __enter__(self) -> "Run":
196
+ return self
197
+
198
+ def __exit__(self, kind, value, tb) -> None:
199
+ if self.proposed is None:
200
+ try:
201
+ self.discard()
202
+ except GatewayError:
203
+ pass
204
+
205
+
206
+ class Gateway:
207
+ def __init__(self, url: str, key: str):
208
+ self.url = url.rstrip("/")
209
+ self.key = key
210
+
211
+ def _call(self, method: str, path: str, body: Any = None) -> Any:
212
+ return _request(method, f"{self.url}{path}", self.key, body)[1]
213
+
214
+ def run(
215
+ self,
216
+ tenant: Any,
217
+ intent: str,
218
+ *,
219
+ end_user: Optional[str] = None,
220
+ may_change: Optional[str] = None,
221
+ max_rows: Optional[int] = None,
222
+ ttl_seconds: Optional[int] = None,
223
+ run_id: Optional[str] = None,
224
+ meta: Optional[dict] = None,
225
+ ) -> Run:
226
+ """Starts a run for `tenant` (a value of the tenant column set at connect, or {"org_id": 42})."""
227
+ body = {"tenant": tenant, "intent": intent}
228
+ for k, v in [("end_user", end_user), ("may_change", may_change), ("max_rows", max_rows),
229
+ ("ttl_seconds", ttl_seconds), ("run_id", run_id), ("meta", meta)]:
230
+ if v is not None:
231
+ body[k] = v
232
+ return Run(self, self._call("POST", "/v1/runs", body))
233
+
234
+ def get_run(self, run_id: str) -> dict:
235
+ return self._call("GET", f"/v1/runs/{run_id}")
236
+
237
+ def runs(self, status: Optional[str] = None, limit: int = 50) -> list[dict]:
238
+ q = f"?limit={limit}" + (f"&status={status}" if status else "")
239
+ return self._call("GET", f"/v1/runs{q}")["runs"]
240
+
241
+ def approval(self, run_id: str, end_user: Optional[str] = None, expires_in: Optional[int] = None) -> Approval:
242
+ """A one-time link for a person to approve or reject a held run (`<chronos-approve>`)."""
243
+ body = {k: v for k, v in [("end_user", end_user), ("expires_in", expires_in)] if v is not None}
244
+ v = self._call("POST", f"/v1/runs/{run_id}/approvals", body)
245
+ return Approval(v["token"], v["expires"], v["widget"]["html"], v["widget"]["script"], v)
246
+
247
+ def approve(self, run_id: str, version: Optional[int] = None, by: Any = None, by_columns: bool = False,
248
+ resolve: Optional[str] = None, rows: Optional[dict] = None, target: Optional[int] = None) -> dict:
249
+ """Merges a held run, or one in conflict, as a person; conflicts settled as in Run.propose."""
250
+ body = {"version": version, "by": by, **_settle(by_columns, resolve, rows, target)}
251
+ return self._call("POST", f"/v1/runs/{run_id}/approve", body)
252
+
253
+ def reject(self, run_id: str, reason: Optional[str] = None, by: Any = None) -> dict:
254
+ return self._call("POST", f"/v1/runs/{run_id}/reject", {"reason": reason, "by": by})
255
+
256
+ def set_labels(self, labels: dict) -> dict:
257
+ return self._call("PUT", "/v1/labels", labels)
258
+
259
+ def add_webhook(self, url: str, events: Optional[list[str]] = None) -> dict:
260
+ """Returns the webhook with its `secret` (shown once): check deliveries with `verify_signature`."""
261
+ return self._call("POST", "/v1/webhooks", {"url": url, "events": events or []})
262
+
263
+ def status(self) -> dict:
264
+ return self._call("GET", "/v1/status")
265
+
266
+ def refresh(self) -> dict:
267
+ return self._call("POST", "/v1/refresh", {})
268
+
269
+
270
+ class AsyncGateway:
271
+ """`Gateway`'s calls for asyncio code, each on a worker thread."""
272
+
273
+ def __init__(self, url: str, key: str):
274
+ self._gw = Gateway(url, key)
275
+
276
+ def __getattr__(self, name: str) -> Callable:
277
+ f = getattr(self._gw, name)
278
+
279
+ async def call(*a, **kw):
280
+ return await asyncio.to_thread(f, *a, **kw)
281
+
282
+ return call
283
+
284
+
285
+ def verify_signature(secret: str, header: str, body: bytes | str, tolerance: int = 300) -> bool:
286
+ """Whether a webhook delivery's `Chronos-Signature` header signs `body` (the raw bytes received)."""
287
+ if isinstance(body, bytes):
288
+ body = body.decode()
289
+ parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
290
+ try:
291
+ t = int(parts.get("t", ""))
292
+ except ValueError:
293
+ return False
294
+ if abs(time.time() - t) > tolerance:
295
+ return False
296
+ want = hmac.new(secret.encode(), f"{t}.{body}".encode(), hashlib.sha256).hexdigest()
297
+ sigs = [v for k, v in (p.split("=", 1) for p in header.split(",") if "=" in p) if k.strip() == "v1"]
298
+ return any(hmac.compare_digest(s, want) for s in sigs)
@@ -0,0 +1,57 @@
1
+ """A run's tools for agent frameworks. Each needs its framework installed; nothing here is imported until asked.
2
+
3
+ from chronos_gateway.adapters import langchain_tools, claude_agent_options
4
+
5
+ tools = langchain_tools(run) # LangChain / LangGraph: StructuredTools for the run
6
+ options = claude_agent_options(run, system="...") # Claude Agent SDK: the run as an MCP server
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ from . import Run
14
+
15
+
16
+ def langchain_tools(run: Run) -> list:
17
+ """`query` and `changes` as LangChain StructuredTools (LangGraph's prebuilt agents take them as they are)."""
18
+ from langchain_core.tools import StructuredTool # type: ignore
19
+
20
+ def query(sql: str, params: list | None = None) -> str:
21
+ """Run SQL (Postgres dialect). Reads see only the rows this task may touch; writes are made in a private
22
+ copy and reach the real database only once approved."""
23
+ return run.call_tool("query", {"sql": sql, "params": params or []})
24
+
25
+ def changes() -> str:
26
+ """List the changes this task has made so far, in plain words."""
27
+ return run.call_tool("changes", {})
28
+
29
+ return [StructuredTool.from_function(query), StructuredTool.from_function(changes)]
30
+
31
+
32
+ def claude_agent_options(run: Run, **kwargs: Any) -> Any:
33
+ """ClaudeAgentOptions with the run's MCP server, its tools allowed (`mcp__chronos__*`)."""
34
+ from claude_agent_sdk import ClaudeAgentOptions # type: ignore
35
+
36
+ servers = run.mcp_server("chronos")
37
+ allowed = kwargs.pop("allowed_tools", None) or [
38
+ f"mcp__chronos__{t}" for t in ("describe", "find", "sql", "put", "diff", "merge_preview", "check_reads")
39
+ ]
40
+ return ClaudeAgentOptions(mcp_servers=servers, allowed_tools=allowed, **kwargs)
41
+
42
+
43
+ def openai_agents_tools(run: Run) -> list:
44
+ """The run's tools for the OpenAI Agents SDK (`function_tool`)."""
45
+ from agents import function_tool # type: ignore
46
+
47
+ @function_tool
48
+ def query(sql: str) -> str:
49
+ """Run SQL (Postgres dialect) on the task's rows; writes reach the real database only once approved."""
50
+ return run.call_tool("query", {"sql": sql})
51
+
52
+ @function_tool
53
+ def changes() -> str:
54
+ """List the changes this task has made so far, in plain words."""
55
+ return run.call_tool("changes", {})
56
+
57
+ return [query, changes]
@@ -0,0 +1,30 @@
1
+ """A pytest fixture for testing agents against a gateway: `chronos_run`, a run discarded after the test.
2
+
3
+ def test_agent_reassigns_leads(chronos_run):
4
+ my_agent(chronos_run.openai_tools(), chronos_run.call_tool).run("reassign Bo's leads to Ada")
5
+ changes = chronos_run.changes()
6
+ assert changes["total"] == 2
7
+
8
+ Set CHRONOS_GATEWAY_URL, CHRONOS_GATEWAY_KEY and CHRONOS_GATEWAY_TENANT (a test tenant's value); without them the
9
+ fixture skips the test. Nothing reaches Postgres unless the test proposes and the rules let it through.
10
+ """
11
+
12
+ import os
13
+
14
+ import pytest
15
+
16
+ from . import Gateway
17
+
18
+
19
+ @pytest.fixture
20
+ def chronos_run(request):
21
+ url, key = os.environ.get("CHRONOS_GATEWAY_URL"), os.environ.get("CHRONOS_GATEWAY_KEY")
22
+ tenant = os.environ.get("CHRONOS_GATEWAY_TENANT")
23
+ if not (url and key and tenant):
24
+ pytest.skip("set CHRONOS_GATEWAY_URL, CHRONOS_GATEWAY_KEY and CHRONOS_GATEWAY_TENANT")
25
+ run = Gateway(url, key).run(tenant=tenant, intent=f"test {request.node.name}", ttl_seconds=600)
26
+ yield run
27
+ try:
28
+ run.discard()
29
+ except Exception:
30
+ pass
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: chronos-gateway
3
+ Version: 0.1.0
4
+ Summary: Client for Chronos Gateway: AI agents change your Postgres only through checked, approved merges
5
+ License-Expression: BUSL-1.1
6
+ Project-URL: Homepage, https://chronos.2090.tech
7
+ Keywords: postgres,ai-agents,mcp,chronos,approvals
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Framework :: Pytest
10
+ Classifier: Topic :: Database
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+
14
+ # chronos-gateway
15
+
16
+ The Python client for Chronos Gateway: AI agents change your Postgres only through checked, approved merges. Each
17
+ agent task is a run for one tenant, working in its own copy of your data; its merge lands when your rules allow it,
18
+ or waits for a person to approve it. Standard library only, Python 3.9+.
19
+
20
+ ```bash
21
+ pip install chronos-gateway
22
+ ```
23
+
24
+ ```python
25
+ from chronos_gateway import Gateway
26
+
27
+ gw = Gateway("https://gateway.example.com", key=os.environ["CHRONOS_GATEWAY_KEY"])
28
+ with gw.run(tenant=user.org_id, intent="clean up duplicate leads", end_user=user.id) as run:
29
+ agent.tools = run.openai_tools() # or run.mcp_server() for MCP clients
30
+ agent.invoke(task)
31
+ result = run.propose()
32
+ if result.held:
33
+ link = gw.approval(run.id, end_user=user.id) # show link.html (the <chronos-approve> widget) to the user
34
+ ```
35
+
36
+ - `AsyncGateway` runs the same calls for asyncio code.
37
+ - `chronos_gateway.adapters`: the run's tools for LangChain and LangGraph, the Claude Agent SDK and the OpenAI Agents
38
+ SDK (each needs its framework installed).
39
+ - A pytest fixture, `chronos_run`: a run discarded after the test (set `CHRONOS_GATEWAY_URL`, `CHRONOS_GATEWAY_KEY`
40
+ and `CHRONOS_GATEWAY_TENANT`).
41
+ - `verify_signature` checks a webhook delivery's `Chronos-Signature`.
42
+
43
+ The gateway itself is chronos-gateway, which you run beside your Postgres (or link to Chronos Cloud).
@@ -0,0 +1,11 @@
1
+ README.md
2
+ pyproject.toml
3
+ chronos_gateway/__init__.py
4
+ chronos_gateway/adapters.py
5
+ chronos_gateway/pytest_plugin.py
6
+ chronos_gateway.egg-info/PKG-INFO
7
+ chronos_gateway.egg-info/SOURCES.txt
8
+ chronos_gateway.egg-info/dependency_links.txt
9
+ chronos_gateway.egg-info/entry_points.txt
10
+ chronos_gateway.egg-info/top_level.txt
11
+ tests/test_client.py
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ chronos_gateway = chronos_gateway.pytest_plugin
@@ -0,0 +1 @@
1
+ chronos_gateway
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "chronos-gateway"
3
+ version = "0.1.0"
4
+ description = "Client for Chronos Gateway: AI agents change your Postgres only through checked, approved merges"
5
+ requires-python = ">=3.9"
6
+ readme = "README.md"
7
+ license = "BUSL-1.1"
8
+ keywords = ["postgres", "ai-agents", "mcp", "chronos", "approvals"]
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3",
11
+ "Framework :: Pytest",
12
+ "Topic :: Database",
13
+ ]
14
+
15
+ dependencies = []
16
+
17
+ [project.urls]
18
+ Homepage = "https://chronos.2090.tech"
19
+
20
+ [project.entry-points.pytest11]
21
+ chronos_gateway = "chronos_gateway.pytest_plugin"
22
+
23
+ [build-system]
24
+ requires = ["setuptools>=77"]
25
+ build-backend = "setuptools.build_meta"
26
+
27
+ [tool.setuptools]
28
+ packages = ["chronos_gateway"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,113 @@
1
+ """The Python client against a stand-in gateway (no network beyond loopback): requests, errors, tools, signatures."""
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import threading
7
+ import time
8
+ import unittest
9
+ from http.server import BaseHTTPRequestHandler, HTTPServer
10
+
11
+ from chronos_gateway import Gateway, GatewayError, verify_signature
12
+
13
+ SEEN = []
14
+
15
+
16
+ class Fake(BaseHTTPRequestHandler):
17
+ def log_message(self, *a):
18
+ pass
19
+
20
+ def reply(self, status, body):
21
+ data = json.dumps(body).encode()
22
+ self.send_response(status)
23
+ self.send_header("Content-Type", "application/json")
24
+ self.send_header("Content-Length", str(len(data)))
25
+ self.end_headers()
26
+ self.wfile.write(data)
27
+
28
+ def body(self):
29
+ n = int(self.headers.get("Content-Length") or 0)
30
+ return json.loads(self.rfile.read(n) or b"null")
31
+
32
+ def do_POST(self):
33
+ b = self.body()
34
+ SEEN.append((self.command, self.path, self.headers.get("Authorization"), b))
35
+ base = f"http://{self.server.server_address[0]}:{self.server.server_address[1]}"
36
+ if self.path == "/v1/runs":
37
+ return self.reply(201, {"id": "run_1", "token": "cgr_t", "sql_url": f"{base}/v1/runs/run_1/sql",
38
+ "mcp_url": f"{base}/v1/runs/run_1/mcp", "status": "open"})
39
+ if self.path == "/v1/runs/run_1/sql":
40
+ if "boom" in b["sql"]:
41
+ return self.reply(400, {"error": {"message": "syntax error", "code": "42601"}})
42
+ return self.reply(200, {"results": [{"command": "SELECT 1", "rows": [{"n": 2}]}]})
43
+ if self.path == "/v1/runs/run_1/propose":
44
+ return self.reply(202, {"status": "held", "reasons": "it deletes 1 rows (max_deletes 0)"})
45
+ if self.path == "/v1/runs/run_1/approvals":
46
+ return self.reply(200, {"token": "cga_x", "expires": 1, "widget": {"html": "<chronos-approve>", "script": "s"}})
47
+ return self.reply(404, {"error": "no"})
48
+
49
+ def do_DELETE(self):
50
+ SEEN.append((self.command, self.path, self.headers.get("Authorization"), None))
51
+ self.reply(200, {"status": "discarded"})
52
+
53
+ def do_GET(self):
54
+ SEEN.append((self.command, self.path, self.headers.get("Authorization"), None))
55
+ self.reply(200, {"changes": [{"text": "Remove lead “Hooli”"}], "total": 1})
56
+
57
+
58
+ class ClientTest(unittest.TestCase):
59
+ @classmethod
60
+ def setUpClass(cls):
61
+ cls.server = HTTPServer(("127.0.0.1", 0), Fake)
62
+ threading.Thread(target=cls.server.serve_forever, daemon=True).start()
63
+ cls.gw = Gateway(f"http://127.0.0.1:{cls.server.server_address[1]}", "cgk_dev")
64
+
65
+ @classmethod
66
+ def tearDownClass(cls):
67
+ cls.server.shutdown()
68
+
69
+ def setUp(self):
70
+ SEEN.clear()
71
+
72
+ def test_a_run_from_start_to_held(self):
73
+ with self.gw.run(tenant=42, intent="tidy", end_user="u7") as run:
74
+ self.assertEqual(run.sql("select count(*) as n from leads"), [{"n": 2}])
75
+ p = run.propose()
76
+ self.assertTrue(p.held)
77
+ self.assertIn("deletes", p.reasons)
78
+ # the run's own token for SQL, the developer key for the rest; a proposed run isn't discarded
79
+ self.assertEqual(SEEN[0][2], "Bearer cgk_dev")
80
+ self.assertEqual(SEEN[0][3], {"tenant": 42, "intent": "tidy", "end_user": "u7"})
81
+ self.assertEqual(SEEN[1][2], "Bearer cgr_t")
82
+ self.assertFalse(any(m == "DELETE" for m, *_ in SEEN))
83
+ a = self.gw.approval("run_1", end_user="u7")
84
+ self.assertEqual(a.token, "cga_x")
85
+
86
+ def test_a_run_left_without_proposing_is_discarded(self):
87
+ with self.gw.run(tenant=42, intent="look"):
88
+ pass
89
+ self.assertEqual(SEEN[-1][:2], ("DELETE", "/v1/runs/run_1"))
90
+
91
+ def test_errors_carry_their_code(self):
92
+ run = self.gw.run(tenant=42, intent="x")
93
+ with self.assertRaises(GatewayError) as e:
94
+ run.sql("boom")
95
+ self.assertEqual((e.exception.status, e.exception.code), (400, "42601"))
96
+ # as a tool, the error goes back to the model as text
97
+ out = json.loads(run.call_tool("query", '{"sql": "boom"}'))
98
+ self.assertEqual(out["code"], "42601")
99
+ self.assertEqual(json.loads(run.call_tool("changes", {})), ["Remove lead “Hooli”"])
100
+ self.assertEqual(run.mcp_server()["chronos"]["headers"]["Authorization"], "Bearer cgr_t")
101
+
102
+ def test_signatures(self):
103
+ t = int(time.time())
104
+ body = '{"type":"merge.held"}'
105
+ sig = hmac.new(b"whsec", f"{t}.{body}".encode(), hashlib.sha256).hexdigest()
106
+ self.assertTrue(verify_signature("whsec", f"t={t},v1={sig}", body))
107
+ self.assertFalse(verify_signature("whsec", f"t={t},v1={sig}", body + " "))
108
+ self.assertFalse(verify_signature("whsec", f"t={t - 1000},v1={sig}", body))
109
+ self.assertFalse(verify_signature("other", f"t={t},v1={sig}", body))
110
+
111
+
112
+ if __name__ == "__main__":
113
+ unittest.main()