piton-cli 0.4.2__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.
piton/iac/lockfile.py ADDED
@@ -0,0 +1,420 @@
1
+ """
2
+ Split-Hash MCP Manifest Pinning Engine (`piton.lock`) & CI Diff Gate.
3
+
4
+ Fills the operational gap left when the MCP signed-manifests proposal closed (Sep 2026)
5
+ and `snyk-agent-scan` dropped hash-based pinning (Aug 2026):
6
+ - `structural_sha256`: Canonical SHA-256 of `{name, inputSchema}` (hard-blocks on drift for all servers).
7
+ - `description_sha256`: Canonical SHA-256 of `description` (hard-blocks on `third_party` servers,
8
+ warns on `internal` servers so benign docstring edits don't break production).
9
+ - Cross-server tool shadowing detection: Flags duplicate tool names exposed by distinct MCP servers.
10
+ - Day-1 poisoning gate: Refuses to pin tools that fail `lint_tool_definition()` unless explicitly forced.
11
+ """
12
+
13
+ from enum import Enum
14
+ import hashlib
15
+ import json
16
+ from typing import Any, Dict, List, Optional, Tuple
17
+ from pydantic import BaseModel, Field
18
+
19
+ from piton.iac.poisoning_lint import LintSeverity, PoisoningFinding, lint_tool_definition
20
+ from piton.iac.schema import (
21
+ ManifestLockfile,
22
+ PinnedServerManifest,
23
+ PinnedToolEntry,
24
+ TrustTier,
25
+ )
26
+
27
+
28
+ class DriftKind(str, Enum):
29
+ STRUCTURAL_DRIFT = "structural_drift"
30
+ DESCRIPTION_DRIFT = "description_drift"
31
+ UNPINNED_TOOL = "unpinned_tool"
32
+ REMOVED_TOOL = "removed_tool"
33
+ CROSS_SERVER_SHADOWING = "cross_server_shadowing"
34
+ DAY1_POISONING = "day1_poisoning"
35
+ PROBE_ERROR = "probe_error"
36
+
37
+
38
+ class DriftAction(str, Enum):
39
+ BLOCK = "block"
40
+ WARN = "warn"
41
+
42
+
43
+ class ManifestDriftItem(BaseModel):
44
+ server_name: str
45
+ tool_name: str
46
+ kind: DriftKind
47
+ action: DriftAction
48
+ message: str
49
+ expected_sha256: Optional[str] = None
50
+ observed_sha256: Optional[str] = None
51
+ previous_preview: Optional[str] = None
52
+ observed_preview: Optional[str] = None
53
+
54
+
55
+ class LockVerificationResult(BaseModel):
56
+ passed: bool
57
+ blocked_count: int = 0
58
+ warning_count: int = 0
59
+ drifts: List[ManifestDriftItem] = Field(default_factory=list)
60
+
61
+
62
+ def _strip_schema_descriptions(obj: Any, in_properties_map: bool = False) -> Any:
63
+ """
64
+ Removes prose `description`/`title` metadata strings from `inputSchema` so `structural_sha256`
65
+ hashes strictly the machine contract (types, required fields, property names, enums, bounds)
66
+ while preserving real tool parameters literally named `title` or `description` inside `properties`.
67
+ """
68
+ if isinstance(obj, dict):
69
+ out: Dict[str, Any] = {}
70
+ for k, v in obj.items():
71
+ if not in_properties_map and k in ("description", "title") and isinstance(v, str):
72
+ continue
73
+ child_is_props = (not in_properties_map) and k in ("properties", "$defs", "definitions", "patternProperties") and isinstance(v, dict)
74
+ out[k] = _strip_schema_descriptions(v, in_properties_map=child_is_props)
75
+ return out
76
+ if isinstance(obj, list):
77
+ return [_strip_schema_descriptions(i, in_properties_map=False) for i in obj]
78
+ return obj
79
+
80
+
81
+ def _collect_prose_surface(tool: Dict[str, Any]) -> Dict[str, Any]:
82
+ """Extracts all human/LLM prose surfaces (tool description + schema property descriptions)."""
83
+ def _extract_prose(obj: Any, in_properties_map: bool = False) -> Any:
84
+ if isinstance(obj, dict):
85
+ out = {}
86
+ for k, v in obj.items():
87
+ if not in_properties_map and k in ("description", "title") and isinstance(v, str):
88
+ out[k] = v.strip()
89
+ elif isinstance(v, (dict, list)):
90
+ child_is_props = (not in_properties_map) and k in ("properties", "$defs", "definitions", "patternProperties") and isinstance(v, dict)
91
+ sub = _extract_prose(v, in_properties_map=child_is_props)
92
+ if sub:
93
+ out[k] = sub
94
+ return out
95
+ if isinstance(obj, list):
96
+ items = [_extract_prose(i, in_properties_map=False) for i in obj]
97
+ return [i for i in items if i]
98
+ return None
99
+
100
+ return {
101
+ "description": str(tool.get("description") or "").strip(),
102
+ "schema_prose": _extract_prose(tool.get("inputSchema") or {}),
103
+ }
104
+
105
+
106
+ def compute_structural_sha256(tool: Dict[str, Any]) -> str:
107
+ """Canonical SHA-256 of the tool's machine contract (`name`, `inputSchema`, plus optional `outputSchema`/`annotations`)."""
108
+ contract: Dict[str, Any] = {
109
+ "name": str(tool.get("name") or ""),
110
+ "inputSchema": _strip_schema_descriptions(tool.get("inputSchema") or {}),
111
+ }
112
+ if tool.get("outputSchema") is not None:
113
+ contract["outputSchema"] = _strip_schema_descriptions(tool["outputSchema"])
114
+ if tool.get("annotations") is not None:
115
+ contract["annotations"] = tool["annotations"]
116
+ canonical = json.dumps(contract, sort_keys=True, separators=(",", ":")).encode("utf-8")
117
+ return hashlib.sha256(canonical).hexdigest()
118
+
119
+
120
+ def compute_description_sha256(tool: Dict[str, Any]) -> str:
121
+ """Canonical SHA-256 of the tool's prose descriptions (tool description + parameter descriptions)."""
122
+ prose = _collect_prose_surface(tool)
123
+ canonical = json.dumps(prose, sort_keys=True, separators=(",", ":")).encode("utf-8")
124
+ return hashlib.sha256(canonical).hexdigest()
125
+
126
+
127
+ def build_lockfile_from_servers(
128
+ servers_tools: Dict[str, Tuple[TrustTier, Optional[str], List[Dict[str, Any]]]],
129
+ allow_poisoned: bool = False,
130
+ ) -> Tuple[ManifestLockfile, List[PoisoningFinding]]:
131
+ """
132
+ Builds a split-hash `ManifestLockfile` from discovered/live server `tools/list` payloads.
133
+ Runs Day-1 poisoning lint on every tool; unless `allow_poisoned=True`, tools with
134
+ CRITICAL/HIGH poisoning findings are quarantined (excluded from pinned lockfile).
135
+ """
136
+ lock = ManifestLockfile()
137
+ all_findings: List[PoisoningFinding] = []
138
+
139
+ for server_name, (trust_tier, url, tools) in sorted(servers_tools.items()):
140
+ pinned_tools: Dict[str, PinnedToolEntry] = {}
141
+ for tool in tools:
142
+ if not isinstance(tool, dict) or not tool.get("name"):
143
+ continue
144
+ tool_name = str(tool["name"])
145
+ findings = lint_tool_definition(server_name, tool)
146
+ all_findings.extend(findings)
147
+ has_blocking_poison = any(
148
+ f.severity in (LintSeverity.CRITICAL, LintSeverity.HIGH) for f in findings
149
+ )
150
+ if has_blocking_poison and not allow_poisoned:
151
+ continue
152
+
153
+ desc_text = str(tool.get("description") or "").strip()
154
+ pinned_tools[tool_name] = PinnedToolEntry(
155
+ structural_sha256=compute_structural_sha256(tool),
156
+ description_sha256=compute_description_sha256(tool),
157
+ description_preview=desc_text[:160],
158
+ poisoning_lint_passed=not has_blocking_poison,
159
+ poisoning_warnings=[f"{f.rule_id}: {f.message}" for f in findings],
160
+ )
161
+
162
+ lock.servers[server_name] = PinnedServerManifest(
163
+ trust_tier=trust_tier,
164
+ url=url,
165
+ tools=pinned_tools,
166
+ )
167
+
168
+ return lock, all_findings
169
+
170
+
171
+ def detect_cross_server_shadowing(
172
+ observed_servers: Dict[str, List[Dict[str, Any]]],
173
+ ) -> List[ManifestDriftItem]:
174
+ """Detects duplicate tool names exposed across multiple MCP servers in the same agent config."""
175
+ tool_owners: Dict[str, List[str]] = {}
176
+ for server_name, tools in sorted(observed_servers.items()):
177
+ for tool in tools:
178
+ if isinstance(tool, dict) and tool.get("name"):
179
+ tname = str(tool["name"])
180
+ tool_owners.setdefault(tname, []).append(server_name)
181
+
182
+ drifts: List[ManifestDriftItem] = []
183
+ for tool_name, owners in sorted(tool_owners.items()):
184
+ unique_owners = sorted(set(owners))
185
+ if len(unique_owners) > 1:
186
+ drifts.append(
187
+ ManifestDriftItem(
188
+ server_name=", ".join(unique_owners),
189
+ tool_name=tool_name,
190
+ kind=DriftKind.CROSS_SERVER_SHADOWING,
191
+ action=DriftAction.BLOCK,
192
+ message=(
193
+ f"Cross-server tool shadowing detected: tool '{tool_name}' is exposed by "
194
+ f"multiple servers ({', '.join(unique_owners)}). Namespace or remove duplicate."
195
+ ),
196
+ )
197
+ )
198
+ return drifts
199
+
200
+
201
+ def verify_tools_list(
202
+ lockfile: ManifestLockfile,
203
+ server_name: str,
204
+ observed_tools: List[Dict[str, Any]],
205
+ trust_tier_override: Optional[TrustTier] = None,
206
+ ) -> LockVerificationResult:
207
+ """
208
+ Verifies a live or CI-inspected `tools/list` payload against `piton.lock`.
209
+ - Structural schema drift -> BLOCK on ALL servers (internal & third-party).
210
+ - Description drift -> BLOCK on `third_party`, WARN on `internal`.
211
+ - Poisoning lint critical/high on drifted or new tools -> BLOCK on ALL servers.
212
+ - Unpinned tool -> BLOCK on `third_party`, WARN on `internal`.
213
+ """
214
+ pinned_server = lockfile.servers.get(server_name)
215
+ trust_tier = trust_tier_override or (
216
+ pinned_server.trust_tier if pinned_server else TrustTier.THIRD_PARTY
217
+ )
218
+ pinned_tools = pinned_server.tools if pinned_server else {}
219
+
220
+ drifts: List[ManifestDriftItem] = []
221
+ seen_names = set()
222
+
223
+ for tool in observed_tools:
224
+ if not isinstance(tool, dict) or not tool.get("name"):
225
+ continue
226
+ tname = str(tool["name"])
227
+ seen_names.add(tname)
228
+
229
+ obs_struct = compute_structural_sha256(tool)
230
+ obs_desc = compute_description_sha256(tool)
231
+ obs_preview = str(tool.get("description") or "").strip()[:160]
232
+
233
+ # Always run poisoning lint on observed tools so rug-pull injections are caught immediately
234
+ poison_findings = lint_tool_definition(server_name, tool)
235
+ blocking_poison = [
236
+ f for f in poison_findings if f.severity in (LintSeverity.CRITICAL, LintSeverity.HIGH)
237
+ ]
238
+ if blocking_poison:
239
+ drifts.append(
240
+ ManifestDriftItem(
241
+ server_name=server_name,
242
+ tool_name=tname,
243
+ kind=DriftKind.DAY1_POISONING,
244
+ action=DriftAction.BLOCK,
245
+ message=f"Tool poisoning detected ({blocking_poison[0].rule_id}): {blocking_poison[0].message}",
246
+ observed_sha256=obs_desc,
247
+ observed_preview=obs_preview,
248
+ )
249
+ )
250
+
251
+ pinned = pinned_tools.get(tname)
252
+ if pinned is None:
253
+ drifts.append(
254
+ ManifestDriftItem(
255
+ server_name=server_name,
256
+ tool_name=tname,
257
+ kind=DriftKind.UNPINNED_TOOL,
258
+ action=DriftAction.BLOCK if trust_tier == TrustTier.THIRD_PARTY else DriftAction.WARN,
259
+ message=f"Tool '{tname}' on server '{server_name}' is not pinned in piton.lock.",
260
+ observed_sha256=obs_struct,
261
+ observed_preview=obs_preview,
262
+ )
263
+ )
264
+ continue
265
+
266
+ if obs_struct != pinned.structural_sha256:
267
+ drifts.append(
268
+ ManifestDriftItem(
269
+ server_name=server_name,
270
+ tool_name=tname,
271
+ kind=DriftKind.STRUCTURAL_DRIFT,
272
+ action=DriftAction.BLOCK,
273
+ message=(
274
+ f"Structural schema drift on '{server_name}.{tname}': inputSchema contract "
275
+ "changed since piton.lock was approved."
276
+ ),
277
+ expected_sha256=pinned.structural_sha256,
278
+ observed_sha256=obs_struct,
279
+ )
280
+ )
281
+
282
+ if obs_desc != pinned.description_sha256:
283
+ action = DriftAction.BLOCK if trust_tier == TrustTier.THIRD_PARTY else DriftAction.WARN
284
+ drifts.append(
285
+ ManifestDriftItem(
286
+ server_name=server_name,
287
+ tool_name=tname,
288
+ kind=DriftKind.DESCRIPTION_DRIFT,
289
+ action=action,
290
+ message=(
291
+ f"Description drift on {trust_tier.value} server '{server_name}.{tname}': "
292
+ + (
293
+ "blocked as potential rug pull."
294
+ if action == DriftAction.BLOCK
295
+ else "warning only (internal server); run `piton lock --update` after review."
296
+ )
297
+ ),
298
+ expected_sha256=pinned.description_sha256,
299
+ observed_sha256=obs_desc,
300
+ previous_preview=pinned.description_preview,
301
+ observed_preview=obs_preview,
302
+ )
303
+ )
304
+
305
+ for pinned_name in sorted(pinned_tools.keys()):
306
+ if pinned_name not in seen_names:
307
+ drifts.append(
308
+ ManifestDriftItem(
309
+ server_name=server_name,
310
+ tool_name=pinned_name,
311
+ kind=DriftKind.REMOVED_TOOL,
312
+ action=DriftAction.WARN,
313
+ message=f"Pinned tool '{pinned_name}' is no longer advertised by '{server_name}'.",
314
+ )
315
+ )
316
+
317
+ blocked_count = sum(1 for d in drifts if d.action == DriftAction.BLOCK)
318
+ warning_count = sum(1 for d in drifts if d.action == DriftAction.WARN)
319
+ return LockVerificationResult(
320
+ passed=blocked_count == 0,
321
+ blocked_count=blocked_count,
322
+ warning_count=warning_count,
323
+ drifts=drifts,
324
+ )
325
+
326
+
327
+ def diff_lockfiles(old: ManifestLockfile, new: ManifestLockfile) -> LockVerificationResult:
328
+ """Computes a structured diff between an approved `piton.lock` and a newly scanned lockfile."""
329
+ drifts: List[ManifestDriftItem] = []
330
+ all_servers = sorted(set(old.servers.keys()) | set(new.servers.keys()))
331
+
332
+ for srv in all_servers:
333
+ old_srv = old.servers.get(srv)
334
+ new_srv = new.servers.get(srv)
335
+ trust = new_srv.trust_tier if new_srv else (old_srv.trust_tier if old_srv else TrustTier.THIRD_PARTY)
336
+ old_tools = old_srv.tools if old_srv else {}
337
+ new_tools = new_srv.tools if new_srv else {}
338
+
339
+ for tname in sorted(set(old_tools.keys()) | set(new_tools.keys())):
340
+ o = old_tools.get(tname)
341
+ n = new_tools.get(tname)
342
+ if o is None and n is not None:
343
+ drifts.append(
344
+ ManifestDriftItem(
345
+ server_name=srv,
346
+ tool_name=tname,
347
+ kind=DriftKind.UNPINNED_TOOL,
348
+ action=DriftAction.BLOCK if trust == TrustTier.THIRD_PARTY else DriftAction.WARN,
349
+ message=f"New tool added: '{srv}.{tname}'.",
350
+ observed_sha256=n.structural_sha256,
351
+ observed_preview=n.description_preview,
352
+ )
353
+ )
354
+ elif o is not None and n is None:
355
+ drifts.append(
356
+ ManifestDriftItem(
357
+ server_name=srv,
358
+ tool_name=tname,
359
+ kind=DriftKind.REMOVED_TOOL,
360
+ action=DriftAction.WARN,
361
+ message=f"Tool removed: '{srv}.{tname}'.",
362
+ expected_sha256=o.structural_sha256,
363
+ )
364
+ )
365
+ elif o is not None and n is not None:
366
+ if o.structural_sha256 != n.structural_sha256:
367
+ drifts.append(
368
+ ManifestDriftItem(
369
+ server_name=srv,
370
+ tool_name=tname,
371
+ kind=DriftKind.STRUCTURAL_DRIFT,
372
+ action=DriftAction.BLOCK,
373
+ message=f"Structural inputSchema changed on '{srv}.{tname}'.",
374
+ expected_sha256=o.structural_sha256,
375
+ observed_sha256=n.structural_sha256,
376
+ )
377
+ )
378
+ if o.description_sha256 != n.description_sha256:
379
+ drifts.append(
380
+ ManifestDriftItem(
381
+ server_name=srv,
382
+ tool_name=tname,
383
+ kind=DriftKind.DESCRIPTION_DRIFT,
384
+ action=DriftAction.BLOCK if trust == TrustTier.THIRD_PARTY else DriftAction.WARN,
385
+ message=f"Description prose changed on '{srv}.{tname}'.",
386
+ expected_sha256=o.description_sha256,
387
+ observed_sha256=n.description_sha256,
388
+ previous_preview=o.description_preview,
389
+ observed_preview=n.description_preview,
390
+ )
391
+ )
392
+
393
+ blocked = sum(1 for d in drifts if d.action == DriftAction.BLOCK)
394
+ warned = sum(1 for d in drifts if d.action == DriftAction.WARN)
395
+ return LockVerificationResult(
396
+ passed=blocked == 0,
397
+ blocked_count=blocked,
398
+ warning_count=warned,
399
+ drifts=drifts,
400
+ )
401
+
402
+
403
+ def render_diff_markdown(result: LockVerificationResult) -> str:
404
+ """Renders a GitHub PR-ready markdown table for CI diff-review gates."""
405
+ if not result.drifts:
406
+ return "### Piton Lockfile Check: Passed\nNo MCP tool schema or description drift detected."
407
+
408
+ status = "BLOCKED" if not result.passed else "WARNING"
409
+ warn_word = "warning" if result.warning_count == 1 else "warnings"
410
+ lines = [
411
+ f"### Piton Lockfile Check: {status} ({result.blocked_count} blocking, {result.warning_count} {warn_word})",
412
+ "",
413
+ "| Action | Server | Tool | Drift Type | Details |",
414
+ "| --- | --- | --- | --- | --- |",
415
+ ]
416
+ for d in result.drifts:
417
+ lines.append(
418
+ f"| **{d.action.value.upper()}** | `{d.server_name}` | `{d.tool_name}` | `{d.kind.value}` | {d.message} |"
419
+ )
420
+ return "\n".join(lines)