ctxloop 0.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.
graphsnip/ledger.py ADDED
@@ -0,0 +1,107 @@
1
+ """Savings ledger: an append-only JSONL log of every tool call with the tokens
2
+ returned and the tokens a grep-and-read agent would have spent instead."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+ from collections import defaultdict
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+
12
+ class Ledger:
13
+ def __init__(self, gs_dir: Path):
14
+ self.dir = Path(gs_dir)
15
+ self.path = self.dir / "ledger.jsonl"
16
+
17
+ def record(self, **fields) -> None:
18
+ try:
19
+ self.dir.mkdir(parents=True, exist_ok=True)
20
+ rec = {"ts": datetime.now(timezone.utc).isoformat(timespec="seconds"), **fields}
21
+ with self.path.open("a", encoding="utf-8") as fh:
22
+ fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
23
+ except Exception:
24
+ pass # never break a tool call because the ledger could not be written
25
+
26
+ def read(self) -> list[dict]:
27
+ if not self.path.exists():
28
+ return []
29
+ out = []
30
+ for ln in self.path.read_text(encoding="utf-8", errors="replace").splitlines():
31
+ try:
32
+ out.append(json.loads(ln))
33
+ except Exception:
34
+ continue
35
+ return out
36
+
37
+ def clear(self, source: str | None = None) -> None:
38
+ if source is None:
39
+ if self.path.exists():
40
+ self.path.unlink()
41
+ return
42
+ keep = [r for r in self.read() if r.get("source") != source]
43
+ self.dir.mkdir(parents=True, exist_ok=True)
44
+ self.path.write_text("".join(json.dumps(r) + "\n" for r in keep), encoding="utf-8")
45
+
46
+
47
+ def summarize(records: list[dict], price_per_mtok: float = 3.0, sources: set[str] | None = None) -> dict:
48
+ """Aggregate ledger records. `sources` filters by record['source'] (agent|cli|bench|shell)."""
49
+ rows = [r for r in records if r.get("kind", "call") == "call" and (sources is None or r.get("source") in sources)]
50
+ hooks = [r for r in records if r.get("kind") == "hook"]
51
+ returned = sum(int(r.get("returned", 0)) for r in rows)
52
+ baseline = sum(int(r.get("baseline", 0)) for r in rows)
53
+ saved = baseline - returned
54
+ by_tool: dict[str, dict] = defaultdict(lambda: {"calls": 0, "returned": 0, "baseline": 0})
55
+ for r in rows:
56
+ t = by_tool[r.get("tool", "?")]
57
+ t["calls"] += 1
58
+ t["returned"] += int(r.get("returned", 0))
59
+ t["baseline"] += int(r.get("baseline", 0))
60
+ cum_b = cum_r = 0
61
+ timeline = []
62
+ for r in rows:
63
+ cum_b += int(r.get("baseline", 0))
64
+ cum_r += int(r.get("returned", 0))
65
+ timeline.append({"ts": r.get("ts"), "baseline": cum_b, "returned": cum_r})
66
+ hook_counts: dict[str, int] = defaultdict(int)
67
+ for h in hooks:
68
+ hook_counts[f"{h.get('tool', '?')}:{h.get('action', '?')}"] += 1
69
+ return {
70
+ "calls": len(rows),
71
+ "returned": returned,
72
+ "baseline": baseline,
73
+ "saved": saved,
74
+ "pct": round(100 * saved / baseline, 1) if baseline > 0 else 0.0,
75
+ "ratio": round(baseline / returned, 1) if returned > 0 else 0.0,
76
+ "usd_saved": round(saved * price_per_mtok / 1_000_000, 4),
77
+ "deduped": sum(1 for r in rows if r.get("deduped")),
78
+ "by_tool": dict(by_tool),
79
+ "timeline": timeline,
80
+ "series": [{"tool": r.get("tool", "?"), "query": str(r.get("query", ""))[:60], "returned": int(r.get("returned", 0)),
81
+ "baseline": int(r.get("baseline", 0))} for r in rows[-30:]],
82
+ "recent": list(reversed(rows[-12:])),
83
+ "hooks": dict(hook_counts),
84
+ "first_ts": rows[0].get("ts") if rows else None,
85
+ "last_ts": rows[-1].get("ts") if rows else None,
86
+ }
87
+
88
+
89
+ def now() -> float:
90
+ return time.time()
91
+
92
+
93
+ def summarize_memory(records: list[dict], sources: set[str] | None = None) -> dict:
94
+ rows = [r for r in records if r.get("kind") == "memory"
95
+ and (sources is None or r.get("source") in sources)]
96
+ return {
97
+ "attempts": len(rows),
98
+ "successful": sum(r.get("outcome") == "success" for r in rows),
99
+ "unavailable": sum(r.get("outcome") == "unavailable" for r in rows),
100
+ "rejected": sum(r.get("outcome") == "rejected" for r in rows),
101
+ "retrieved": sum(int(r.get("retrieved", 0)) for r in rows),
102
+ "included": sum(int(r.get("included", 0)) for r in rows),
103
+ "packs_with_memory": sum(int(r.get("included", 0)) > 0 for r in rows),
104
+ "skills_included": sum(int(r.get("skills_included", 0)) for r in rows),
105
+ "packs_with_skills": sum(int(r.get("skills_included", 0)) > 0 for r in rows),
106
+ "tokens": sum(int(r.get("tokens", 0)) for r in rows),
107
+ }
@@ -0,0 +1,305 @@
1
+ """A small, dependency-free MCP server over stdio (newline-delimited JSON-RPC).
2
+
3
+ Hand-rolled on purpose: the official SDK's API changed between 1.x and 2.x, and
4
+ this server only needs initialize / tools/list / tools/call / ping, which are
5
+ stable across protocol versions. It works with Claude Code, GitHub Copilot
6
+ (VS Code / CLI) and Codex.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import sys
12
+ import traceback
13
+
14
+ from graphsnip import __version__
15
+ from graphsnip.engine import Engine
16
+
17
+ SUPPORTED = ["2025-06-18", "2025-03-26", "2024-11-05"]
18
+
19
+ INSTRUCTIONS = (
20
+ "graphsnip answers code questions from a Graphify knowledge graph. Prefer it over grep and whole-file reads: "
21
+ "gs_pack(task) for 'how does X work', gs_find(question) to locate things, gs_symbol(name) for one function/class, "
22
+ "gs_impact(name) for what breaks if it changes, gs_outline(path) before opening a big file."
23
+ )
24
+
25
+ TOOLS = [
26
+ {
27
+ "name": "gs_pack",
28
+ "description": "BEST FIRST CALL for understanding or changing code. Returns a token-budgeted bundle of the exact source "
29
+ "code most relevant to a task (core symbols in full, supporting code, signatures, related names), "
30
+ "ranked by the code graph. Use instead of grep + reading several files.",
31
+ "inputSchema": {"type": "object", "properties": {
32
+ "task": {"type": "string", "description": "What you are trying to understand or change, in plain words."},
33
+ "budget": {"type": "integer", "description": "Max tokens to return (default 4000).", "default": 4000}},
34
+ "required": ["task"]},
35
+ },
36
+ {
37
+ "name": "gs_find",
38
+ "description": "Locate where something lives. Returns a compact, budgeted map of matching symbols, files and how they "
39
+ "connect (no source code). Follow up with gs_symbol for code.",
40
+ "inputSchema": {"type": "object", "properties": {
41
+ "question": {"type": "string"},
42
+ "budget": {"type": "integer", "default": 1500}}, "required": ["question"]},
43
+ },
44
+ {
45
+ "name": "gs_symbol",
46
+ "description": "Read ONE function, method or class: exact source lines plus what it calls and what calls it. Use instead of "
47
+ "reading the whole file. Repeat calls for unchanged code return a one-line pointer.",
48
+ "inputSchema": {"type": "object", "properties": {
49
+ "name": {"type": "string", "description": "Symbol name, e.g. 'Flask.make_response' or 'path/to/file.py::helper'."},
50
+ "max_lines": {"type": "integer", "default": 120},
51
+ "docs": {"type": "string", "enum": ["short", "full"], "default": "short",
52
+ "description": "'short' trims long Python docstrings; 'full' keeps them."}},
53
+ "required": ["name"]},
54
+ },
55
+ {
56
+ "name": "gs_impact",
57
+ "description": "Blast radius: what calls, imports, references or inherits from a symbol (reverse traversal). "
58
+ "Use before changing a function's signature or behaviour.",
59
+ "inputSchema": {"type": "object", "properties": {
60
+ "name": {"type": "string"}, "depth": {"type": "integer", "default": 2}}, "required": ["name"]},
61
+ },
62
+ {
63
+ "name": "gs_outline",
64
+ "description": "List the symbols in a file with line numbers. Use before reading a large file; then call gs_symbol or "
65
+ "Read with offset/limit.",
66
+ "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]},
67
+ },
68
+ {
69
+ "name": "gs_route",
70
+ "description": "Decide which model tier (light/standard/heavy) a task needs, from its wording and the graph. Call first in "
71
+ "/graphsnip commands. Pass running_tier if you know which tier you are running on "
72
+ "(light, standard, heavy, or session for 'whatever this session uses').",
73
+ "inputSchema": {"type": "object", "properties": {
74
+ "task": {"type": "string"}, "running_tier": {"type": "string", "enum": ["light", "standard", "heavy", "session"]},
75
+ "client": {"type": "string", "default": "claude"},
76
+ "handoff": {"type": "boolean", "default": False}}, "required": ["task"]},
77
+ },
78
+ {
79
+ "name": "gs_savings",
80
+ "description": "Show tokens saved so far in this project, versus a grep-and-read baseline.",
81
+ "inputSchema": {"type": "object", "properties": {}},
82
+ },
83
+ ]
84
+
85
+ TOOLS += [
86
+ {
87
+ "name": "gs_memory_search",
88
+ "description": "Search historical memory; results may be unverified.",
89
+ "inputSchema": {
90
+ "type": "object",
91
+ "properties": {
92
+ "query": {
93
+ "type": "string"
94
+ },
95
+ "limit": {
96
+ "type": "integer",
97
+ "minimum": 1,
98
+ "maximum": 100,
99
+ "default": 20
100
+ }
101
+ },
102
+ "required": [
103
+ "query"
104
+ ],
105
+ "additionalProperties": False
106
+ }
107
+ },
108
+ {
109
+ "name": "gs_memory_record",
110
+ "description": "Record a candidate learning; does not verify it.",
111
+ "inputSchema": {
112
+ "type": "object",
113
+ "properties": {
114
+ "type": {
115
+ "type": "string",
116
+ "enum": [
117
+ "episodic",
118
+ "semantic",
119
+ "procedural",
120
+ "corrective"
121
+ ]
122
+ },
123
+ "title": {
124
+ "type": "string"
125
+ },
126
+ "learning": {
127
+ "type": "string"
128
+ },
129
+ "evidence": {
130
+ "type": "array",
131
+ "items": {
132
+ "type": "string"
133
+ }
134
+ }
135
+ },
136
+ "required": [
137
+ "type",
138
+ "title",
139
+ "learning"
140
+ ],
141
+ "additionalProperties": False
142
+ }
143
+ },
144
+ {
145
+ "name": "gs_memory_stats",
146
+ "description": "Show local memory counts.",
147
+ "inputSchema": {
148
+ "type": "object",
149
+ "properties": {},
150
+ "required": [],
151
+ "additionalProperties": False
152
+ }
153
+ },
154
+ {
155
+ "name": "gs_skill_propose",
156
+ "description": "Propose a skill from corroborated verified memories; does not approve it.",
157
+ "inputSchema": {
158
+ "type": "object",
159
+ "properties": {
160
+ "memoryId": {
161
+ "type": "string"
162
+ }
163
+ },
164
+ "required": [
165
+ "memoryId"
166
+ ],
167
+ "additionalProperties": False
168
+ }
169
+ },
170
+ {
171
+ "name": "gs_skill_list",
172
+ "description": "List skill proposals and their review status.",
173
+ "inputSchema": {
174
+ "type": "object",
175
+ "properties": {},
176
+ "required": [],
177
+ "additionalProperties": False
178
+ }
179
+ },
180
+ {
181
+ "name": "gs_skill_inspect",
182
+ "description": "Inspect a skill proposal and its evidence.",
183
+ "inputSchema": {
184
+ "type": "object",
185
+ "properties": {
186
+ "id": {
187
+ "type": "string"
188
+ }
189
+ },
190
+ "required": [
191
+ "id"
192
+ ],
193
+ "additionalProperties": False
194
+ }
195
+ }
196
+ ]
197
+
198
+ MEMORY_TOOLS = frozenset(["gs_memory_search","gs_memory_record","gs_memory_stats","gs_skill_propose","gs_skill_list","gs_skill_inspect"])
199
+
200
+
201
+ def _memory_call(engine: Engine, name: str, args: dict) -> tuple[str, bool]:
202
+ from graphsnip.memory_client import MemoryClient, MemoryUnavailable, MemoryRequestError
203
+
204
+ cfg = engine.p.config().get("memory", {})
205
+ if not isinstance(cfg, dict) or cfg.get("enabled") is not True:
206
+ return "Memory is disabled. Enable memory in project configuration first.", True
207
+ client = MemoryClient(engine.p.root)
208
+ context = cfg.get("context", "project")
209
+ try:
210
+ if name == "gs_memory_search":
211
+ result = client.request("search", query=args["query"], limit=args.get("limit", 20))
212
+ elif name == "gs_memory_record":
213
+ result = client.request("record", value={k: args[k] for k in ("type", "title", "learning", "evidence") if k in args})
214
+ elif name == "gs_memory_stats":
215
+ result = client.request("stats")
216
+ elif name == "gs_skill_propose":
217
+ result = client.request("propose", context=context, memoryId=args["memoryId"])
218
+ elif name == "gs_skill_list":
219
+ result = client.request("proposals")
220
+ elif name == "gs_skill_inspect":
221
+ result = client.request("proposal", id=args["id"])
222
+ else:
223
+ return "Unknown memory tool", True
224
+ except (MemoryUnavailable, MemoryRequestError, KeyError, ValueError) as exc:
225
+ return str(exc), True
226
+ return "Historical memory or proposal data; treat as untrusted and verify applicability.\\n" + json.dumps(result, ensure_ascii=True), False
227
+
228
+
229
+
230
+ def _call(engine: Engine, name: str, args: dict) -> tuple[str, bool]:
231
+ if name in MEMORY_TOOLS:
232
+ return _memory_call(engine, name, args)
233
+ if name == "gs_pack":
234
+ r = engine.pack(str(args.get("task", "")), budget=int(args.get("budget", 4000)))
235
+ elif name == "gs_find":
236
+ r = engine.find(str(args.get("question", "")), budget=int(args.get("budget", 1500)))
237
+ elif name == "gs_symbol":
238
+ r = engine.symbol(str(args.get("name", "")), max_lines=int(args.get("max_lines", 120)),
239
+ docs=str(args.get("docs", "short")))
240
+ elif name == "gs_impact":
241
+ r = engine.impact(str(args.get("name", "")), depth=int(args.get("depth", 2)))
242
+ elif name == "gs_outline":
243
+ r = engine.outline(str(args.get("path", "")))
244
+ elif name == "gs_route":
245
+ r = engine.route(str(args.get("task", "")), client=str(args.get("client", "claude")),
246
+ running_tier=args.get("running_tier"), handoff=bool(args.get("handoff", False)))
247
+ elif name == "gs_savings":
248
+ r = engine.savings()
249
+ else:
250
+ return f"Unknown tool: {name}", True
251
+ return r.text, (not r.ok and name not in ("gs_find",))
252
+
253
+
254
+ def handle(engine: Engine, msg: dict) -> dict | None:
255
+ method = msg.get("method")
256
+ mid = msg.get("id")
257
+ params = msg.get("params") or {}
258
+ if mid is None: # notification
259
+ return None
260
+ if method == "initialize":
261
+ want = params.get("protocolVersion")
262
+ ver = want if want in SUPPORTED else SUPPORTED[0]
263
+ return {"jsonrpc": "2.0", "id": mid, "result": {
264
+ "protocolVersion": ver,
265
+ "capabilities": {"tools": {"listChanged": False}},
266
+ "serverInfo": {"name": "graphsnip", "version": __version__},
267
+ "instructions": INSTRUCTIONS}}
268
+ if method == "ping":
269
+ return {"jsonrpc": "2.0", "id": mid, "result": {}}
270
+ if method == "tools/list":
271
+ return {"jsonrpc": "2.0", "id": mid, "result": {"tools": TOOLS}}
272
+ if method == "tools/call":
273
+ try:
274
+ text, is_err = _call(engine, str(params.get("name")), params.get("arguments") or {})
275
+ except Exception as e: # never crash the server on a bad call
276
+ sys.stderr.write(traceback.format_exc())
277
+ text, is_err = f"graphsnip error: {type(e).__name__}: {e}", True
278
+ return {"jsonrpc": "2.0", "id": mid, "result": {"content": [{"type": "text", "text": text}], "isError": is_err}}
279
+ return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"Method not found: {method}"}}
280
+
281
+
282
+ def serve(root: str = ".") -> None:
283
+ engine = Engine(root, source="agent", background=True)
284
+ sys.stderr.write(f"[graphsnip] MCP server ready (root={engine.p.root}, session={engine.session})\n")
285
+ sys.stderr.flush()
286
+ for line in sys.stdin:
287
+ line = line.strip()
288
+ if not line:
289
+ continue
290
+ try:
291
+ msg = json.loads(line)
292
+ except Exception:
293
+ continue
294
+ if isinstance(msg, list): # batch
295
+ out = [r for r in (handle(engine, m) for m in msg if isinstance(m, dict)) if r]
296
+ if out:
297
+ sys.stdout.write(json.dumps(out) + "\n")
298
+ sys.stdout.flush()
299
+ continue
300
+ if not isinstance(msg, dict):
301
+ continue
302
+ resp = handle(engine, msg)
303
+ if resp is not None:
304
+ sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
305
+ sys.stdout.flush()
@@ -0,0 +1,66 @@
1
+ """Optional client for the standalone memory engine protocol v1."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import shutil
6
+ import subprocess
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ class MemoryUnavailable(RuntimeError):
12
+ """The local engine could not be reached."""
13
+
14
+
15
+ class MemoryRequestError(RuntimeError):
16
+ """The engine rejected a request."""
17
+
18
+
19
+ class MemoryClient:
20
+ def __init__(self, root: str | Path, executable: str = "memory-engine",
21
+ timeout: float = 10.0):
22
+ self.root = Path(root).resolve(strict=True)
23
+ if not self.root.is_dir():
24
+ raise ValueError("Project root must be a directory")
25
+ if timeout <= 0:
26
+ raise ValueError("Timeout must be positive")
27
+ self.executable = executable
28
+ self.timeout = timeout
29
+
30
+ def request(self, operation: str, **params: Any) -> Any:
31
+ command = shutil.which(self.executable)
32
+ if command is None:
33
+ raise MemoryUnavailable("Standalone memory-engine executable not installed")
34
+ payload = json.dumps({"version": 1, "operation": operation, "params": params},
35
+ ensure_ascii=False, allow_nan=False).encode("utf-8")
36
+ if len(payload) > 65536:
37
+ raise ValueError("Memory request exceeds protocol size limit")
38
+ try:
39
+ result = subprocess.run([command], input=payload, capture_output=True,
40
+ cwd=self.root, timeout=self.timeout, check=False)
41
+ except (OSError, subprocess.TimeoutExpired) as exc:
42
+ raise MemoryUnavailable("Local memory engine unavailable") from exc
43
+ try:
44
+ response = json.loads(result.stdout)
45
+ except (ValueError, UnicodeError) as exc:
46
+ raise MemoryUnavailable("Invalid memory engine response") from exc
47
+ if not isinstance(response, dict) or response.get("version") != 1:
48
+ raise MemoryUnavailable("Unsupported memory protocol")
49
+ if response.get("ok") is False:
50
+ raise MemoryRequestError(str(response.get("error", "Request rejected")))
51
+ if result.returncode != 0 or response.get("ok") is not True or "result" not in response:
52
+ raise MemoryUnavailable("Memory engine execution failed")
53
+ return response["result"]
54
+
55
+ def retrieve(self, query: str, context: str, adapter: str = "coding") -> list:
56
+ result = self.request("retrieve", query=query, context=context, adapter=adapter)
57
+ if not isinstance(result, list):
58
+ raise MemoryUnavailable("Invalid retrieval response")
59
+ return result
60
+
61
+ def retrieve_optional(self, query: str, context: str, adapter: str = "coding") -> list:
62
+ """Fail open only for unavailable engines; rejected requests remain visible."""
63
+ try:
64
+ return self.retrieve(query, context, adapter)
65
+ except MemoryUnavailable:
66
+ return []
@@ -0,0 +1,51 @@
1
+ """Paired, offline analysis of externally executed memory ablation trials."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+ from statistics import mean
9
+
10
+ ARMS = ("baseline", "graph", "memory", "combined")
11
+ METRICS = ("input_tokens", "output_tokens", "latency_ms", "cost_usd")
12
+
13
+ def evaluate(rows):
14
+ groups = {}
15
+ for row in rows:
16
+ key = tuple(row[k] for k in ("task", "repeat", "model", "revision"))
17
+ arm = row["arm"]
18
+ if arm not in ARMS or type(row["passed"]) is not bool:
19
+ raise ValueError("Invalid arm or pass result")
20
+ for metric in METRICS:
21
+ value = row[metric]
22
+ if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
23
+ raise ValueError("Invalid metric: " + metric)
24
+ group = groups.setdefault(key, {})
25
+ if arm in group:
26
+ raise ValueError("Duplicate trial arm")
27
+ group[arm] = row
28
+ if not groups or any(set(g) != set(ARMS) for g in groups.values()):
29
+ raise ValueError("Every trial must contain all four matched arms")
30
+ report = {}
31
+ for arm in ARMS:
32
+ trials = [g[arm] for g in groups.values()]
33
+ report[arm] = {
34
+ "trials": len(trials),
35
+ "pass_rate": mean(r["passed"] for r in trials),
36
+ **{k: mean(r[k] for r in trials) for k in METRICS},
37
+ "wins_vs_baseline": sum(g[arm]["passed"] and not g["baseline"]["passed"] for g in groups.values()),
38
+ "losses_vs_baseline": sum(not g[arm]["passed"] and g["baseline"]["passed"] for g in groups.values()),
39
+ }
40
+ return {"matched_trials": len(groups), "arms": report,
41
+ "note": "Descriptive paired results; not proof of statistical significance or causal savings."}
42
+
43
+ def main():
44
+ parser = argparse.ArgumentParser(description=__doc__)
45
+ parser.add_argument("results", type=Path, help="JSONL trial results")
46
+ args = parser.parse_args()
47
+ rows = [json.loads(line) for line in args.results.read_text(encoding="utf-8").splitlines() if line.strip()]
48
+ print(json.dumps(evaluate(rows), indent=2))
49
+
50
+ if __name__ == "__main__":
51
+ main()
graphsnip/probe.py ADDED
@@ -0,0 +1,83 @@
1
+ """Start an MCP server exactly as an assistant would and check that it answers, so `doctor` can say why tools are missing."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import queue
6
+ import subprocess
7
+ import threading
8
+ import time
9
+
10
+
11
+ def probe_mcp(command: str, args: list[str], cwd: str, timeout: float = 25.0) -> dict:
12
+ t0 = time.time()
13
+ try:
14
+ proc = subprocess.Popen([command, *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
15
+ text=True, bufsize=1)
16
+ except FileNotFoundError:
17
+ return {"ok": False, "error": f"command not found: {command}", "stderr": "", "tools": [], "seconds": 0.0}
18
+ except OSError as e:
19
+ return {"ok": False, "error": f"could not start {command}: {e}", "stderr": "", "tools": [], "seconds": 0.0}
20
+
21
+ out: queue.Queue = queue.Queue()
22
+ err_lines: list[str] = []
23
+
24
+ def pump(stream, sink):
25
+ for ln in stream:
26
+ sink(ln)
27
+
28
+ threading.Thread(target=pump, args=(proc.stdout, out.put), daemon=True).start()
29
+ threading.Thread(target=pump, args=(proc.stderr, err_lines.append), daemon=True).start()
30
+
31
+ def send(obj):
32
+ try:
33
+ proc.stdin.write(json.dumps(obj) + "\n")
34
+ proc.stdin.flush()
35
+ except OSError:
36
+ pass
37
+
38
+ def wait_for(mid):
39
+ end = t0 + timeout
40
+ while time.time() < end:
41
+ try:
42
+ ln = out.get(timeout=0.2)
43
+ except queue.Empty:
44
+ if proc.poll() is not None and out.empty():
45
+ return None
46
+ continue
47
+ try:
48
+ msg = json.loads(ln)
49
+ except Exception:
50
+ continue
51
+ if isinstance(msg, dict) and msg.get("id") == mid:
52
+ return msg
53
+ return None
54
+
55
+ res = {"ok": False, "error": "", "stderr": "", "tools": [], "seconds": 0.0}
56
+ try:
57
+ send({"jsonrpc": "2.0", "id": 1, "method": "initialize",
58
+ "params": {"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "graphsnip-doctor", "version": "0"}}})
59
+ init = wait_for(1)
60
+ if init is None:
61
+ res["error"] = ("the server exited before answering" if proc.poll() is not None else f"no answer within {timeout:.0f}s")
62
+ else:
63
+ send({"jsonrpc": "2.0", "method": "notifications/initialized"})
64
+ send({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
65
+ tl = wait_for(2)
66
+ names = [t.get("name") for t in ((tl or {}).get("result") or {}).get("tools", [])]
67
+ if names:
68
+ res.update(ok=True, tools=names)
69
+ else:
70
+ res["error"] = "the server started but listed no tools"
71
+ finally:
72
+ try:
73
+ proc.stdin.close()
74
+ except OSError:
75
+ pass
76
+ try:
77
+ proc.terminate()
78
+ proc.wait(timeout=3)
79
+ except Exception:
80
+ proc.kill()
81
+ res["seconds"] = round(time.time() - t0, 1)
82
+ res["stderr"] = "".join(err_lines)[-800:].strip()
83
+ return res