@mokuyoaxis/agent-guard 0.2.5 → 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 +61 -23
- package/README.zh-CN.md +51 -22
- package/adapters/INTEGRATION.md +90 -10
- package/adapters/claude/README.md +6 -0
- package/adapters/dsh/README.md +19 -8
- package/adapters/dsh/compatibility.json +14 -0
- package/adapters/dsh/harness/README.md +11 -0
- package/adapters/dsh/harness/guard_lab.py +42 -14
- package/adapters/kimi-code/README.md +154 -14
- package/adapters/kimi-code/compatibility.json +1 -1
- package/adapters/kimi-code/config.example.toml +18 -6
- package/adapters/kimi-code/hook_bridge.sh +19 -4
- package/adapters/kimi-code/pre_tool_use.py +1 -1
- package/adapters/kimi-code/stop_feedback.py +237 -0
- package/adapters/mcp/__init__.py +1 -0
- package/adapters/mcp/operations.py +174 -0
- package/adapters/mcp/requirements.txt +3 -0
- package/adapters/mcp/server.py +126 -0
- package/core/admission.py +388 -0
- package/core/audit.py +1 -1
- package/core/classifier.py +2 -1
- package/core/cleanup.py +297 -0
- package/core/delete_config.py +153 -0
- package/core/policy.py +35 -7
- package/core/recovery.py +10 -0
- package/docs/README.md +25 -7
- package/docs/design/architecture.md +16 -4
- package/docs/design/compatibility.md +230 -6
- package/docs/design/dsh-compatibility.md +65 -0
- package/docs/design/threat-model.md +53 -1
- package/docs/guides/cleanup-plan.md +227 -0
- package/docs/guides/deletion-limits.md +150 -0
- package/docs/guides/getting-started.md +72 -11
- package/docs/guides/harness-capabilities.md +37 -4
- package/docs/guides/host-drift.md +32 -0
- package/docs/guides/mcp.md +293 -0
- package/docs/guides/recovery-feedback.md +29 -1
- package/docs/history/friction.md +99 -1
- package/docs/releases/release-notes-0.2.6.md +167 -0
- package/docs/releases/release-notes-0.2.7.md +217 -0
- package/docs/releases/unreleased.md +275 -0
- package/docs/reports/test-report-dsh-alpha4.md +102 -0
- package/docs/reports/test-report-dsh-paired-lab.md +1 -1
- package/docs/reports/test-report-kimi-code-block.md +120 -7
- package/doctor.py +175 -28
- package/package.json +13 -2
- package/skills/delete-guard/SKILL.md +69 -1
- package/skills/delete-guard/references/policy.md +66 -3
- package/skills/delete-guard/scripts/check.py +39 -9
- package/skills/delete-guard/scripts/cleanup.py +164 -0
- package/skills/delete-guard/scripts/safe_delete.py +22 -4
- package/skills/delete-guard/scripts/status.py +77 -1
|
@@ -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,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())
|