@mokuyoaxis/agent-guard 0.2.7 → 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.
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.7](https://img.shields.io/badge/version-0.2.7-5B6B7A)](docs/releases/release-notes-0.2.7.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,18 +24,22 @@ 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
- 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.
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.
29
32
 
30
- | Capability | What it helps you do | Entry |
33
+ | Main capability | Included functions | Guides |
31
34
  |---|---|---|
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) |
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) |
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) |
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.
38
43
 
39
44
  A Skill supplies instructions; it does not intercept tool calls. Automatic
40
45
  protection depends on an active, compatible host hook and its covered tools.
@@ -112,28 +117,29 @@ The optional MCP adapter requires Python 3.10+ and a separately installed
112
117
 
113
118
  | Version | Status |
114
119
  |---|---|
115
- | [0.2.7](docs/releases/release-notes-0.2.7.md) | Version documented here; verify exact-version availability below |
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 |
116
122
  | [0.2.6](docs/releases/release-notes-0.2.6.md) | Earlier published release with Kimi feedback and host compatibility updates |
117
123
  | [0.2.5](docs/releases/release-notes-0.2.5.md) | Earlier stable release |
118
124
  | [0.2.4](docs/releases/release-notes-0.2.4.md) | Earlier stable release |
119
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` |
120
126
  | [0.2.5-rc3](docs/releases/release-notes-0.2.5-rc3.md) | Published prerelease, including RC1/RC2 maintenance; npm `rc` |
121
127
 
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).
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).
125
131
  A checkout or manifest alone does not establish package availability.
126
132
 
127
133
  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).
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.
132
138
 
133
139
  Once the exact version is available, install to a chosen, stable user-owned prefix:
134
140
 
135
141
  ```sh
136
- npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.7
142
+ npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.8
137
143
  ```
138
144
 
139
145
  The package root is
@@ -252,7 +258,8 @@ tool paths. Other combinations need their own checks.
252
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) |
253
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) |
254
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) |
255
- | 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) |
256
263
 
257
264
  Use the [full capability and evidence matrix](docs/guides/harness-capabilities.md)
258
265
  for precise versions, tests and gaps. `doctor.py kimi|claude --probe` checks a
@@ -282,7 +289,7 @@ reconstruction and known gaps. It cannot recreate bytes that no source kept.
282
289
  | [Threat model](docs/design/threat-model.md) | Trust assumptions and unresolved boundaries |
283
290
  | [Compatibility](docs/design/compatibility.md) | Interface and release contracts |
284
291
  | [Blue-team research](docs/research/README.md) | Defensive methods, sanitized results and a zero-model starting point |
285
- | [0.2.7 notes](docs/releases/release-notes-0.2.7.md) | Version 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 |
286
293
 
287
294
  ## Contributing
288
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.7](https://img.shields.io/badge/version-0.2.7-5B6B7A)](docs/releases/release-notes-0.2.7.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,17 +21,20 @@ 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 工具。安装前请通过下方精确版本渠道确认可用性。
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 包是否可用。
26
28
 
27
- | 能力 | 能帮助你做什么 | 入口 |
29
+ | 主要功能 | 下属功能 | 对应链接 |
28
30
  |---|---|---|
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) |
33
- | **外发检测** | 检测受支持的凭据和本机标识路径;应用脱敏计划或拒绝输出 | [exfil-guard](skills/exfil-guard/SKILL.md) |
34
- | **行为验测** | 校准观察器,验证声明信道的暴露,再比较匹配的关闭/开启防护试次 | [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
+ 提供事故后的工作区重建与恢复审计辅助流程。
35
38
 
36
39
  Skill 提供操作纪律,不会自行拦截工具调用。自动保护依赖宿主实际加载了
37
40
  兼容 hook,且调用位于其覆盖范围内。Agent Guard 不是抵抗同权限恶意进程的
@@ -96,26 +99,28 @@ Core 需要 Python 3.9+ 和 Git。示例采用 POSIX Shell;原生桥接和可
96
99
 
97
100
  | 版本 | 状态 |
98
101
  |---|---|
99
- | [0.2.7](docs/releases/release-notes-0.2.7.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 工具 |
100
104
  | [0.2.6](docs/releases/release-notes-0.2.6.md) | 历史已发布版本,包含 Kimi 反馈与宿主兼容性更新 |
101
105
  | [0.2.5](docs/releases/release-notes-0.2.5.md) | 更早稳定版 |
102
106
  | [0.2.4](docs/releases/release-notes-0.2.4.md) | 更早稳定版 |
103
107
  | [0.2.4-hotfix.1](https://github.com/mokuyoaxis/agent-guard/releases/tag/0.2.4-hotfix.1) | 显式选择的回收站保护回补;npm `hotfix` |
104
108
  | [0.2.5-rc3](docs/releases/release-notes-0.2.5-rc3.md) | 已发布预发布版,包含 RC1/RC2 维护;npm `rc` |
105
109
 
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)确认可用性,
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)确认可用性,
109
113
  checkout 或 manifest 本身不代表包已可安装。
110
114
 
111
- 若该版本尚不可用,请按[版本说明](docs/releases/release-notes-0.2.7.md)使用经复核的
112
- 源码或本地构建 tarball。版本化测试和包核验已单独记录,不能沿用旧 0.2.6 元数据
113
- 候选的通过结论。此前可执行的删除可能被新的[准入限制](docs/guides/deletion-limits.md)拒绝。
115
+ 若该版本尚不可用,请按[版本说明](docs/releases/release-notes-0.2.8.md)使用经复核的
116
+ 源码或本地构建 tarball。版本化测试和包核验保留各自检查点。
117
+ 自 0.2.7 引入的[准入限制](docs/guides/deletion-limits.md)可能拒绝此前可执行的删除,
118
+ 这些限制在 0.2.8 中继续生效。
114
119
 
115
120
  确认精确版本可用后,可安装到用户选定的长期目录:
116
121
 
117
122
  ```sh
118
- npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.7
123
+ npm install --prefix /absolute/path/to/agent-guard-install @mokuyoaxis/agent-guard@0.2.8
119
124
  ```
120
125
 
121
126
  包根目录是
@@ -216,7 +221,8 @@ python3 -c 'print("config: sk-proj-" + "AbCdEf0123456789GhIjKl")' |
216
221
  | Claude Code | 保留参考实现,暂缓新版本验收。Bash 原生 `PreToolUse`;2.1.270/2.1.273 的受限脚本宿主拦截记录。[接入](adapters/claude/README.md) |
217
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) |
218
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) |
219
- | 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) |
220
226
 
221
227
  精确版本、试验与缺口统一见[完整能力矩阵](docs/guides/harness-capabilities.md)。
222
228
  `doctor.py kimi|claude --probe` 只检查选定配置和本地适配路径;PASS 不证明
@@ -244,7 +250,7 @@ Git/会话/缓存证据恢复项目,区分原文、重建与确认缺失
244
250
  | [威胁模型](docs/design/threat-model.md) | 信任假设与尚未解决的边界 |
245
251
  | [兼容契约](docs/design/compatibility.md) | 接口与发布约定 |
246
252
  | [蓝队研究](docs/research/README.md) | 防守方法、去敏结果与零模型起点 |
247
- | [0.2.7 说明](docs/releases/release-notes-0.2.7.md) | 版本范围、升级影响与验证边界 |
253
+ | [0.2.8 说明](docs/releases/release-notes-0.2.8.md) | 版本范围、升级影响与验证边界 |
248
254
 
249
255
  ## 参与贡献
250
256
 
@@ -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"