@mokuyoaxis/agent-guard 0.2.6 → 0.2.7

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.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![npm stable](https://img.shields.io/npm/v/%40mokuyoaxis%2Fagent-guard.svg)](https://www.npmjs.com/package/@mokuyoaxis/agent-guard)
5
5
  [![License](https://img.shields.io/github/license/mokuyoaxis/agent-guard)](LICENSE)
6
6
  [![Python 3.9+](https://img.shields.io/badge/Python-3.9%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
7
- [![0.2.5](https://img.shields.io/badge/release-0.2.5-5B6B7A)](docs/releases/release-notes-0.2.5.md)
7
+ [![0.2.7](https://img.shields.io/badge/version-0.2.7-5B6B7A)](docs/releases/release-notes-0.2.7.md)
8
8
 
9
9
  **Make destructive agent actions reversible by default.** · [简体中文](README.zh-CN.md)
10
10
 
@@ -23,14 +23,23 @@ Installed Skills or copied configuration alone do not establish protection.
23
23
  We currently focus on **DSH and Kimi Code** integrations. For other hosts,
24
24
  ask the official coding agent to configure Agent Guard locally.
25
25
 
26
+ This documentation covers [0.2.7](docs/releases/release-notes-0.2.7.md), adding
27
+ Cleanup plans, deletion admission limits and optional local MCP tools.
28
+ Check the exact-version release channels below before installing.
29
+
26
30
  | Capability | What it helps you do | Entry |
27
31
  |---|---|---|
28
32
  | **Recovery protection** | Relocate valuable files before deletion; snapshot tracked state before supported Git overwrites; inspect and restore transactions | [delete-guard](skills/delete-guard/SKILL.md) |
33
+ | **Cleanup proposals (0.2.7)** | Review classified workspace candidates, sizes and effects; explicitly confirm selected targets before safe_delete | [Cleanup Copilot](docs/guides/cleanup-plan.md) |
34
+ | **Deletion limits (0.2.7)** | Inspect shared protected paths, persistent budgets, rate/repeat limits and large-batch confirmation | [Limits and recovery](docs/guides/deletion-limits.md) |
35
+ | **Local MCP tools (0.2.7)** | Call safe_delete, ordinary restore, transaction/status queries and GC preview from a supporting client | [MCP setup](docs/guides/mcp.md) |
29
36
  | **Disclosure checks** | Detect supported credentials and host-identifying paths; apply a redaction plan or withhold a payload | [exfil-guard](skills/exfil-guard/SKILL.md) |
30
37
  | **Behaviour experiments** | Calibrate an observer, test a declared exposure channel, then compare matched guard-off/on trials | [guard-lab](docs/lab/guard-lab.md) |
31
38
 
32
39
  A Skill supplies instructions; it does not intercept tool calls. Automatic
33
40
  protection depends on an active, compatible host hook and its covered tools.
41
+ The optional local MCP adapter provides explicit tools and does not intercept
42
+ actions that bypass them; its SDK installation is separate from the Core.
34
43
  Agent Guard is not an OS sandbox against a malicious process with equal
35
44
  privileges. The [capability matrix](docs/guides/harness-capabilities.md)
36
45
  states the observed coverage and gaps.
@@ -98,24 +107,33 @@ This example calls no model; its summary describes instrument calibration.
98
107
 
99
108
  Python 3.9+ and Git are required for the Core. The examples use a POSIX shell;
100
109
  native bridges and optional capture helpers have their own requirements.
110
+ The optional MCP adapter requires Python 3.10+ and a separately installed
111
+ [pinned SDK](docs/guides/mcp.md).
101
112
 
102
113
  | Version | Status |
103
114
  |---|---|
104
- | [0.2.6](docs/releases/release-notes-0.2.6.md) | Stable release; npm `latest`; release links below |
105
- | [0.2.5](docs/releases/release-notes-0.2.5.md) | Previous stable release |
115
+ | [0.2.7](docs/releases/release-notes-0.2.7.md) | Version documented here; verify exact-version availability below |
116
+ | [0.2.6](docs/releases/release-notes-0.2.6.md) | Earlier published release with Kimi feedback and host compatibility updates |
117
+ | [0.2.5](docs/releases/release-notes-0.2.5.md) | Earlier stable release |
106
118
  | [0.2.4](docs/releases/release-notes-0.2.4.md) | Earlier stable release |
107
119
  | [0.2.4-hotfix.1](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.4-hotfix.1) | Opt-in quarantine protection backport; npm `hotfix` |
108
120
  | [0.2.5-rc3](docs/releases/release-notes-0.2.5-rc3.md) | Published prerelease, including RC1/RC2 maintenance; npm `rc` |
109
121
 
110
- Publication is established by the exact
111
- [GitHub release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.6)
112
- and [npm version](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.6).
122
+ Before installing 0.2.7, confirm availability through its exact
123
+ [GitHub release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.7)
124
+ and [npm version](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.7).
113
125
  A checkout or manifest alone does not establish package availability.
114
126
 
115
- For the stable release, use a chosen, stable user-owned prefix:
127
+ If that version is unavailable, use reviewed source or a locally built
128
+ tarball following the [version notes](docs/releases/release-notes-0.2.7.md).
129
+ Versioned tests and package checks are recorded separately from the historical
130
+ 0.2.6-metadata source results. Existing successful deletes can newly be
131
+ refused by the [admission limits](docs/guides/deletion-limits.md).
132
+
133
+ Once the exact version is available, install to a chosen, stable user-owned prefix:
116
134
 
117
135
  ```sh
118
- npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.6
136
+ npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.7
119
137
  ```
120
138
 
121
139
  The package root is
@@ -140,7 +158,7 @@ preflight diagnostics, DSH `0.2.1-alpha.4` default deletion support and the
140
158
  Kimi `2.3.0` Bash profile. Existing installations need an upgrade to acquire
141
159
  these additions; Stop also needs explicit configuration. See
142
160
  [setup and the agent setup prompt](docs/guides/getting-started.md) and the
143
- [maintenance details](docs/releases/unreleased.md).
161
+ [0.2.6 version details](docs/releases/release-notes-0.2.6.md).
144
162
 
145
163
  ## Recover a supported deletion
146
164
 
@@ -264,7 +282,7 @@ reconstruction and known gaps. It cannot recreate bytes that no source kept.
264
282
  | [Threat model](docs/design/threat-model.md) | Trust assumptions and unresolved boundaries |
265
283
  | [Compatibility](docs/design/compatibility.md) | Interface and release contracts |
266
284
  | [Blue-team research](docs/research/README.md) | Defensive methods, sanitized results and a zero-model starting point |
267
- | [0.2.5 notes](docs/releases/release-notes-0.2.5.md) | Release scope, upgrade impact and validation boundaries |
285
+ | [0.2.7 notes](docs/releases/release-notes-0.2.7.md) | Version scope, upgrade impact and validation boundaries |
268
286
 
269
287
  ## Contributing
270
288
 
package/README.zh-CN.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![npm 稳定版](https://img.shields.io/npm/v/%40mokuyoaxis%2Fagent-guard.svg)](https://www.npmjs.com/package/@mokuyoaxis/agent-guard)
5
5
  [![License](https://img.shields.io/github/license/mokuyoaxis/agent-guard)](LICENSE)
6
6
  [![Python 3.9+](https://img.shields.io/badge/Python-3.9%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
7
- [![0.2.5](https://img.shields.io/badge/release-0.2.5-5B6B7A)](docs/releases/release-notes-0.2.5.md)
7
+ [![0.2.7](https://img.shields.io/badge/version-0.2.7-5B6B7A)](docs/releases/release-notes-0.2.7.md)
8
8
 
9
9
  **让 AI Agent 的破坏性操作默认可逆。** · [English](README.md)
10
10
 
@@ -21,15 +21,23 @@ Agent Guard 在受支持的删除、覆盖操作前保留恢复数据,检查
21
21
  目前主要维护 **DSH 和 Kimi Code** 的接入。其他宿主建议交给对应的官方
22
22
  编码 Agent 在本地配置。
23
23
 
24
+ 本文档覆盖 [0.2.7](docs/releases/release-notes-0.2.7.md),新增 Cleanup 计划、
25
+ 删除准入限制与可选本地 MCP 工具。安装前请通过下方精确版本渠道确认可用性。
26
+
24
27
  | 能力 | 能帮助你做什么 | 入口 |
25
28
  |---|---|---|
26
29
  | **恢复保护** | 删除前迁移有价值的文件;受支持的 Git 覆盖前快照 tracked 状态;查询和恢复事务 | [delete-guard](skills/delete-guard/SKILL.md) |
30
+ | **清理提议(0.2.7)** | 扫描候选、分类、大小与实际执行方式;显式选择并确认后交给 safe_delete | [Cleanup Copilot](docs/guides/cleanup-plan.md) |
31
+ | **删除限制(0.2.7)** | 查询共享保护路径、持久预算、速率/重复限制与大批量确认 | [限制与恢复](docs/guides/deletion-limits.md) |
32
+ | **本地 MCP 工具(0.2.7)** | 在支持的客户端中调用 safe_delete、普通恢复、事务/状态查询和 GC 预览 | [MCP 接入](docs/guides/mcp.md) |
27
33
  | **外发检测** | 检测受支持的凭据和本机标识路径;应用脱敏计划或拒绝输出 | [exfil-guard](skills/exfil-guard/SKILL.md) |
28
34
  | **行为验测** | 校准观察器,验证声明信道的暴露,再比较匹配的关闭/开启防护试次 | [guard-lab](docs/lab/guard-lab.md) |
29
35
 
30
36
  Skill 提供操作纪律,不会自行拦截工具调用。自动保护依赖宿主实际加载了
31
37
  兼容 hook,且调用位于其覆盖范围内。Agent Guard 不是抵抗同权限恶意进程的
32
38
  OS 沙箱;实际接入证据和缺口见[能力矩阵](docs/guides/harness-capabilities.md)。
39
+ 可选本地 MCP 适配器提供显式工具,不会拦截绕过它的操作;其 SDK 单独安装,
40
+ 不改变 Core 的运行依赖。
33
41
 
34
42
  <a id="guard-lab-合成蜜罐"></a>
35
43
 
@@ -84,24 +92,30 @@ python3 docs/lab/examples/blue-team-calibration.py --output-dir "$blue_run/contr
84
92
 
85
93
  Core 需要 Python 3.9+ 和 Git。示例采用 POSIX Shell;原生桥接和可选采集
86
94
  工具另有运行要求。
95
+ 可选 MCP 适配器需要 Python 3.10+,并单独安装[固定版本 SDK](docs/guides/mcp.md)。
87
96
 
88
97
  | 版本 | 状态 |
89
98
  |---|---|
90
- | [0.2.6](docs/releases/release-notes-0.2.6.md) | 正式版;npm `latest`;发布地址见下方 |
91
- | [0.2.5](docs/releases/release-notes-0.2.5.md) | 上一稳定版 |
99
+ | [0.2.7](docs/releases/release-notes-0.2.7.md) | 本文档对应版本;精确版本的可用性见下方渠道 |
100
+ | [0.2.6](docs/releases/release-notes-0.2.6.md) | 历史已发布版本,包含 Kimi 反馈与宿主兼容性更新 |
101
+ | [0.2.5](docs/releases/release-notes-0.2.5.md) | 更早稳定版 |
92
102
  | [0.2.4](docs/releases/release-notes-0.2.4.md) | 更早稳定版 |
93
103
  | [0.2.4-hotfix.1](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.4-hotfix.1) | 显式选择的回收站保护回补;npm `hotfix` |
94
104
  | [0.2.5-rc3](docs/releases/release-notes-0.2.5-rc3.md) | 已发布预发布版,包含 RC1/RC2 维护;npm `rc` |
95
105
 
96
- 实际发布状态以精确版本的
97
- [GitHub Release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.6)和
98
- [npm 版本页](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.6)为准,
106
+ 安装 0.2.7 前,请通过精确版本的
107
+ [GitHub Release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.7)和
108
+ [npm 版本页](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.7)确认可用性,
99
109
  checkout 或 manifest 本身不代表包已可安装。
100
110
 
101
- 稳定包可安装到用户选定的长期目录:
111
+ 若该版本尚不可用,请按[版本说明](docs/releases/release-notes-0.2.7.md)使用经复核的
112
+ 源码或本地构建 tarball。版本化测试和包核验已单独记录,不能沿用旧 0.2.6 元数据
113
+ 候选的通过结论。此前可执行的删除可能被新的[准入限制](docs/guides/deletion-limits.md)拒绝。
114
+
115
+ 确认精确版本可用后,可安装到用户选定的长期目录:
102
116
 
103
117
  ```sh
104
- npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.6
118
+ npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.7
105
119
  ```
106
120
 
107
121
  包根目录是
@@ -123,7 +137,7 @@ cd agent-guard
123
137
  恢复反馈、独立 Stop doctor 检查、DSH Lab 预检诊断、DSH `0.2.1-alpha.4` 默认删除适配,
124
138
  以及 Kimi `2.3.0` Bash profile。已有安装需要升级才能取得这些功能,Stop 还需显式配置。
125
139
  接入步骤与 Agent 提示词见[入门指南](docs/guides/getting-started.md),
126
- 功能边界见[维护说明](docs/releases/unreleased.md)。
140
+ 历史功能边界见[0.2.6 说明](docs/releases/release-notes-0.2.6.md)。
127
141
 
128
142
  ## 恢复一次受支持的删除
129
143
 
@@ -230,7 +244,7 @@ Git/会话/缓存证据恢复项目,区分原文、重建与确认缺失
230
244
  | [威胁模型](docs/design/threat-model.md) | 信任假设与尚未解决的边界 |
231
245
  | [兼容契约](docs/design/compatibility.md) | 接口与发布约定 |
232
246
  | [蓝队研究](docs/research/README.md) | 防守方法、去敏结果与零模型起点 |
233
- | [0.2.5 说明](docs/releases/release-notes-0.2.5.md) | 发布范围、升级影响与验证边界 |
247
+ | [0.2.7 说明](docs/releases/release-notes-0.2.7.md) | 版本范围、升级影响与验证边界 |
234
248
 
235
249
  ## 参与贡献
236
250
 
@@ -63,6 +63,12 @@ or a public report. If the host contract or version is unclear, mark it
63
63
  - **No verified blocking event:** use the [Skills](../skills) and explicit
64
64
  CLI cooperatively. Say `Skill/CLI only`; do not claim native interception.
65
65
  A hook limited to some tools does not cover other tools or hidden uploads.
66
+ - **Client supports MCP:** the [local MCP adapter](../docs/guides/mcp.md), introduced in 0.2.7,
67
+ exposes explicit safe_delete, ordinary restore, transaction/status queries
68
+ and GC preview. Configure its optional SDK and fixed workspace separately.
69
+ Say `MCP tools only` unless a separate blocking hook has been verified;
70
+ registering tools does not intercept shell, script or editor operations.
71
+ This path adds no force restore, GC execution or model-approved budget reset.
66
72
 
67
73
  Core `ASK` must reach a real human-approval path or become a refusal for that
68
74
  call. It must never silently become allow. Treat malformed payloads and
@@ -0,0 +1 @@
1
+ """Optional MCP adapter; importing its operations does not require an MCP SDK."""
@@ -0,0 +1,174 @@
1
+ """Fixed-workspace MCP operations implemented by the existing JSON CLIs.
2
+
3
+ This module has no SDK dependency. It accepts structured arguments, never a
4
+ shell command, and leaves policy, admission, audit and recovery to the CLIs.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import glob
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import re
13
+ import subprocess
14
+ import sys
15
+ import threading
16
+
17
+
18
+ ROOT = Path(__file__).resolve().parents[2]
19
+ SCRIPTS = ROOT / "skills" / "delete-guard" / "scripts"
20
+ TOOLS = frozenset(("safe_delete", "restore", "transactions", "status", "gc_plan"))
21
+ MAX_PATHS = 1000
22
+ TXID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*\Z")
23
+
24
+
25
+ class InvalidArguments(ValueError):
26
+ """An unsupported MCP argument, before any CLI is started."""
27
+
28
+
29
+ def _inside(path, root):
30
+ try:
31
+ return os.path.commonpath((os.path.normcase(path), os.path.normcase(root))) == os.path.normcase(root)
32
+ except ValueError:
33
+ return False
34
+
35
+
36
+ def _locations(path):
37
+ absolute = os.path.normpath(os.path.abspath(path))
38
+ parent, leaf = os.path.split(absolute)
39
+ return (absolute, os.path.realpath(absolute), os.path.join(os.path.realpath(parent), leaf))
40
+
41
+
42
+ class Operations:
43
+ """One server binding; clients cannot supply paths to another workspace.
44
+
45
+ ``session=None`` uses the CLI's stable shared default budget, including
46
+ after a server restart. An explicit identity is trusted startup input,
47
+ never a tool argument. The selected quarantine is workspace-local.
48
+ """
49
+
50
+ def __init__(self, workspace, *, session=None, timeout=120):
51
+ selected = Path(workspace).resolve(strict=True)
52
+ if not selected.is_dir() or selected.parent == selected:
53
+ raise ValueError("MCP workspace must be an existing non-root directory")
54
+ if session is not None and (not isinstance(session, str) or not session or "\0" in session):
55
+ raise ValueError("MCP session must be a nonempty startup identity")
56
+ if type(timeout) not in (int, float) or not 0 < timeout <= 3600:
57
+ raise ValueError("MCP CLI timeout must be positive and at most 3600 seconds")
58
+ self.workspace = str(selected)
59
+ self.trash_root = os.path.join(self.workspace, ".agent-trash")
60
+ self.timeout = timeout
61
+ self._env = {key: value for key, value in os.environ.items()
62
+ if not key.startswith(("AGENT_GUARD_", "GIT_"))
63
+ and key not in ("PYTHONPATH", "PYTHONHOME")}
64
+ self._env.update(AGENT_GUARD_WORKSPACE=self.workspace,
65
+ AGENT_GUARD_TRASH=self.trash_root,
66
+ PYTHONDONTWRITEBYTECODE="1")
67
+ if session is not None:
68
+ self._env["AGENT_GUARD_SESSION"] = session
69
+ self._lock = threading.Lock()
70
+
71
+ @staticmethod
72
+ def validate(name, arguments):
73
+ """Validate once at the adapter boundary, including unknown fields."""
74
+ if not isinstance(name, str) or name not in TOOLS:
75
+ raise InvalidArguments("unknown MCP tool")
76
+ if not isinstance(arguments, dict):
77
+ raise InvalidArguments("tool arguments must be an object")
78
+ allowed = {"safe_delete": {"paths", "dry_run"}, "restore": {"txid"},
79
+ "status": {"tail"}, "transactions": set(), "gc_plan": set()}[name]
80
+ if set(arguments) - allowed:
81
+ raise InvalidArguments("unsupported tool argument")
82
+ result = dict(arguments)
83
+ if name == "safe_delete":
84
+ paths = result.get("paths")
85
+ if (not isinstance(paths, list) or not 1 <= len(paths) <= MAX_PATHS
86
+ or any(not isinstance(path, str) or not path or "\0" in path for path in paths)):
87
+ raise InvalidArguments("paths must contain 1 through 1000 nonempty literal paths")
88
+ if any(os.path.normpath(path)[-1].isspace() for path in paths):
89
+ # The existing path classifier strips terminal whitespace.
90
+ # Refuse rather than let a literal tool select a neighbor.
91
+ raise InvalidArguments("literal paths cannot end in whitespace")
92
+ if type(result.get("dry_run", False)) is not bool:
93
+ raise InvalidArguments("dry_run must be a boolean")
94
+ result["dry_run"] = result.get("dry_run", False)
95
+ elif name == "restore":
96
+ txid = result.get("txid")
97
+ # Match the recovery engine's transaction-ID grammar at this
98
+ # untrusted tool boundary; no filesystem path or CLI option.
99
+ if not isinstance(txid, str) or not TXID_RE.fullmatch(txid):
100
+ raise InvalidArguments("txid must use the recovery transaction-ID format")
101
+ elif name == "status":
102
+ if type(result.get("tail", 10)) is not int or not 0 <= result.get("tail", 10) <= 100:
103
+ raise InvalidArguments("tail must be an integer between 0 and 100")
104
+ result["tail"] = result.get("tail", 10)
105
+ return result
106
+
107
+ def _quarantine_overlap(self, paths):
108
+ boundaries = _locations(self.trash_root)
109
+ return any(_inside(target, boundary) or _inside(boundary, target)
110
+ for path in paths for target in _locations(path) for boundary in boundaries)
111
+
112
+ @staticmethod
113
+ def _failure(name, code, message, *, exit_code=None, may_have_changed=False):
114
+ return {"tool": name, "ok": False, "exit_code": exit_code,
115
+ "error": {"code": code, "message": message,
116
+ "may_have_changed": may_have_changed,
117
+ "inspect_tools": ["status", "transactions"] if may_have_changed else []}}
118
+
119
+ def call(self, name, arguments):
120
+ args = self.validate(name, arguments)
121
+ mutating = name == "restore" or (name == "safe_delete" and not args["dry_run"])
122
+ if name == "safe_delete":
123
+ paths = [os.path.normpath(os.path.join(self.workspace, path)) for path in args["paths"]]
124
+ if self._quarantine_overlap(paths):
125
+ return self._failure(name, "MCP_QUARANTINE_PROTECTED",
126
+ "MCP safe_delete cannot remove quarantine contents or their ancestors; GC is preview-only")
127
+ command = ["safe_delete.py", "--json"]
128
+ if args["dry_run"]:
129
+ command.append("--dry-run")
130
+ # The CLI expands globs. Escape each absolute target so a literal
131
+ # filename such as '[old]*.txt' cannot select adjacent files.
132
+ command += ["--", *(glob.escape(path) for path in paths)]
133
+ elif name == "restore":
134
+ command = ["restore.py", "restore", "--json", "--", args["txid"]]
135
+ elif name == "transactions":
136
+ command = ["restore.py", "list", "--json"]
137
+ elif name == "status":
138
+ command = ["status.py", "--json", "--tail", str(args["tail"])]
139
+ else:
140
+ command = ["gc.py", "--json"]
141
+
142
+ # Serialize calls in this server, without changing process cwd or
143
+ # environment. Other participating processes share Core admission.
144
+ with self._lock:
145
+ try:
146
+ child = subprocess.run([sys.executable, "-B", str(SCRIPTS / command[0]), *command[1:]],
147
+ cwd=self.workspace, env=self._env, stdin=subprocess.DEVNULL,
148
+ capture_output=True, text=True, encoding="utf-8", errors="strict",
149
+ timeout=self.timeout, shell=False)
150
+ except subprocess.TimeoutExpired:
151
+ return self._failure(name, "MCP_CLI_TIMEOUT",
152
+ "CLI timed out; do not retry automatically. Inspect status and recovery transactions",
153
+ may_have_changed=mutating)
154
+ except OSError as exc:
155
+ return self._failure(name, "MCP_CLI_UNAVAILABLE",
156
+ "CLI could not start (OS error " + str(exc.errno) + ")")
157
+ except UnicodeError:
158
+ return self._failure(name, "MCP_CLI_PROTOCOL_ERROR",
159
+ "CLI output is not valid UTF-8; inspect recovery state before retrying",
160
+ may_have_changed=mutating)
161
+ try:
162
+ result = json.loads(child.stdout)
163
+ except (ValueError, RecursionError):
164
+ return self._failure(name, "MCP_CLI_PROTOCOL_ERROR",
165
+ "CLI did not return a JSON object; inspect recovery state before retrying",
166
+ exit_code=child.returncode, may_have_changed=mutating)
167
+ if not isinstance(result, dict):
168
+ return self._failure(name, "MCP_CLI_PROTOCOL_ERROR",
169
+ "CLI did not return a JSON object; inspect recovery state before retrying",
170
+ exit_code=child.returncode, may_have_changed=mutating)
171
+ # Preserve all existing CLI evidence, including txids/moved paths on
172
+ # partial failures. A nonzero exit never means 'nothing changed'.
173
+ return {"tool": name, "ok": child.returncode == 0,
174
+ "exit_code": child.returncode, "result": result}
@@ -0,0 +1,3 @@
1
+ # Optional MCP adapter only; the existing Core and CLIs use the standard library.
2
+ # Official modelcontextprotocol/python-sdk, MIT license. No CLI extras required.
3
+ mcp==2.3.0
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env python3
2
+ """Optional, workspace-bound MCP stdio adapter for the existing guard CLIs."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import importlib.metadata
8
+ import json
9
+ from pathlib import Path
10
+ import sys
11
+
12
+ sys.dont_write_bytecode = True
13
+ ROOT = Path(__file__).resolve().parents[2]
14
+ sys.path.insert(0, str(ROOT))
15
+
16
+ SDK_VERSION = "2.3.0"
17
+ INSTRUCTIONS = (
18
+ "Use these tools for explicit filesystem maintenance in the server's fixed workspace. "
19
+ "Ordinary safe_delete preserves recovery copies and does not free their disk space; "
20
+ "proven regenerable artifacts may be physically removed. Record returned transaction IDs. "
21
+ "Inspect transactions before restoring. Never bypass a refusal, change session identity, "
22
+ "or retry an uncertain mutation automatically. Large batches and operator-only actions "
23
+ "remain in the existing CLI workflow. GC here is preview only. These tools do not "
24
+ "intercept other shell or editor operations."
25
+ )
26
+
27
+ TOOL_DEFINITIONS = {
28
+ "safe_delete": {
29
+ "description": "Delete explicit literal paths using existing guard policy, budgets and audit. Ordinary files are quarantined with a recovery transaction; proven ignored regenerable artifacts may be permanently removed. No shell or glob expansion. Quarantine targets are refused. Large batches require the operator's existing Cleanup CLI workflow.",
30
+ "properties": {"paths": {"type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1, "maxItems": 1000},
31
+ "dry_run": {"type": "boolean", "default": False}},
32
+ "required": ["paths"], "read_only": False, "destructive": True,
33
+ },
34
+ "restore": {
35
+ "description": "Restore one transaction returned by transactions, without overwriting an existing occupant. No force option. Restoration does not refund deletion budget. Inspect the returned per-item result and filesystem after partial errors.",
36
+ "properties": {"txid": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9_-]*$"}},
37
+ "required": ["txid"], "read_only": False, "destructive": False,
38
+ },
39
+ "transactions": {
40
+ "description": "List recovery transactions and their RESTORABLE/RESTORED state without changing workspace files. Use returned transaction IDs for ordinary restore.",
41
+ "properties": {}, "required": [], "read_only": True, "destructive": False,
42
+ },
43
+ "status": {
44
+ "description": "Read guard state, recovery storage and persistent current-session budget. A BLOCKED deletion-admission field can coexist with a successful status inspection. Does not reset budgets or change modes.",
45
+ "properties": {"tail": {"type": "integer", "minimum": 0, "maximum": 100, "default": 10}},
46
+ "required": [], "read_only": True, "destructive": False,
47
+ },
48
+ "gc_plan": {
49
+ "description": "Preview existing quarantine transaction GC eligibility and retained space. This tool never executes GC or deletes recovery copies. Execution remains an explicit operator CLI action.",
50
+ "properties": {}, "required": [], "read_only": True, "destructive": False,
51
+ },
52
+ }
53
+
54
+
55
+ def create_server(operations):
56
+ """Load the optional SDK only when starting the adapter, never for --help."""
57
+ import anyio
58
+ import mcp_types as types
59
+ from mcp.server import Server
60
+
61
+ schemas = {name: {"type": "object", "properties": value["properties"],
62
+ "required": value["required"], "additionalProperties": False}
63
+ for name, value in TOOL_DEFINITIONS.items()}
64
+ tools = [types.Tool(
65
+ name=name, description=value["description"], input_schema=schemas[name],
66
+ annotations=types.ToolAnnotations(read_only_hint=value["read_only"],
67
+ destructive_hint=value["destructive"],
68
+ idempotent_hint=False, open_world_hint=False))
69
+ for name, value in TOOL_DEFINITIONS.items()]
70
+
71
+ async def list_tools(context, params):
72
+ return types.ListToolsResult(tools=tools)
73
+
74
+ async def call_tool(context, params):
75
+ # Do not abandon a mutation thread on protocol cancellation: it may
76
+ # already have written recovery evidence. The caller must inspect
77
+ # state after a disconnect instead of inferring rollback or retrying.
78
+ from adapters.mcp.operations import InvalidArguments
79
+
80
+ try:
81
+ result = await anyio.to_thread.run_sync(operations.call, params.name, params.arguments or {})
82
+ except InvalidArguments as exc:
83
+ result = {"tool": params.name, "ok": False, "exit_code": None,
84
+ "error": {"code": "MCP_INVALID_ARGUMENTS", "message": str(exc),
85
+ "may_have_changed": False, "inspect_tools": []}}
86
+ return types.CallToolResult(
87
+ content=[types.TextContent(type="text", text=json.dumps(result, ensure_ascii=True))],
88
+ structured_content=result, is_error=not result["ok"])
89
+
90
+ package_version = json.loads((ROOT / "package.json").read_text(encoding="utf-8"))["version"]
91
+ return Server("agent-guard", version=package_version, instructions=INSTRUCTIONS,
92
+ get_tool_input_schema=schemas.get,
93
+ on_list_tools=list_tools, on_call_tool=call_tool)
94
+
95
+
96
+ async def serve(operations):
97
+ from mcp.server.stdio import stdio_server
98
+
99
+ server = create_server(operations)
100
+ async with stdio_server() as (read_stream, write_stream):
101
+ await server.run(read_stream, write_stream, server.create_initialization_options())
102
+
103
+
104
+ def main(argv=None):
105
+ parser = argparse.ArgumentParser(description="Local agent-guard MCP tools over stdio (optional SDK).")
106
+ parser.add_argument("--workspace", required=True, help="Existing workspace directory, fixed for this process")
107
+ parser.add_argument("--session", help="Trusted stable budget identity; omitted uses the shared CLI bucket")
108
+ args = parser.parse_args(argv)
109
+ from adapters.mcp.operations import Operations
110
+
111
+ try:
112
+ operations = Operations(args.workspace, session=args.session)
113
+ except (ValueError, OSError) as exc:
114
+ parser.error(str(exc))
115
+ try:
116
+ version = importlib.metadata.version("mcp")
117
+ except importlib.metadata.PackageNotFoundError:
118
+ parser.exit(1, "MCP SDK is optional and is not installed. Use a separate Python environment and adapters/mcp/requirements.txt.\n")
119
+ if version != SDK_VERSION:
120
+ parser.exit(1, "Unsupported MCP SDK version. Install the pinned adapters/mcp/requirements.txt in a separate environment.\n")
121
+ asyncio.run(serve(operations))
122
+ return 0
123
+
124
+
125
+ if __name__ == "__main__":
126
+ raise SystemExit(main())