@mokuyoaxis/agent-guard 0.2.6 → 0.2.8

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.
Files changed (39) hide show
  1. package/README.md +45 -20
  2. package/README.zh-CN.md +39 -19
  3. package/adapters/INTEGRATION.md +6 -0
  4. package/adapters/mcp/__init__.py +1 -0
  5. package/adapters/mcp/doctor.py +325 -0
  6. package/adapters/mcp/operations.py +174 -0
  7. package/adapters/mcp/requirements.txt +3 -0
  8. package/adapters/mcp/server.py +126 -0
  9. package/core/admission.py +388 -0
  10. package/core/audit.py +1 -1
  11. package/core/classifier.py +2 -1
  12. package/core/cleanup.py +297 -0
  13. package/core/delete_config.py +153 -0
  14. package/core/policy.py +35 -7
  15. package/core/recovery.py +10 -0
  16. package/docs/README.md +35 -14
  17. package/docs/design/architecture.md +42 -16
  18. package/docs/design/compatibility.md +246 -7
  19. package/docs/design/threat-model.md +53 -1
  20. package/docs/guides/cleanup-plan.md +227 -0
  21. package/docs/guides/deletion-limits.md +150 -0
  22. package/docs/guides/getting-started.md +26 -12
  23. package/docs/guides/harness-capabilities.md +29 -4
  24. package/docs/guides/mcp.md +420 -0
  25. package/docs/history/friction.md +99 -1
  26. package/docs/releases/release-notes-0.2.7.md +217 -0
  27. package/docs/releases/release-notes-0.2.8.md +172 -0
  28. package/docs/releases/unreleased.md +182 -5
  29. package/docs/reports/test-report-dsh-paired-lab.md +1 -1
  30. package/docs/reports/test-report-kimi-code-block.md +1 -1
  31. package/doctor.py +25 -1
  32. package/live_sentinel.py +1 -1
  33. package/package.json +3 -1
  34. package/skills/delete-guard/SKILL.md +69 -1
  35. package/skills/delete-guard/references/policy.md +66 -3
  36. package/skills/delete-guard/scripts/check.py +39 -9
  37. package/skills/delete-guard/scripts/cleanup.py +164 -0
  38. package/skills/delete-guard/scripts/safe_delete.py +22 -4
  39. package/skills/delete-guard/scripts/status.py +77 -1
package/README.md CHANGED
@@ -4,14 +4,15 @@
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.8](https://img.shields.io/badge/release-0.2.8-5B6B7A)](docs/releases/release-notes-0.2.8.md)
8
8
 
9
- **Make destructive agent actions reversible by default.** · [简体中文](README.zh-CN.md)
9
+ **Disclosure checks · Recoverable deletion · Agent experiments** · [简体中文](README.zh-CN.md)
10
10
 
11
- Agent Guard preserves recovery data before supported destructive actions,
12
- checks text before sending it, and provides a Lab for testing agent and host
13
- behaviour. The shared Python Core can be called through command-line tools
14
- or host adapters.
11
+ Agent Guard has three main capabilities: **Exfil-guard** checks text before
12
+ sending it, **Delete-guard** preserves recovery data before supported destructive
13
+ actions, and **Guard-lab** tests agent and host behaviour through controlled
14
+ experiments. A shared Python Core supports the command-line tools and optional
15
+ host adapters.
15
16
 
16
17
  **AI agents setting up this project:** Before changing configuration or writing
17
18
  a bridge, read the [integration requirements](adapters/INTEGRATION.md), then
@@ -23,14 +24,27 @@ Installed Skills or copied configuration alone do not establish protection.
23
24
  We currently focus on **DSH and Kimi Code** integrations. For other hosts,
24
25
  ask the official coding agent to configure Agent Guard locally.
25
26
 
26
- | Capability | What it helps you do | Entry |
27
+ Version **[0.2.8](docs/releases/release-notes-0.2.8.md)** adds MCP connection
28
+ diagnosis and recovery validation to the Cleanup plans, deletion admission
29
+ limits and optional local MCP tools introduced in
30
+ [0.2.7](docs/releases/release-notes-0.2.7.md). Before installing, verify the exact
31
+ GitHub release and npm version through the links below.
32
+
33
+ | Main capability | Included functions | Guides |
27
34
  |---|---|---|
28
- | **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) |
29
- | **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
- | **Behaviour experiments** | Calibrate an observer, test a declared exposure channel, then compare matched guard-off/on trials | [guard-lab](docs/lab/guard-lab.md) |
35
+ | **Exfil-guard** | Check supported credentials and identifying paths; plan and apply redaction; inspect JSON/dotenv structure without displaying scalar values | [Skill and CLI](skills/exfil-guard/SKILL.md) · [Rules](skills/exfil-guard/references/rules.md) · [Safe config view](skills/exfil-guard/SKILL.md#safe-config-view) |
36
+ | **Delete-guard** | Recoverable deletion and supported Git snapshots; Cleanup Copilot; persistent budgets, rate/repeat limits, protected paths and batch confirmation; transaction restore and manual GC; optional local MCP tools and connection diagnosis | [Skill and CLI](skills/delete-guard/SKILL.md) · [Cleanup Copilot](docs/guides/cleanup-plan.md) · [Deletion limits](docs/guides/deletion-limits.md) · [Recovery and GC](docs/guides/recovery-feedback.md) · [MCP tools](docs/guides/mcp.md) · [MCP doctor (0.2.8)](docs/guides/mcp.md#diagnose-a-local-service-028) |
37
+ | **Guard-lab** | Four zero-model calibration controls; synthetic markers and declared-channel observation; evidence and observer-health checks; matched guard-off/on comparisons after an effective baseline | [Lab workflow](docs/lab/guard-lab.md) · [Four-control example](docs/lab/blue-team-calibration.md) · [Evidence levels](docs/lab/guard-lab.md#evidence-levels) |
38
+
39
+ Cleanup Copilot, deletion limits and the current MCP tools/doctor belong to
40
+ **Delete-guard**. Core and adapters provide shared infrastructure;
41
+ [recovery-audit](skills/recovery-audit/SKILL.md) supplies an auxiliary workflow
42
+ for reconstructing a workspace and auditing recovery after an incident.
31
43
 
32
44
  A Skill supplies instructions; it does not intercept tool calls. Automatic
33
45
  protection depends on an active, compatible host hook and its covered tools.
46
+ The optional local MCP adapter provides explicit tools and does not intercept
47
+ actions that bypass them; its SDK installation is separate from the Core.
34
48
  Agent Guard is not an OS sandbox against a malicious process with equal
35
49
  privileges. The [capability matrix](docs/guides/harness-capabilities.md)
36
50
  states the observed coverage and gaps.
@@ -98,24 +112,34 @@ This example calls no model; its summary describes instrument calibration.
98
112
 
99
113
  Python 3.9+ and Git are required for the Core. The examples use a POSIX shell;
100
114
  native bridges and optional capture helpers have their own requirements.
115
+ The optional MCP adapter requires Python 3.10+ and a separately installed
116
+ [pinned SDK](docs/guides/mcp.md).
101
117
 
102
118
  | Version | Status |
103
119
  |---|---|
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 |
120
+ | [0.2.8](docs/releases/release-notes-0.2.8.md) | Current release line; verify exact-version availability below |
121
+ | [0.2.7](docs/releases/release-notes-0.2.7.md) | Earlier release with Cleanup, deletion limits and local MCP tools |
122
+ | [0.2.6](docs/releases/release-notes-0.2.6.md) | Earlier published release with Kimi feedback and host compatibility updates |
123
+ | [0.2.5](docs/releases/release-notes-0.2.5.md) | Earlier stable release |
106
124
  | [0.2.4](docs/releases/release-notes-0.2.4.md) | Earlier stable release |
107
125
  | [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
126
  | [0.2.5-rc3](docs/releases/release-notes-0.2.5-rc3.md) | Published prerelease, including RC1/RC2 maintenance; npm `rc` |
109
127
 
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).
128
+ Before installing 0.2.8, confirm availability through its exact
129
+ [GitHub release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.8)
130
+ and [npm version](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.8).
113
131
  A checkout or manifest alone does not establish package availability.
114
132
 
115
- For the stable release, use a chosen, stable user-owned prefix:
133
+ If that version is unavailable, use reviewed source or a locally built
134
+ tarball following the [version notes](docs/releases/release-notes-0.2.8.md).
135
+ Versioned tests and package checks retain their original checkpoints.
136
+ The [admission limits](docs/guides/deletion-limits.md) introduced in 0.2.7 can
137
+ refuse previously successful deletions and remain in effect in 0.2.8.
138
+
139
+ Once the exact version is available, install to a chosen, stable user-owned prefix:
116
140
 
117
141
  ```sh
118
- npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.6
142
+ npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.8
119
143
  ```
120
144
 
121
145
  The package root is
@@ -140,7 +164,7 @@ preflight diagnostics, DSH `0.2.1-alpha.4` default deletion support and the
140
164
  Kimi `2.3.0` Bash profile. Existing installations need an upgrade to acquire
141
165
  these additions; Stop also needs explicit configuration. See
142
166
  [setup and the agent setup prompt](docs/guides/getting-started.md) and the
143
- [maintenance details](docs/releases/unreleased.md).
167
+ [0.2.6 version details](docs/releases/release-notes-0.2.6.md).
144
168
 
145
169
  ## Recover a supported deletion
146
170
 
@@ -234,7 +258,8 @@ tool paths. Other combinations need their own checks.
234
258
  | Claude Code | Retained reference; new version validation paused. Native Bash `PreToolUse`; sampled 2.1.270/2.1.273 scripted-host enforcement. [Setup](adapters/claude/README.md) |
235
259
  | Kimi Code | Native Bash `PreToolUse`; bounded 0.42.0 root/child and 2.1.1 root-Bash observations. Version 0.2.6 adds 2.3.0 prompt/ACP root-Bash evidence with fixed responses. ASK is denied; missing/timed-out hooks remain uncovered. [Setup](adapters/kimi-code/README.md) |
236
260
  | DSH | Default deletion paths on 0.1.5-rc.1/0.2.0-rc.2/0.2.1-alpha.4. Optional native read and Lab retain their two-version boundaries. [Compatibility](docs/design/dsh-compatibility.md) · [Setup](adapters/dsh/README.md) |
237
- | Codex / other hosts | Use the official coding agent for version-specific local hook setup; verify blocking before claiming native interception. Without a blocking hook, explicit Skill/CLI remains cooperative. [Adaptation guide](adapters/INTEGRATION.md) |
261
+ | Codex | Codex 0.165.0 exercised published 0.2.7 through actual-client and real-model MCP trials. This covers explicit tools; native Shell/editor interception needs separate verification. [MCP evidence and limits](docs/guides/mcp.md#codex-01650-with-published-027) |
262
+ | Other hosts | Use the official coding agent for version-specific local setup; verify blocking before claiming native interception. Explicit Skill/CLI/MCP use remains cooperative without a blocking hook. [Adaptation guide](adapters/INTEGRATION.md) |
238
263
 
239
264
  Use the [full capability and evidence matrix](docs/guides/harness-capabilities.md)
240
265
  for precise versions, tests and gaps. `doctor.py kimi|claude --probe` checks a
@@ -264,7 +289,7 @@ reconstruction and known gaps. It cannot recreate bytes that no source kept.
264
289
  | [Threat model](docs/design/threat-model.md) | Trust assumptions and unresolved boundaries |
265
290
  | [Compatibility](docs/design/compatibility.md) | Interface and release contracts |
266
291
  | [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 |
292
+ | [0.2.8 notes](docs/releases/release-notes-0.2.8.md) | Version scope, upgrade impact and validation boundaries |
268
293
 
269
294
  ## Contributing
270
295
 
package/README.zh-CN.md CHANGED
@@ -4,13 +4,13 @@
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.8](https://img.shields.io/badge/release-0.2.8-5B6B7A)](docs/releases/release-notes-0.2.8.md)
8
8
 
9
- **让 AI Agent 的破坏性操作默认可逆。** · [English](README.md)
9
+ **外发检查 · 可恢复删除 · Agent 验测** · [English](README.md)
10
10
 
11
- Agent Guard 在受支持的删除、覆盖操作前保留恢复数据,检查待外发文本中的
12
- 敏感信息,并提供 Lab 来测试 Agent 和宿主的实际行为。共享 Python Core
13
- 可通过命令行工具或宿主适配器调用。
11
+ Agent Guard 提供三大功能:**Exfil-guard** 检查待外发文本,**Delete-guard**
12
+ 在受支持的破坏性操作前保留恢复数据,**Guard-lab** 通过受控实验测试 Agent
13
+ 和宿主的实际行为。共享 Python Core 支撑命令行工具与可选宿主适配器。
14
14
 
15
15
  **负责接入本项目的 AI agent:** 修改配置或编写桥接前,必须先读取
16
16
  [适配要求](adapters/INTEGRATION.md),再阅读
@@ -21,15 +21,26 @@ Agent Guard 在受支持的删除、覆盖操作前保留恢复数据,检查
21
21
  目前主要维护 **DSH 和 Kimi Code** 的接入。其他宿主建议交给对应的官方
22
22
  编码 Agent 在本地配置。
23
23
 
24
- | 能力 | 能帮助你做什么 | 入口 |
24
+ 本版 **[0.2.8](docs/releases/release-notes-0.2.8.md)** 提供 MCP 接入诊断与恢复验证,
25
+ 在 [0.2.7](docs/releases/release-notes-0.2.7.md) 已有的 Cleanup 计划、删除准入限制与
26
+ 可选本地 MCP 工具基础上完善。安装前,请通过下方链接核实精确版本的
27
+ GitHub Release 与 npm 包是否可用。
28
+
29
+ | 主要功能 | 下属功能 | 对应链接 |
25
30
  |---|---|---|
26
- | **恢复保护** | 删除前迁移有价值的文件;受支持的 Git 覆盖前快照 tracked 状态;查询和恢复事务 | [delete-guard](skills/delete-guard/SKILL.md) |
27
- | **外发检测** | 检测受支持的凭据和本机标识路径;应用脱敏计划或拒绝输出 | [exfil-guard](skills/exfil-guard/SKILL.md) |
28
- | **行为验测** | 校准观察器,验证声明信道的暴露,再比较匹配的关闭/开启防护试次 | [guard-lab](docs/lab/guard-lab.md) |
31
+ | **Exfil-guard** | 受支持的凭据与标识路径检测;脱敏计划与执行;不展示标量值的 JSON/dotenv 配置结构视图 | [Skill 与 CLI](skills/exfil-guard/SKILL.md) · [检测规则](skills/exfil-guard/references/rules.md) · [安全配置视图](skills/exfil-guard/SKILL.md#safe-config-view) |
32
+ | **Delete-guard** | 可恢复删除与受支持的 Git 快照;Cleanup Copilot;持久预算、速率/重复限制、保护路径与批量确认;事务恢复与手动 GC;可选本地 MCP 工具及接入诊断 | [Skill 与 CLI](skills/delete-guard/SKILL.md) · [Cleanup Copilot](docs/guides/cleanup-plan.md) · [删除限制](docs/guides/deletion-limits.md) · [恢复与 GC](docs/guides/recovery-feedback.md) · [MCP 工具](docs/guides/mcp.md) · [MCP doctor(0.2.8)](docs/guides/mcp.md#diagnose-a-local-service-028) |
33
+ | **Guard-lab** | 四项零模型校准对照;合成标记与声明信道观察;证据和观察器健康检查;有效基线成立后的关闭/开启防护配对比较 | [Lab 流程](docs/lab/guard-lab.md) · [四控制示例](docs/lab/blue-team-calibration.md) · [证据等级](docs/lab/guard-lab.md#evidence-levels) |
34
+
35
+ Cleanup Copilot、删除限制以及当前 MCP 工具/doctor 均归属 **Delete-guard**。
36
+ Core 与适配器提供共享基础设施;[recovery-audit](skills/recovery-audit/SKILL.md)
37
+ 提供事故后的工作区重建与恢复审计辅助流程。
29
38
 
30
39
  Skill 提供操作纪律,不会自行拦截工具调用。自动保护依赖宿主实际加载了
31
40
  兼容 hook,且调用位于其覆盖范围内。Agent Guard 不是抵抗同权限恶意进程的
32
41
  OS 沙箱;实际接入证据和缺口见[能力矩阵](docs/guides/harness-capabilities.md)。
42
+ 可选本地 MCP 适配器提供显式工具,不会拦截绕过它的操作;其 SDK 单独安装,
43
+ 不改变 Core 的运行依赖。
33
44
 
34
45
  <a id="guard-lab-合成蜜罐"></a>
35
46
 
@@ -84,24 +95,32 @@ python3 docs/lab/examples/blue-team-calibration.py --output-dir "$blue_run/contr
84
95
 
85
96
  Core 需要 Python 3.9+ 和 Git。示例采用 POSIX Shell;原生桥接和可选采集
86
97
  工具另有运行要求。
98
+ 可选 MCP 适配器需要 Python 3.10+,并单独安装[固定版本 SDK](docs/guides/mcp.md)。
87
99
 
88
100
  | 版本 | 状态 |
89
101
  |---|---|
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) | 上一稳定版 |
102
+ | [0.2.8](docs/releases/release-notes-0.2.8.md) | 本版;安装前核实下方精确版本渠道 |
103
+ | [0.2.7](docs/releases/release-notes-0.2.7.md) | 历史版本,包含 Cleanup、删除限制与本地 MCP 工具 |
104
+ | [0.2.6](docs/releases/release-notes-0.2.6.md) | 历史已发布版本,包含 Kimi 反馈与宿主兼容性更新 |
105
+ | [0.2.5](docs/releases/release-notes-0.2.5.md) | 更早稳定版 |
92
106
  | [0.2.4](docs/releases/release-notes-0.2.4.md) | 更早稳定版 |
93
107
  | [0.2.4-hotfix.1](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.4-hotfix.1) | 显式选择的回收站保护回补;npm `hotfix` |
94
108
  | [0.2.5-rc3](docs/releases/release-notes-0.2.5-rc3.md) | 已发布预发布版,包含 RC1/RC2 维护;npm `rc` |
95
109
 
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)为准,
110
+ 安装 0.2.8 前,请通过精确版本的
111
+ [GitHub Release](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.8)和
112
+ [npm 版本页](https://www.npmjs.com/package/@mokuyoaxis/agent-guard/v/0.2.8)确认可用性,
99
113
  checkout 或 manifest 本身不代表包已可安装。
100
114
 
101
- 稳定包可安装到用户选定的长期目录:
115
+ 若该版本尚不可用,请按[版本说明](docs/releases/release-notes-0.2.8.md)使用经复核的
116
+ 源码或本地构建 tarball。版本化测试和包核验保留各自检查点。
117
+ 自 0.2.7 引入的[准入限制](docs/guides/deletion-limits.md)可能拒绝此前可执行的删除,
118
+ 这些限制在 0.2.8 中继续生效。
119
+
120
+ 确认精确版本可用后,可安装到用户选定的长期目录:
102
121
 
103
122
  ```sh
104
- npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.6
123
+ npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.8
105
124
  ```
106
125
 
107
126
  包根目录是
@@ -123,7 +142,7 @@ cd agent-guard
123
142
  恢复反馈、独立 Stop doctor 检查、DSH Lab 预检诊断、DSH `0.2.1-alpha.4` 默认删除适配,
124
143
  以及 Kimi `2.3.0` Bash profile。已有安装需要升级才能取得这些功能,Stop 还需显式配置。
125
144
  接入步骤与 Agent 提示词见[入门指南](docs/guides/getting-started.md),
126
- 功能边界见[维护说明](docs/releases/unreleased.md)。
145
+ 历史功能边界见[0.2.6 说明](docs/releases/release-notes-0.2.6.md)。
127
146
 
128
147
  ## 恢复一次受支持的删除
129
148
 
@@ -202,7 +221,8 @@ python3 -c 'print("config: sk-proj-" + "AbCdEf0123456789GhIjKl")' |
202
221
  | Claude Code | 保留参考实现,暂缓新版本验收。Bash 原生 `PreToolUse`;2.1.270/2.1.273 的受限脚本宿主拦截记录。[接入](adapters/claude/README.md) |
203
222
  | Kimi Code | Bash 原生 `PreToolUse`;0.42.0 的有限主/子路径及 2.1.1 的根代理 Bash 记录。0.2.6 新增 2.3.0 prompt/ACP 根代理 Bash 固定响应证据。ASK 拒绝;缺失/超时 hook 不覆盖。[接入](adapters/kimi-code/README.md) |
204
223
  | DSH | 默认删除适配覆盖 0.1.5-rc.1/0.2.0-rc.2/0.2.1-alpha.4。可选原生 read 与 Lab 保留各自的两版边界。[兼容范围](docs/design/dsh-compatibility.md) · [接入](adapters/dsh/README.md) |
205
- | Codex/其他宿主 | 推荐官方 Agent 按当前版本完成本地 hook 接入,并验证确实阻止执行。没有阻塞 hook 时,Skill/CLI 仍属于协作式使用。[适配指南](adapters/INTEGRATION.md) |
224
+ | Codex | Codex 0.165.0 已通过已发布 0.2.7 的实际客户端与真实模型 MCP 试次。证据覆盖显式工具;原生 Shell/编辑器拦截仍需单独验证。[MCP 证据与限制](docs/guides/mcp.md#codex-01650-with-published-027) |
225
+ | 其他宿主 | 推荐官方 Agent 按当前版本完成本地接入,并验证确实阻止执行后再声明原生拦截。没有阻塞 hook 时,Skill/CLI/MCP 仍属于协作式使用。[适配指南](adapters/INTEGRATION.md) |
206
226
 
207
227
  精确版本、试验与缺口统一见[完整能力矩阵](docs/guides/harness-capabilities.md)。
208
228
  `doctor.py kimi|claude --probe` 只检查选定配置和本地适配路径;PASS 不证明
@@ -230,7 +250,7 @@ Git/会话/缓存证据恢复项目,区分原文、重建与确认缺失
230
250
  | [威胁模型](docs/design/threat-model.md) | 信任假设与尚未解决的边界 |
231
251
  | [兼容契约](docs/design/compatibility.md) | 接口与发布约定 |
232
252
  | [蓝队研究](docs/research/README.md) | 防守方法、去敏结果与零模型起点 |
233
- | [0.2.5 说明](docs/releases/release-notes-0.2.5.md) | 发布范围、升级影响与验证边界 |
253
+ | [0.2.8 说明](docs/releases/release-notes-0.2.8.md) | 版本范围、升级影响与验证边界 |
234
254
 
235
255
  ## 参与贡献
236
256
 
@@ -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,325 @@
1
+ """Read-only diagnostics for one explicitly selected local MCP service.
2
+
3
+ Only the selected child interpreter needs the optional SDK. This module is
4
+ stdlib-only so the ordinary doctor and its help remain usable without it.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import math
10
+ import os
11
+ from pathlib import Path
12
+ import queue
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import threading
18
+ import time
19
+
20
+
21
+ ROOT = Path(__file__).resolve().parents[2]
22
+ SERVER = ROOT / "adapters/mcp/server.py"
23
+ SDK_VERSION = "2.3.0"
24
+ PROTOCOL_VERSION = "2025-06-18"
25
+ TOOLS = frozenset(("safe_delete", "restore", "transactions", "status", "gc_plan"))
26
+ READ_ONLY = ("status", "transactions", "gc_plan")
27
+ MAX_MESSAGE_BYTES = 2 * 1024 * 1024
28
+
29
+ PROBLEMS = {
30
+ "MCP_DOCTOR_WORKSPACE": ("Select an existing non-root workspace directory.",
31
+ "Check the requested workspace path before reconnecting."),
32
+ "MCP_DOCTOR_SERVER": ("The selected server script is unavailable.",
33
+ "Select the reviewed agent-guard adapters/mcp/server.py file."),
34
+ "MCP_DOCTOR_PYTHON": ("The selected Python executable could not start.",
35
+ "Check the selected interpreter path and execution permission."),
36
+ "MCP_DOCTOR_SDK_MISSING": ("The optional MCP SDK is not installed in the selected interpreter.",
37
+ "Use a separate environment with adapters/mcp/requirements.txt."),
38
+ "MCP_DOCTOR_SDK_VERSION": ("The selected interpreter has an unsupported MCP SDK version.",
39
+ "Use the pinned SDK from adapters/mcp/requirements.txt."),
40
+ "MCP_DOCTOR_SDK_IMPORT": ("The selected interpreter could not import the MCP SDK dependencies.",
41
+ "Check that the selected SDK environment is complete and runnable."),
42
+ "MCP_DOCTOR_SDK_CHECK": ("The selected interpreter did not complete the SDK check.",
43
+ "Check the interpreter and its installed environment directly."),
44
+ "MCP_DOCTOR_STARTUP": ("The selected service could not start.",
45
+ "Check the reviewed server script and selected interpreter."),
46
+ "MCP_DOCTOR_TIMEOUT": ("The diagnostic deadline expired.",
47
+ "Inspect the failed stage and service startup; reconnect explicitly after investigation."),
48
+ "MCP_DOCTOR_EOF": ("The service closed its protocol output before completing the check.",
49
+ "Inspect the selected service startup and optional SDK environment."),
50
+ "MCP_DOCTOR_PROTOCOL": ("The service returned an invalid or unsupported protocol response.",
51
+ "Use the reviewed agent-guard stdio service; stdout must contain protocol messages only."),
52
+ "MCP_DOCTOR_IDENTITY": ("The service identity or version does not match this installation.",
53
+ "Select a server script from the same agent-guard version as this doctor."),
54
+ "MCP_DOCTOR_TOOLS": ("The service tool set or read-only annotations do not match the five-tool contract.",
55
+ "Check the selected service version and tool definitions."),
56
+ "MCP_DOCTOR_QUERY": ("A read-only tool returned an unsuccessful or invalid result.",
57
+ "Inspect the failed tool and local recovery state before any mutation."),
58
+ "MCP_DOCTOR_BINDING": ("The service status does not match the requested workspace and quarantine.",
59
+ "Correct the trusted service workspace binding before using its tools."),
60
+ }
61
+
62
+
63
+ class _Failure(Exception):
64
+ def __init__(self, code):
65
+ self.code = code
66
+
67
+
68
+ def _remaining(deadline):
69
+ remaining = deadline - time.monotonic()
70
+ if remaining <= 0:
71
+ raise _Failure("MCP_DOCTOR_TIMEOUT")
72
+ return remaining
73
+
74
+
75
+ def _environment():
76
+ env = {key: value for key, value in os.environ.items()
77
+ if not key.startswith(("AGENT_GUARD_", "GIT_"))
78
+ and key not in ("PYTHONPATH", "PYTHONHOME")}
79
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
80
+ return env
81
+
82
+
83
+ def _check_sdk(python, deadline, env, diagnostics):
84
+ # Fixed exit codes avoid exposing import exceptions, paths or environment
85
+ # contents. This is a trusted interpreter, not a sandbox for hostile code.
86
+ code = (
87
+ "import importlib.metadata, sys\n"
88
+ "try: version = importlib.metadata.version('mcp')\n"
89
+ "except importlib.metadata.PackageNotFoundError: sys.exit(10)\n"
90
+ "if version != '2.3.0': sys.exit(11)\n"
91
+ "try: import mcp.server, mcp.server.stdio, mcp_types, anyio\n"
92
+ "except (ImportError, OSError): sys.exit(12)\n"
93
+ )
94
+ try:
95
+ child = subprocess.run([python, "-B", "-c", code], cwd=ROOT, env=env,
96
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
97
+ stderr=diagnostics, timeout=_remaining(deadline), shell=False)
98
+ except subprocess.TimeoutExpired:
99
+ raise _Failure("MCP_DOCTOR_TIMEOUT") from None
100
+ except OSError:
101
+ raise _Failure("MCP_DOCTOR_PYTHON") from None
102
+ if child.returncode:
103
+ raise _Failure({10: "MCP_DOCTOR_SDK_MISSING", 11: "MCP_DOCTOR_SDK_VERSION",
104
+ 12: "MCP_DOCTOR_SDK_IMPORT"}.get(child.returncode, "MCP_DOCTOR_SDK_CHECK"))
105
+
106
+
107
+ class _Connection:
108
+ def __init__(self, python, server, workspace, env, deadline, diagnostics):
109
+ self.deadline = deadline
110
+ self.counter = 0
111
+ self.messages = queue.Queue(maxsize=8)
112
+ self.stopped = threading.Event()
113
+ try:
114
+ self.child = subprocess.Popen([python, "-B", str(server), "--workspace", str(workspace)],
115
+ cwd=workspace, env=env, stdin=subprocess.PIPE,
116
+ stdout=subprocess.PIPE, stderr=diagnostics, shell=False)
117
+ except OSError:
118
+ raise _Failure("MCP_DOCTOR_STARTUP") from None
119
+
120
+ def enqueue(value):
121
+ while not self.stopped.is_set():
122
+ try:
123
+ self.messages.put(value, timeout=0.1)
124
+ return
125
+ except queue.Full:
126
+ continue
127
+
128
+ def read():
129
+ while not self.stopped.is_set():
130
+ line = self.child.stdout.readline(MAX_MESSAGE_BYTES + 1)
131
+ if not line:
132
+ enqueue(_Failure("MCP_DOCTOR_EOF"))
133
+ return
134
+ if len(line) > MAX_MESSAGE_BYTES or not line.endswith(b"\n"):
135
+ enqueue(_Failure("MCP_DOCTOR_PROTOCOL"))
136
+ return
137
+ try:
138
+ value = json.loads(line.decode("utf-8"))
139
+ except (UnicodeError, ValueError, RecursionError):
140
+ enqueue(_Failure("MCP_DOCTOR_PROTOCOL"))
141
+ return
142
+ enqueue(value)
143
+
144
+ self.reader = threading.Thread(target=read, daemon=True)
145
+ self.reader.start()
146
+
147
+ def send(self, value):
148
+ _remaining(self.deadline)
149
+ try:
150
+ self.child.stdin.write((json.dumps(value) + "\n").encode("utf-8"))
151
+ self.child.stdin.flush()
152
+ except (OSError, ValueError):
153
+ raise _Failure("MCP_DOCTOR_EOF") from None
154
+
155
+ def request(self, method, params):
156
+ self.counter += 1
157
+ self.send({"jsonrpc": "2.0", "id": self.counter, "method": method, "params": params})
158
+ # The selected service does not need client-side tools, sampling or
159
+ # approval. Notifications may occur but cannot extend the deadline.
160
+ for _ in range(32):
161
+ try:
162
+ value = self.messages.get(timeout=_remaining(self.deadline))
163
+ except queue.Empty:
164
+ raise _Failure("MCP_DOCTOR_TIMEOUT") from None
165
+ if isinstance(value, _Failure):
166
+ raise value
167
+ if not isinstance(value, dict) or value.get("jsonrpc") != "2.0":
168
+ raise _Failure("MCP_DOCTOR_PROTOCOL")
169
+ if "id" not in value and isinstance(value.get("method"), str):
170
+ if value["method"].startswith("notifications/"):
171
+ continue
172
+ if type(value.get("id")) is not int or value["id"] != self.counter or "error" in value:
173
+ raise _Failure("MCP_DOCTOR_PROTOCOL")
174
+ if "method" in value or not isinstance(value.get("result"), dict):
175
+ raise _Failure("MCP_DOCTOR_PROTOCOL")
176
+ return value["result"]
177
+ raise _Failure("MCP_DOCTOR_PROTOCOL")
178
+
179
+ def close(self):
180
+ self.stopped.set()
181
+ try:
182
+ self.child.stdin.close()
183
+ except OSError:
184
+ pass
185
+ try:
186
+ self.child.wait(timeout=1)
187
+ except subprocess.TimeoutExpired:
188
+ self.child.terminate()
189
+ try:
190
+ self.child.wait(timeout=1)
191
+ except subprocess.TimeoutExpired:
192
+ self.child.kill()
193
+ self.child.wait(timeout=1)
194
+ self.child.stdout.close()
195
+ self.reader.join(timeout=1)
196
+
197
+
198
+ def _tool_result(value, name):
199
+ content = value.get("structuredContent")
200
+ if (value.get("isError", False) is not False or not isinstance(content, dict)
201
+ or content.get("tool") != name or content.get("ok") is not True
202
+ or type(content.get("exit_code")) is not int or content["exit_code"] != 0
203
+ or not isinstance(content.get("result"), dict)):
204
+ raise _Failure("MCP_DOCTOR_QUERY")
205
+ return content["result"]
206
+
207
+
208
+ def diagnose(python, workspace, *, server=None, timeout=30):
209
+ """Check a trusted local service, without returning its private responses.
210
+
211
+ ``timeout`` is the total diagnostic deadline (5..120 seconds); closing
212
+ this invocation's own service can add three seconds of process waits
213
+ and one second waiting for its reader thread.
214
+ Python paths retain their symlink spelling so virtual environments work.
215
+ """
216
+ if type(timeout) not in (int, float) or not math.isfinite(timeout) or not 5 <= timeout <= 120:
217
+ raise ValueError("MCP doctor timeout must be from 5 to 120 seconds")
218
+ python = os.fspath(python)
219
+ if not python or "\0" in python:
220
+ raise ValueError("MCP doctor needs a nonempty interpreter")
221
+ python = os.path.expanduser(python)
222
+ if os.path.dirname(python):
223
+ python = os.path.abspath(python)
224
+ else:
225
+ python = shutil.which(python) or python
226
+ expected_version = json.loads((ROOT / "package.json").read_text(encoding="utf-8"))["version"]
227
+ report = {"schema_version": 1, "harness": "mcp", "status": "FAIL", "stage": "workspace",
228
+ "checks": [], "host_connection": "UNVERIFIED", "model_delivery": "UNVERIFIED",
229
+ "host_interception": "UNVERIFIED"}
230
+ stage = "workspace"
231
+ connection = None
232
+ deadline = time.monotonic() + timeout
233
+ with tempfile.TemporaryFile() as diagnostics:
234
+ try:
235
+ try:
236
+ selected = Path(workspace).expanduser().resolve(strict=True)
237
+ valid = selected.is_dir() and selected.parent != selected
238
+ except (OSError, ValueError):
239
+ valid = False
240
+ if not valid:
241
+ raise _Failure("MCP_DOCTOR_WORKSPACE")
242
+ report["checks"].append({"stage": stage, "status": "PASS"})
243
+ stage = "server"
244
+ try:
245
+ selected_server = Path(server if server is not None else SERVER).expanduser().absolute()
246
+ valid = selected_server.is_file()
247
+ except (OSError, ValueError):
248
+ valid = False
249
+ if not valid:
250
+ raise _Failure("MCP_DOCTOR_SERVER")
251
+ report["checks"].append({"stage": stage, "status": "PASS"})
252
+ env = _environment()
253
+ stage = "sdk"
254
+ _check_sdk(python, deadline, env, diagnostics)
255
+ report["sdk_version"] = SDK_VERSION
256
+ report["checks"].append({"stage": stage, "status": "PASS"})
257
+ stage = "initialize"
258
+ connection = _Connection(python, selected_server, selected, env, deadline, diagnostics)
259
+ initialized = connection.request("initialize", {"protocolVersion": PROTOCOL_VERSION,
260
+ "capabilities": {}, "clientInfo": {"name": "agent-guard-doctor", "version": expected_version}})
261
+ identity = initialized.get("serverInfo")
262
+ if (not isinstance(identity, dict) or identity.get("name") != "agent-guard"
263
+ or identity.get("version") != expected_version):
264
+ raise _Failure("MCP_DOCTOR_IDENTITY")
265
+ if initialized.get("protocolVersion") != PROTOCOL_VERSION:
266
+ raise _Failure("MCP_DOCTOR_PROTOCOL")
267
+ connection.send({"jsonrpc": "2.0", "method": "notifications/initialized"})
268
+ report["server"] = {"name": "agent-guard", "version": expected_version,
269
+ "protocol_version": PROTOCOL_VERSION}
270
+ report["checks"].append({"stage": stage, "status": "PASS"})
271
+ stage = "tools"
272
+ listing = connection.request("tools/list", {})
273
+ tools = listing.get("tools")
274
+ if (not isinstance(tools, list) or len(tools) != len(TOOLS)
275
+ or any(not isinstance(tool, dict) or not isinstance(tool.get("name"), str) for tool in tools)
276
+ or {tool["name"] for tool in tools} != TOOLS or listing.get("nextCursor") is not None):
277
+ raise _Failure("MCP_DOCTOR_TOOLS")
278
+ for tool in tools:
279
+ annotations = tool.get("annotations")
280
+ if (not isinstance(annotations, dict) or
281
+ annotations.get("readOnlyHint") is not (tool["name"] in READ_ONLY)):
282
+ raise _Failure("MCP_DOCTOR_TOOLS")
283
+ report["tools"] = sorted(TOOLS)
284
+ report["checks"].append({"stage": stage, "status": "PASS"})
285
+ for name in READ_ONLY:
286
+ stage = name
287
+ result = _tool_result(connection.request("tools/call", {
288
+ "name": name, "arguments": {"tail": 0} if name == "status" else {}}), name)
289
+ if name == "status":
290
+ if (result.get("workspace") != str(selected)
291
+ or result.get("trash_root") != str(selected / ".agent-trash")):
292
+ raise _Failure("MCP_DOCTOR_BINDING")
293
+ admission = result.get("delete_admission")
294
+ if not isinstance(admission, dict):
295
+ raise _Failure("MCP_DOCTOR_QUERY")
296
+ report["deletion_admission"] = "BLOCKED" if admission.get("status") == "BLOCKED" else "READABLE"
297
+ elif name == "transactions" and not isinstance(result.get("transactions"), list):
298
+ raise _Failure("MCP_DOCTOR_QUERY")
299
+ elif name == "gc_plan" and (result.get("mode") != "plan" or not isinstance(result.get("eligible"), list)):
300
+ raise _Failure("MCP_DOCTOR_QUERY")
301
+ report["checks"].append({"stage": stage, "status": "PASS"})
302
+ report.update(status="PASS", stage="complete", code="MCP_DOCTOR_READY",
303
+ message="The selected local service passed handshake, binding and read-only tool checks.",
304
+ guidance="Inspect the actual client's MCP connection and permissions before using its tools.")
305
+ except _Failure as failure:
306
+ message, guidance = PROBLEMS[failure.code]
307
+ report.update(stage=stage, code=failure.code, message=message, guidance=guidance)
308
+ report["checks"].append({"stage": stage, "status": "FAIL", "code": failure.code})
309
+ finally:
310
+ if connection is not None:
311
+ connection.close()
312
+ diagnostics.flush()
313
+ report["diagnostic_stderr_bytes"] = diagnostics.tell()
314
+ return report
315
+
316
+
317
+ def render(report):
318
+ """Render only fixed report fields; private MCP tool content is absent."""
319
+ lines = [report["status"] + ": " + report["code"], report["message"]]
320
+ lines.extend(" " + check["stage"] + ": " + check["status"] for check in report["checks"])
321
+ if report.get("deletion_admission") == "BLOCKED":
322
+ lines.append("DELETION_ADMISSION: BLOCKED (connection checks do not grant deletion permission)")
323
+ lines.extend([report["guidance"],
324
+ "HOST_CONNECTION: UNVERIFIED; MODEL_DELIVERY: UNVERIFIED; HOST_INTERCEPTION: UNVERIFIED"])
325
+ return "\n".join(lines) + "\n"