agent-certify 0.5.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.
@@ -0,0 +1,603 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """agent-certify as an MCP server: an agent can scan its own topology.
5
+
6
+ Model Context Protocol over stdio: newline-delimited JSON-RPC 2.0 on
7
+ stdin/stdout, no third-party MCP package. Implements ``initialize``,
8
+ ``notifications/initialized`` (and any other notification: no reply),
9
+ ``ping``, ``tools/list`` and ``tools/call``.
10
+
11
+ Errors never stop the server. Protocol problems (bad JSON, unknown method,
12
+ unknown tool) are JSON-RPC errors; a tool that fails (missing session, no
13
+ baseline, unknown node...) returns a normal result with ``isError: true`` and a
14
+ message the calling agent can act on, as the MCP specification asks.
15
+
16
+ Untrusted input
17
+ ---------------
18
+ Tool arguments come from an AI agent, which may be acting on injected
19
+ instructions. So:
20
+
21
+ * path arguments (``session_path``, ``baseline_path``, ``policy_path``) expand
22
+ ``~`` but **never** environment variables, are resolved (symlinks, ``..``)
23
+ and must lie inside an allowed root: ``~/.claude/projects`` or the server's
24
+ working directory. Anything else is refused with "Path not allowed";
25
+ * no response or error message contains a resolved path, a file's contents or
26
+ an exception's text. Unexpected failures are logged with their traceback on
27
+ stderr and reported to the client as a generic message with a correlation id;
28
+ * each request runs under a time limit (30 s by default).
29
+
30
+ stdout carries protocol messages only: anything else the library would print
31
+ goes to stderr while the server runs.
32
+
33
+ Register with Claude Code::
34
+
35
+ claude mcp add agent-certify -- agent-certify mcp
36
+
37
+ Current session detection (when a tool's ``session_path`` is omitted):
38
+
39
+ 1. ``CLAUDE_CODE_SESSION_ID`` (set by Claude Code for its child processes),
40
+ or ``CLAUDE_SESSION_ID``: ``~/.claude/projects/*/<id>.jsonl``
41
+ 2. the newest session of the project in the working directory
42
+ (``~/.claude/projects/<cwd with separators as dashes>/``)
43
+
44
+ There is no machine-wide fallback: sessions of other projects are never read
45
+ unless the caller names them (and they lie under ``~/.claude/projects``).
46
+ """
47
+ from __future__ import annotations
48
+
49
+ import json
50
+ import logging
51
+ import os
52
+ import re
53
+ import sys
54
+ import threading
55
+ import uuid
56
+ from collections.abc import Callable
57
+ from pathlib import Path
58
+ from typing import Any, BinaryIO
59
+
60
+ from agent_certify.anomaly import AnomalyDetector
61
+ from agent_certify.baseline import DEFAULT_BASELINE_PATH, load_baseline
62
+ from agent_certify.blast import BlastRadiusAnalyzer
63
+ from agent_certify.graph import AgentGraph
64
+ from agent_certify.parser.auto import AutoParser
65
+ from agent_certify.parser.mcp_logs import project_key
66
+ from agent_certify.paths import PathNotAllowed, confine
67
+ from agent_certify.policy import DEFAULT_POLICY_PATH, Policy
68
+ from agent_certify.scanner import HIGH, AgentFIScanner, Perspective, ScanResult
69
+ from agent_certify.watcher import latest_session
70
+
71
+ logger = logging.getLogger(__name__)
72
+
73
+ PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")
74
+ SESSION_ENV_VARS = ("CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID")
75
+ PERSPECTIVES = list(Perspective.NAMES) # engineering, risk, compliance, monitoring, classic
76
+ DEFAULT_REQUEST_TIMEOUT = 30.0
77
+ _SESSION_ID = re.compile(r"[A-Za-z0-9_-]{1,128}")
78
+
79
+ PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNAL_ERROR = -32700, -32600, -32601, -32602, -32603
80
+
81
+ _SESSION = {"type": "string",
82
+ "description": "Session transcript (.jsonl), Cursor .agent-trace, or a project folder (newest session), "
83
+ "inside ~/.claude/projects or the working directory. Omit to use the current session."}
84
+
85
+ TOOLS = [
86
+ {
87
+ "name": "scan_topology",
88
+ "description": "Scan the structural topology of the current agent session. Returns the Fragility Index, "
89
+ "node count, edge count, bridges, and node classifications.",
90
+ "inputSchema": {"type": "object", "properties": {
91
+ "session_path": _SESSION,
92
+ "perspective": {"type": "string", "enum": PERSPECTIVES, "default": "engineering",
93
+ "description": "Vocabulary for node roles."},
94
+ }, "additionalProperties": False},
95
+ },
96
+ {
97
+ "name": "check_anomalies",
98
+ "description": "Compare the current session against the learned baseline. Returns any structural "
99
+ "anomalies detected.",
100
+ "inputSchema": {"type": "object", "properties": {
101
+ "session_path": _SESSION,
102
+ "baseline_path": {"type": "string",
103
+ "description": f"Baseline JSON (default {DEFAULT_BASELINE_PATH.as_posix()})."},
104
+ }, "additionalProperties": False},
105
+ },
106
+ {
107
+ "name": "blast_radius",
108
+ "description": "Analyze what happens if a specific node is compromised or removed. Returns the blast "
109
+ "radius, affected nodes, and whether the system fragments.",
110
+ "inputSchema": {"type": "object", "properties": {
111
+ "session_path": _SESSION,
112
+ "node": {"type": "string", "description": "Node id or name, e.g. 'claude', 'bash', 'tool:Bash'."},
113
+ }, "required": ["node"], "additionalProperties": False},
114
+ },
115
+ {
116
+ "name": "check_policy",
117
+ "description": "Check the current session against the policy rules. Returns any violations.",
118
+ "inputSchema": {"type": "object", "properties": {
119
+ "session_path": _SESSION,
120
+ "policy_path": {"type": "string",
121
+ "description": f"Policy JSON (default {DEFAULT_POLICY_PATH.as_posix()})."},
122
+ }, "additionalProperties": False},
123
+ },
124
+ {
125
+ "name": "topology_summary",
126
+ "description": "Get a brief natural-language summary of the current agent system's structural health. "
127
+ "Designed to be read by an AI agent about itself.",
128
+ "inputSchema": {"type": "object", "properties": {"session_path": _SESSION}, "additionalProperties": False},
129
+ },
130
+ ]
131
+
132
+
133
+ class ToolError(Exception):
134
+ """A tool could not run; reported to the caller as an ``isError`` result."""
135
+
136
+
137
+ # --------------------------------------------------------------- sessions
138
+ def find_current_session(projects_root: Path | None = None, cwd: str | None = None,
139
+ env: dict | None = None) -> tuple[Path, str]:
140
+ """(session file, how it was found) for the current session. Raises ToolError when there is none.
141
+
142
+ Only the session named by ``CLAUDE_CODE_SESSION_ID`` / ``CLAUDE_SESSION_ID``
143
+ or the newest session of the working directory's project qualify.
144
+ """
145
+ root = projects_root or Path.home() / ".claude" / "projects"
146
+ env = os.environ if env is None else env
147
+ if not root.is_dir():
148
+ raise ToolError("No Claude Code projects folder found; pass session_path explicitly.")
149
+ for var in SESSION_ENV_VARS:
150
+ sid = env.get(var)
151
+ if sid and _SESSION_ID.fullmatch(sid):
152
+ hits = sorted(root.glob(f"*/{sid}.jsonl"))
153
+ if hits:
154
+ return hits[0], f"{var}={sid}"
155
+ here = cwd if cwd is not None else os.getcwd()
156
+ project = root / project_key(here)
157
+ newest = latest_session(project) if project.is_dir() else None
158
+ if newest:
159
+ return newest, f"newest session of project {project.name}"
160
+ raise ToolError("No session found in the current project; pass session_path explicitly.")
161
+
162
+
163
+ # ------------------------------------------------------------ summaries
164
+ def _pieces(n: int, all_single: bool) -> str:
165
+ return f"{n} isolated pieces" if all_single else f"{n} pieces"
166
+
167
+
168
+ def _plural(n: int, word: str) -> str:
169
+ return f"{n} {word}{'' if n == 1 else 's'}"
170
+
171
+
172
+ def _readable(graph: AgentGraph, node_ids: list[str]) -> str:
173
+ """Tools by name, sub-agents by type ("2 general-purpose sub-agents"), others by id."""
174
+ names, agent_types = [], {}
175
+ for nid in node_ids:
176
+ node = graph.nodes[nid]
177
+ if node.kind == "agent":
178
+ t = graph.role(nid).split(":", 1)[1]
179
+ agent_types[t] = agent_types.get(t, 0) + 1
180
+ else:
181
+ names.append(node.name if node.kind in ("tool", "file") else nid)
182
+ names += [f"the {t} sub-agent" if c == 1 else f"{c} {t} sub-agents" for t, c in agent_types.items()]
183
+ return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]
184
+
185
+
186
+ def describe(graph: AgentGraph, result: ScanResult, anomalies=None, violations=None,
187
+ baseline_note: str = "", policy_note: str = "", checks: bool = True,
188
+ subject: str = "Your current session") -> str:
189
+ """A plain-language account of the topology, addressed to the agent itself.
190
+
191
+ ``checks=False`` leaves out the baseline and policy sentences (structure
192
+ only). ``subject`` opens the text ("This session" for one the caller named).
193
+ """
194
+ kinds = {k: [n for n in graph.nodes.values() if n.kind == k] for k in ("orchestrator", "agent", "tool", "file")}
195
+ parts = []
196
+ if kinds["orchestrator"]:
197
+ parts.append(f"{len(kinds['orchestrator'])} orchestrator")
198
+ for k, word in (("agent", "sub-agent"), ("tool", "tool"), ("file", "file")):
199
+ if kinds[k]:
200
+ parts.append(f"{len(kinds[k])} {word}{'s' if len(kinds[k]) != 1 else ''}")
201
+ if "human" in graph.nodes:
202
+ parts.append("the human")
203
+ links = result.edge_count
204
+ out = [(f"{subject} has {result.node_count} nodes ({', '.join(parts)}) and {links} "
205
+ f"link{'s' if links != 1 else ''}.")]
206
+
207
+ fragile = len(result.fragile_edges)
208
+ if links == 0:
209
+ out.append("There are no links yet: nothing has been called.")
210
+ elif fragile == links:
211
+ out.append("Fragility Index is 1.0 — every connection is a single point of failure with no backup path.")
212
+ elif fragile == 0:
213
+ out.append("Fragility Index is 0.0 — every connection sits in a triangle, so each has a backup path.")
214
+ else:
215
+ cause = ", which here come from sub-agents sharing tools with the orchestrator" if kinds["agent"] else ""
216
+ out.append(f"Fragility Index is {result.fi:.2f} — {fragile} of {links} links have no backup path; "
217
+ f"the other {links - fragile} sit in triangles{cause}.")
218
+
219
+ if kinds["agent"] and kinds["tool"]:
220
+ orch = {n.id for n in kinds["orchestrator"]}
221
+ agent_ids = {a.id for a in kinds["agent"]}
222
+ shared = sorted(t.name for t in kinds["tool"]
223
+ if graph.neighbors(t.id) & orch and graph.neighbors(t.id) & agent_ids)
224
+ types = sorted({graph.role(a.id).split(":", 1)[1] for a in kinds["agent"]})
225
+ verb = "shares" if len(kinds["agent"]) == 1 else "share"
226
+ out.append(f"{_plural(len(kinds['agent']), 'sub-agent')} ({', '.join(types)}) "
227
+ + (f"{verb} {_plural(len(shared), 'tool')} with the orchestrator "
228
+ f"({', '.join(shared[:5])}{'…' if len(shared) > 5 else ''})."
229
+ if shared else "only use tools the orchestrator does not call itself."))
230
+
231
+ keystones = sorted((n for n, lvl in result.node_levels.items() if lvl == HIGH),
232
+ key=lambda n: (graph.nodes[n].kind != "orchestrator", -graph.nodes[n].call_count, n))
233
+ if keystones:
234
+ first = keystones[0]
235
+ node = graph.nodes[first]
236
+ who = f"The orchestrator ({node.name})" if node.kind == "orchestrator" else _readable(graph, [first])
237
+ b = BlastRadiusAnalyzer(graph).analyze(first)
238
+ single = all(len(c) == 1 for c in b.components_after)
239
+ if b.system_fragmented:
240
+ effect = f"if it fails, the system fragments into {_pieces(len(b.components_after), single)}"
241
+ else:
242
+ effect = f"removing it raises FI from {result.fi:.2f} to {b.remaining_fi:.2f}"
243
+ if len(keystones) == 1:
244
+ out.append(f"{who} is the sole keystone: {effect}.")
245
+ else:
246
+ out.append(f"{who} is the main keystone: {effect}. Other keystones: {_readable(graph, keystones[1:])}.")
247
+ elif links:
248
+ out.append("No single node is a keystone: removing any one leaves the structure largely intact.")
249
+
250
+ tools = kinds["tool"]
251
+ if tools:
252
+ top = max(tools, key=lambda n: n.call_count)
253
+ errs = sum(n.error_count for n in graph.nodes.values())
254
+ line = f"Most-used tool: {top.name} ({top.call_count} calls"
255
+ line += f", {top.error_count} failed)." if top.error_count else ")."
256
+ if errs and graph.total_tool_calls:
257
+ line += f" Overall {errs / graph.total_tool_calls:.1%} of {graph.total_tool_calls} tool calls failed."
258
+ out.append(line)
259
+ if graph.skipped_records:
260
+ out.append(f"{_plural(graph.skipped_records, 'record')} of the session could not be read, so this picture "
261
+ "may be incomplete.")
262
+
263
+ if checks:
264
+ if anomalies is None:
265
+ out.append(baseline_note or "No baseline is loaded, so anomalies can't be judged "
266
+ "(run `agent-certify learn` to create one).")
267
+ elif not anomalies.anomalies:
268
+ out.append(f"No anomalies detected against the baseline of {anomalies.learned_from} sessions.")
269
+ else:
270
+ top = "; ".join(a.message for a in anomalies.anomalies[:3])
271
+ more = f" (and {len(anomalies.anomalies) - 3} more)" if len(anomalies.anomalies) > 3 else ""
272
+ out.append(f"Against the baseline of {anomalies.learned_from} sessions: {anomalies.summary} — {top}{more}.")
273
+ if violations is None:
274
+ out.append(policy_note or "No policy is loaded.")
275
+ elif not violations:
276
+ out.append("No policy violations.")
277
+ else:
278
+ out.append(f"{len(violations)} policy violation{'s' if len(violations) != 1 else ''}: "
279
+ + "; ".join(f"{v.severity.upper()} {v.message}" for v in violations[:3])
280
+ + (" …" if len(violations) > 3 else "") + ".")
281
+
282
+ if links and fragile == links and not kinds["agent"] and not kinds["file"]:
283
+ out.append("This is the usual shape of a single-agent session — one orchestrator calling each tool "
284
+ "directly; redundancy only appears when sub-agents share tools.")
285
+ return " ".join(out)
286
+
287
+
288
+ # ---------------------------------------------------------------- server
289
+ class AgentCertifyMCPServer:
290
+ """MCP server exposing agent-certify tools via stdio JSON-RPC.
291
+
292
+ ``handle(message)`` processes one decoded JSON-RPC message and returns the
293
+ response (``None`` for notifications); ``run()`` is the stdio loop.
294
+ ``projects_root``, ``cwd`` and ``env`` override session auto-detection;
295
+ ``projects_root`` and the process working directory are the roots that
296
+ path arguments are confined to. ``request_timeout`` bounds each tool call.
297
+ """
298
+
299
+ TOOLS = TOOLS
300
+
301
+ def __init__(self, projects_root: str | os.PathLike | None = None, cwd: str | None = None,
302
+ env: dict | None = None, request_timeout: float = DEFAULT_REQUEST_TIMEOUT):
303
+ from agent_certify import __version__
304
+ self.version = __version__
305
+ self.projects_root = Path(projects_root) if projects_root else None
306
+ self.cwd = cwd
307
+ self.env = env
308
+ self.request_timeout = request_timeout
309
+ self.protocol_version = PROTOCOL_VERSIONS[0]
310
+ self._handlers: dict[str, Callable[..., dict]] = {
311
+ "scan_topology": self._scan_topology,
312
+ "check_anomalies": self._check_anomalies,
313
+ "blast_radius": self._blast_radius,
314
+ "check_policy": self._check_policy,
315
+ "topology_summary": self._topology_summary,
316
+ }
317
+
318
+ def allowed_roots(self) -> list[Path]:
319
+ """Directories that path arguments may point into."""
320
+ roots = [self.projects_root or Path.home() / ".claude" / "projects", Path(os.getcwd())]
321
+ if self.cwd and Path(self.cwd).is_dir():
322
+ roots.append(Path(self.cwd))
323
+ return roots
324
+
325
+ # ------------------------------------------------------------ transport
326
+ def run(self, stdin: BinaryIO | None = None, stdout: BinaryIO | None = None) -> None:
327
+ """Read JSON-RPC messages from stdin until EOF; write responses to stdout."""
328
+ inp = stdin or sys.stdin.buffer
329
+ out = stdout or sys.stdout.buffer
330
+ real_stdout, sys.stdout = sys.stdout, sys.stderr # protect the protocol channel
331
+ try:
332
+ for raw in inp:
333
+ line = raw.decode("utf-8", errors="replace").strip()
334
+ if not line:
335
+ continue
336
+ response = self.handle_line(line)
337
+ if response is not None:
338
+ out.write(json.dumps(response, ensure_ascii=False).encode("utf-8") + b"\n")
339
+ out.flush()
340
+ finally:
341
+ sys.stdout = real_stdout
342
+
343
+ def handle_line(self, line: str) -> Any:
344
+ try:
345
+ message = json.loads(line)
346
+ except (json.JSONDecodeError, RecursionError):
347
+ return self._error(None, PARSE_ERROR, "Parse error")
348
+ if isinstance(message, list): # JSON-RPC batch (2025-03-26)
349
+ replies = [r for r in (self.handle(m) for m in message) if r is not None]
350
+ return replies or None
351
+ return self.handle(message)
352
+
353
+ def handle(self, message: Any) -> dict | None:
354
+ if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"),
355
+ str):
356
+ return self._error(message.get("id") if isinstance(message, dict) else None,
357
+ INVALID_REQUEST, "Invalid Request")
358
+ is_notification = "id" not in message
359
+ try:
360
+ response = self._dispatch(message)
361
+ except Exception: # noqa: BLE001 — one bad request must never kill the server
362
+ ref = self._log_failure("dispatch")
363
+ response = self._error(message.get("id"), INTERNAL_ERROR, f"Internal error (ref {ref})")
364
+ return None if is_notification else response
365
+
366
+ def _dispatch(self, request: dict) -> dict | None:
367
+ method = request["method"]
368
+ if method == "initialize":
369
+ return self._handle_initialize(request)
370
+ if method.startswith("notifications/"):
371
+ return None
372
+ if method == "ping":
373
+ return self._result(request, {})
374
+ if method == "tools/list":
375
+ return self._result(request, {"tools": self.TOOLS})
376
+ if method == "tools/call":
377
+ return self._handle_tool_call(request)
378
+ return self._error(request.get("id"), METHOD_NOT_FOUND, "Method not found")
379
+
380
+ def _handle_initialize(self, request: dict) -> dict:
381
+ asked = (request.get("params") or {}).get("protocolVersion")
382
+ self.protocol_version = asked if asked in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0]
383
+ return self._result(request, {
384
+ "protocolVersion": self.protocol_version,
385
+ "capabilities": {"tools": {"listChanged": False}},
386
+ "serverInfo": {"name": "agent-certify", "version": self.version},
387
+ "instructions": "Structural verification of this agent session: call topology_summary for a "
388
+ "plain-language health check, scan_topology for the metrics, blast_radius before "
389
+ "trusting a single node, check_anomalies / check_policy against the project's "
390
+ ".agent-certify/ baseline and policy.",
391
+ })
392
+
393
+ def _handle_tool_call(self, request: dict) -> dict:
394
+ params = request.get("params") or {}
395
+ name = params.get("name")
396
+ arguments = params.get("arguments") or {}
397
+ handler = self._handlers.get(name) if isinstance(name, str) else None
398
+ if handler is None:
399
+ return self._error(request.get("id"), INVALID_PARAMS, "Unknown tool")
400
+ if not isinstance(arguments, dict):
401
+ return self._error(request.get("id"), INVALID_PARAMS, "arguments must be an object")
402
+ schema = next(t["inputSchema"] for t in self.TOOLS if t["name"] == name)
403
+ unknown = set(arguments) - set(schema["properties"])
404
+ missing = set(schema.get("required", [])) - set(arguments)
405
+ try:
406
+ if unknown:
407
+ raise ToolError(f"Unknown argument(s) for {name}: {', '.join(sorted(map(str, unknown)))}")
408
+ if missing:
409
+ raise ToolError(f"Missing required argument(s) for {name}: {', '.join(sorted(missing))}")
410
+ if not all(isinstance(v, str) for v in arguments.values()):
411
+ raise ToolError("Every argument must be a string")
412
+ payload = self._run_with_timeout(handler, arguments)
413
+ except ToolError as exc:
414
+ return self._result(request, {"content": [{"type": "text", "text": str(exc)}], "isError": True})
415
+ except Exception: # noqa: BLE001 — report any tool failure to the caller, keep serving
416
+ ref = self._log_failure(name)
417
+ return self._result(request, {"content": [{"type": "text",
418
+ "text": f"{name} failed (ref {ref}; details in the server log)"}],
419
+ "isError": True})
420
+ result = {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
421
+ if self.protocol_version >= "2025-06-18":
422
+ result["structuredContent"] = payload
423
+ return self._result(request, result)
424
+
425
+ def _run_with_timeout(self, handler: Callable[..., dict], arguments: dict) -> dict:
426
+ """Run a tool in a worker thread; give up after ``request_timeout`` seconds."""
427
+ outcome: dict[str, Any] = {}
428
+
429
+ def target():
430
+ try:
431
+ outcome["value"] = handler(**arguments)
432
+ except BaseException as exc: # noqa: BLE001 — re-raised in the calling thread
433
+ outcome["error"] = exc
434
+
435
+ worker = threading.Thread(target=target, daemon=True)
436
+ worker.start()
437
+ worker.join(self.request_timeout)
438
+ if worker.is_alive():
439
+ # The thread cannot be killed; it is a daemon and its result is discarded.
440
+ raise ToolError(f"Request timed out after {self.request_timeout:g} s")
441
+ if "error" in outcome:
442
+ raise outcome["error"]
443
+ return outcome["value"]
444
+
445
+ @staticmethod
446
+ def _log_failure(where: str) -> str:
447
+ ref = uuid.uuid4().hex[:12]
448
+ logger.exception("agent-certify MCP: %s failed (ref %s)", where, ref)
449
+ return ref
450
+
451
+ @staticmethod
452
+ def _result(request: dict, result: dict) -> dict:
453
+ return {"jsonrpc": "2.0", "id": request.get("id"), "result": result}
454
+
455
+ @staticmethod
456
+ def _error(msg_id, code: int, message: str) -> dict:
457
+ return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}}
458
+
459
+ # ---------------------------------------------------------------- paths
460
+ def _confined(self, raw: str) -> Path:
461
+ try:
462
+ return confine(raw, self.allowed_roots())
463
+ except PathNotAllowed:
464
+ raise ToolError("Path not allowed") from None
465
+
466
+ # ---------------------------------------------------------------- tools
467
+ def _load(self, session_path: str | None) -> tuple[AgentGraph, str, str]:
468
+ """(graph, session label for responses, how it was found). Never exposes a resolved path."""
469
+ if session_path:
470
+ p = self._confined(session_path)
471
+ if not p.exists():
472
+ raise ToolError("Session not found")
473
+ label, how = session_path, "given"
474
+ if p.is_dir() and any(p.glob("*.jsonl")):
475
+ p, how = latest_session(p), "newest session in the given folder"
476
+ else:
477
+ p, how = find_current_session(self.projects_root, self.cwd, self.env)
478
+ label = f"{p.parent.name}/{p.stem}"
479
+ try:
480
+ graph = AutoParser().parse(str(p))
481
+ except (ValueError, OSError, RecursionError, MemoryError):
482
+ raise ToolError("Session could not be read (unsupported or malformed file)") from None
483
+ return graph, label, how
484
+
485
+ def _artifact(self, raw: str | None, default: Path, loader, what: str, hint: str, absent_note: str,
486
+ required: bool):
487
+ """Load a baseline or policy from a confined path; (None, absent_note) when absent and optional."""
488
+ p = self._confined(raw) if raw else default
489
+ if not p.is_file():
490
+ if raw:
491
+ raise ToolError(f"{what.capitalize()} not found")
492
+ if required:
493
+ raise ToolError(f"No {what} at {default.as_posix()}. {hint}")
494
+ return None, absent_note
495
+ try:
496
+ return loader(p), (raw if raw else default.as_posix())
497
+ except (ValueError, KeyError, TypeError, OSError, RecursionError, json.JSONDecodeError):
498
+ raise ToolError(f"Invalid {what} format") from None
499
+
500
+ def _baseline(self, baseline_path: str | None, required: bool):
501
+ where = DEFAULT_BASELINE_PATH.as_posix()
502
+ return self._artifact(baseline_path, DEFAULT_BASELINE_PATH, load_baseline, "baseline",
503
+ "Learn one first: `agent-certify learn ~/.claude/projects/<project>/`.",
504
+ f"No baseline at {where}, so anomalies can't be judged "
505
+ "(run `agent-certify learn` to create one).", required)
506
+
507
+ def _policy(self, policy_path: str | None, required: bool):
508
+ return self._artifact(policy_path, DEFAULT_POLICY_PATH, Policy.load, "policy",
509
+ "Draft one with `agent-certify suggest-policy`.",
510
+ f"No policy at {DEFAULT_POLICY_PATH.as_posix()}.", required)
511
+
512
+ def _scan_topology(self, session_path: str | None = None, perspective: str = "engineering") -> dict:
513
+ if perspective.lower() not in PERSPECTIVES:
514
+ raise ToolError(f"Unknown perspective; choose from {', '.join(PERSPECTIVES)}.")
515
+ graph, label, how = self._load(session_path)
516
+ r = AgentFIScanner(graph, perspective=perspective).scan()
517
+ return {
518
+ "session": label,
519
+ "session_source": how,
520
+ "fi": round(r.fi, 6),
521
+ "node_count": r.node_count,
522
+ "edge_count": r.edge_count,
523
+ "bridge_count": len(r.bridges),
524
+ "components": r.components,
525
+ "articulation_points": r.articulation_points,
526
+ "skipped_records": r.skipped_records,
527
+ "perspective": r.perspective,
528
+ "labels": Perspective.labels(perspective),
529
+ "nodes": [{"id": n.id, "kind": n.kind, "name": n.name, "calls": n.call_count,
530
+ "errors": n.error_count, "classification": r.node_classifications[n.id],
531
+ "level": r.node_levels[n.id]}
532
+ for n in sorted(graph.nodes.values(), key=lambda n: (-n.call_count, n.id))],
533
+ "bridges": [{"source": e.source, "target": e.target} for e in r.bridges],
534
+ "summary": describe(graph, r, checks=False, subject=_subject(how)),
535
+ }
536
+
537
+ def _check_anomalies(self, session_path: str | None = None, baseline_path: str | None = None) -> dict:
538
+ baseline, source = self._baseline(baseline_path, required=True)
539
+ graph, label, _ = self._load(session_path)
540
+ report = AnomalyDetector(baseline, source).detect(graph, AgentFIScanner(graph).scan())
541
+ return {
542
+ "session": label,
543
+ "baseline": source,
544
+ "learned_from": baseline.learned_from,
545
+ "anomaly_count": len(report.anomalies),
546
+ "anomalies": [{k: getattr(a, k) for k in ("severity", "category", "message", "value", "baseline_value",
547
+ "z_score", "detail")} for a in report.anomalies],
548
+ "summary": report.summary,
549
+ }
550
+
551
+ def _blast_radius(self, node: str, session_path: str | None = None) -> dict:
552
+ graph, label, _ = self._load(session_path)
553
+ try:
554
+ b = BlastRadiusAnalyzer(graph).analyze(node)
555
+ except KeyError as exc:
556
+ raise ToolError(str(exc.args[0])) from None # names of this session's own nodes
557
+ return {
558
+ "session": label,
559
+ "compromised": b.compromised,
560
+ "direct_impact": b.direct_impact,
561
+ "total_reachable": b.total_reachable,
562
+ "accessible_tools": b.accessible_tools,
563
+ "baseline_fi": round(b.baseline_fi, 6),
564
+ "remaining_fi": round(b.remaining_fi, 6),
565
+ "system_fragmented": b.system_fragmented,
566
+ "fragment_count": len(b.components_after),
567
+ "recommendation": b.isolation_recommendation,
568
+ }
569
+
570
+ def _check_policy(self, session_path: str | None = None, policy_path: str | None = None) -> dict:
571
+ policy, source = self._policy(policy_path, required=True)
572
+ graph, label, _ = self._load(session_path)
573
+ violations = policy.check(graph)
574
+ return {
575
+ "session": label,
576
+ "policy": source,
577
+ "rule_count": len(policy.rules),
578
+ "violation_count": len(violations),
579
+ "violations": [{"rule_kind": v.rule.kind, "target": v.rule.target, "severity": v.severity,
580
+ "message": v.message, "observed": v.observed} for v in violations],
581
+ "summary": ("No policy violations." if not violations else
582
+ f"{len(violations)} violation(s) of {len(policy.rules)} rule(s): "
583
+ + "; ".join(v.message for v in violations[:3])),
584
+ }
585
+
586
+ def _topology_summary(self, session_path: str | None = None) -> dict:
587
+ graph, label, how = self._load(session_path)
588
+ r = AgentFIScanner(graph, perspective="engineering").scan()
589
+ baseline, b_note = self._baseline(None, required=False)
590
+ policy, p_note = self._policy(None, required=False)
591
+ anomalies = AnomalyDetector(baseline).detect(graph, r) if baseline else None
592
+ violations = policy.check(graph) if policy else None
593
+ return {"session": label, "session_source": how,
594
+ "summary": describe(graph, r, anomalies, violations, baseline_note=b_note, policy_note=p_note,
595
+ subject=_subject(how))}
596
+
597
+
598
+ def _subject(how: str) -> str:
599
+ return "Your current session" if how.startswith(("CLAUDE", "newest session of project")) else "This session"
600
+
601
+
602
+ def main() -> None:
603
+ AgentCertifyMCPServer().run()