intentguard-mcp 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ """IntentGuard runtime security components."""
2
+
intentguard/cli.py ADDED
@@ -0,0 +1,260 @@
1
+ """IntentGuard command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import sqlite3
8
+ import sys
9
+ import uuid
10
+ from pathlib import Path
11
+
12
+ from intentguard.config_installer import install_config, uninstall_config
13
+ from intentguard.engine.policy_engine import PolicyEngine
14
+ from intentguard.engine.provenance import ProvenanceTracker
15
+ from intentguard.hitl.dashboard import DashboardApprovalClient, DashboardServer
16
+ from intentguard.proxy.mcp_stdio import run_stdio_proxy
17
+ from intentguard.storage.audit_db import AuditDB
18
+
19
+
20
+ def _audit_command(database_path: Path, limit: int) -> int:
21
+ try:
22
+ with AuditDB(database_path) as database:
23
+ for record in reversed(database.recent(limit)):
24
+ print(
25
+ f"{record.timestamp} session={record.session_id} "
26
+ f"tool={record.tool_name} decision={record.decision} "
27
+ f"state={record.session_state} reason={record.reason}"
28
+ )
29
+ except (OSError, sqlite3.Error, ValueError) as error:
30
+ print(f"IntentGuard audit failed: {error}", file=sys.stderr)
31
+ return 1
32
+ return 0
33
+
34
+
35
+ def _audit_verify_command(database_path: Path) -> int:
36
+ try:
37
+ if not database_path.is_file():
38
+ raise FileNotFoundError(
39
+ f"Audit database does not exist: {database_path}"
40
+ )
41
+ with AuditDB(database_path) as database:
42
+ result = database.verify_audit_chain()
43
+ if result["valid"]:
44
+ print(
45
+ "Audit chain valid: "
46
+ f"{result['verified_rows']} hash-chained rows verified; "
47
+ f"{result['legacy_rows']} legacy rows."
48
+ )
49
+ return 0
50
+ print(
51
+ f"Audit chain invalid at row id {result['broken_at_id']}: "
52
+ f"{result['error']}",
53
+ file=sys.stderr,
54
+ )
55
+ return 1
56
+ except (OSError, sqlite3.Error, ValueError) as error:
57
+ print(f"IntentGuard audit verification failed: {error}", file=sys.stderr)
58
+ return 1
59
+
60
+
61
+ async def _run_wrap(
62
+ target: list[str],
63
+ workspace: Path,
64
+ database_path: Path,
65
+ dashboard_port: int | None,
66
+ server_name: str | None = None,
67
+ policy_path: Path | None = None,
68
+ ) -> int:
69
+ dashboard = (
70
+ DashboardServer(database_path, port=dashboard_port)
71
+ if dashboard_port is not None
72
+ else None
73
+ )
74
+ if dashboard is not None:
75
+ await dashboard.start()
76
+ try:
77
+ with AuditDB(database_path) as database:
78
+ engine = PolicyEngine(workspace, policy_path=policy_path)
79
+ provenance = ProvenanceTracker(workspace, database)
80
+ approval_client = (
81
+ DashboardApprovalClient(
82
+ dashboard.port,
83
+ dashboard.hub.csrf_token,
84
+ )
85
+ if dashboard is not None
86
+ else None
87
+ )
88
+ return await run_stdio_proxy(
89
+ target,
90
+ engine,
91
+ str(workspace),
92
+ database,
93
+ provenance,
94
+ scope=str(uuid.uuid4()),
95
+ event_publisher=(
96
+ dashboard.hub.publish_event if dashboard is not None else None
97
+ ),
98
+ dashboard_approval=approval_client,
99
+ server_name=server_name,
100
+ )
101
+ finally:
102
+ if dashboard is not None:
103
+ await dashboard.stop()
104
+
105
+
106
+ def main(argv: list[str] | None = None) -> int:
107
+ arguments = list(sys.argv[1:] if argv is None else argv)
108
+ if arguments and arguments[0] == "wrap":
109
+ wrap_parser = argparse.ArgumentParser(prog="intentguard wrap")
110
+ wrap_parser.add_argument(
111
+ "--dashboard",
112
+ nargs="?",
113
+ const=8765,
114
+ default=None,
115
+ type=int,
116
+ metavar="PORT",
117
+ help="Run the local monitoring dashboard (default port 8765).",
118
+ )
119
+ wrap_parser.add_argument(
120
+ "--server-name",
121
+ help="Readable name for this wrapped MCP server.",
122
+ )
123
+ wrap_parser.add_argument(
124
+ "--policy",
125
+ type=Path,
126
+ help="Policy YAML file to load instead of the default policy.",
127
+ )
128
+ wrap_parser.add_argument(
129
+ "--db",
130
+ type=Path,
131
+ help="SQLite audit database path.",
132
+ )
133
+ try:
134
+ separator = arguments.index("--")
135
+ except ValueError:
136
+ if any(argument in {"-h", "--help"} for argument in arguments[1:]):
137
+ wrap_parser.print_help()
138
+ return 0
139
+ print(
140
+ "Usage: intentguard wrap [--dashboard [PORT]] "
141
+ "[--server-name NAME] [--policy PATH] [--db PATH] "
142
+ "-- <target_command> [arguments...]",
143
+ file=sys.stderr,
144
+ )
145
+ return 2
146
+ if any(
147
+ argument in {"-h", "--help"}
148
+ for argument in arguments[1:separator]
149
+ ):
150
+ wrap_parser.print_help()
151
+ return 0
152
+ wrap_options = wrap_parser.parse_args(arguments[1:separator])
153
+ target = arguments[separator + 1 :]
154
+ if not target:
155
+ print("A target MCP server command is required after '--'.", file=sys.stderr)
156
+ return 2
157
+ workspace = Path.cwd()
158
+ database_path = (
159
+ wrap_options.db
160
+ if wrap_options.db is not None
161
+ else workspace / ".intentguard" / "audit.sqlite3"
162
+ )
163
+ try:
164
+ run_args = (
165
+ target,
166
+ workspace,
167
+ database_path,
168
+ wrap_options.dashboard,
169
+ wrap_options.server_name,
170
+ )
171
+ if wrap_options.policy is None:
172
+ coroutine = _run_wrap(*run_args)
173
+ else:
174
+ coroutine = _run_wrap(*run_args, policy_path=wrap_options.policy)
175
+ return asyncio.run(
176
+ coroutine
177
+ )
178
+ except (OSError, RuntimeError, sqlite3.Error, ValueError) as error:
179
+ print(f"IntentGuard wrap failed: {error}", file=sys.stderr)
180
+ return 1
181
+
182
+ parser = argparse.ArgumentParser(prog="intentguard")
183
+ subparsers = parser.add_subparsers(dest="subcommand", required=True)
184
+ audit_parser = subparsers.add_parser("audit", help="List recent policy decisions.")
185
+ audit_parser.add_argument(
186
+ "--db",
187
+ type=Path,
188
+ default=Path(".intentguard") / "audit.sqlite3",
189
+ help="SQLite audit database path.",
190
+ )
191
+ audit_parser.add_argument("--limit", type=int, default=20)
192
+ audit_actions = audit_parser.add_subparsers(dest="audit_action")
193
+ verify_parser = audit_actions.add_parser(
194
+ "verify", help="Verify the cryptographic audit hash chain."
195
+ )
196
+ verify_parser.add_argument(
197
+ "--db",
198
+ type=Path,
199
+ default=Path(".intentguard") / "audit.sqlite3",
200
+ help="SQLite audit database path.",
201
+ )
202
+ install_parser = subparsers.add_parser(
203
+ "install", help="Wrap servers in an MCP client configuration."
204
+ )
205
+ install_parser.add_argument("--config", type=Path, required=True)
206
+ install_parser.add_argument("--policy", type=Path)
207
+ install_parser.add_argument("--db", type=Path)
208
+ install_parser.add_argument("--intentguard-bin", default="intentguard")
209
+ uninstall_parser = subparsers.add_parser(
210
+ "uninstall", help="Restore MCP server commands in a client configuration."
211
+ )
212
+ uninstall_parser.add_argument("--config", type=Path, required=True)
213
+ dashboard_parser = subparsers.add_parser(
214
+ "dashboard", help="Run the local security monitoring dashboard."
215
+ )
216
+ dashboard_parser.add_argument("--port", type=int, default=8765)
217
+ dashboard_parser.add_argument(
218
+ "--db",
219
+ type=Path,
220
+ default=Path(".intentguard") / "audit.sqlite3",
221
+ help="SQLite audit database path.",
222
+ )
223
+ parsed = parser.parse_args(arguments)
224
+ if parsed.subcommand == "audit":
225
+ if parsed.audit_action == "verify":
226
+ return _audit_verify_command(parsed.db)
227
+ if parsed.limit < 1:
228
+ parser.error("--limit must be a positive integer.")
229
+ return _audit_command(parsed.db, parsed.limit)
230
+ if parsed.subcommand == "install":
231
+ try:
232
+ changed = install_config(
233
+ parsed.config,
234
+ policy_path=parsed.policy,
235
+ database_path=parsed.db,
236
+ intentguard_bin=parsed.intentguard_bin,
237
+ )
238
+ except (OSError, ValueError) as error:
239
+ print(f"IntentGuard install failed: {error}", file=sys.stderr)
240
+ return 1
241
+ print(f"IntentGuard installed for {changed} MCP server(s).")
242
+ return 0
243
+ if parsed.subcommand == "uninstall":
244
+ try:
245
+ changed = uninstall_config(parsed.config)
246
+ except (OSError, ValueError) as error:
247
+ print(f"IntentGuard uninstall failed: {error}", file=sys.stderr)
248
+ return 1
249
+ print(f"IntentGuard removed from {changed} MCP server(s).")
250
+ return 0
251
+ try:
252
+ asyncio.run(DashboardServer(parsed.db, port=parsed.port).serve())
253
+ except (OSError, RuntimeError, ValueError, sqlite3.Error) as error:
254
+ print(f"IntentGuard dashboard failed: {error}", file=sys.stderr)
255
+ return 1
256
+ return 0
257
+
258
+
259
+ if __name__ == "__main__":
260
+ raise SystemExit(main())
@@ -0,0 +1,189 @@
1
+ """Install and remove IntentGuard wrappers in MCP client JSON configuration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ _SERVER_COLLECTIONS = ("mcpServers", "servers")
12
+
13
+
14
+ def install_config(
15
+ config_path: str | Path,
16
+ *,
17
+ policy_path: str | Path | None = None,
18
+ database_path: str | Path | None = None,
19
+ intentguard_bin: str = "intentguard",
20
+ ) -> int:
21
+ """Wrap configured stdio MCP servers and return the number changed."""
22
+ path = Path(config_path)
23
+ if not intentguard_bin:
24
+ raise ValueError("The IntentGuard executable command cannot be empty.")
25
+ content = path.read_text(encoding="utf-8")
26
+ config = _load_object(content, path)
27
+ changed = 0
28
+ for collection_name, servers in _server_collections(config):
29
+ for server_name, entry in servers.items():
30
+ if not isinstance(entry, dict):
31
+ raise ValueError(
32
+ f"Server '{server_name}' in '{collection_name}' must be an object."
33
+ )
34
+ command = entry.get("command")
35
+ if command is None:
36
+ continue
37
+ if not isinstance(command, str) or not command:
38
+ raise ValueError(f"Server '{server_name}' has an invalid command.")
39
+ old_args = _string_arguments(entry.get("args", []), server_name)
40
+ if _is_wrapped(command, old_args):
41
+ continue
42
+
43
+ wrapper_args = ["wrap", "--server-name", server_name]
44
+ if policy_path is not None:
45
+ wrapper_args.extend(["--policy", str(policy_path)])
46
+ if database_path is not None:
47
+ wrapper_args.extend(["--db", str(database_path)])
48
+ wrapper_args.extend(["--", command, *old_args])
49
+ entry["command"] = intentguard_bin
50
+ entry["args"] = wrapper_args
51
+ changed += 1
52
+
53
+ if changed:
54
+ backup_path = Path(f"{path}.bak")
55
+ if not backup_path.exists():
56
+ shutil.copy2(path, backup_path)
57
+ _write_config(path, config)
58
+ return changed
59
+
60
+
61
+ def uninstall_config(config_path: str | Path) -> int:
62
+ """Restore wrapped servers and return the number changed."""
63
+ path = Path(config_path)
64
+ config = _load_object(path.read_text(encoding="utf-8"), path)
65
+ backup_path = Path(f"{path}.bak")
66
+ backup_config: dict[str, Any] | None = None
67
+ if backup_path.exists():
68
+ backup_config = _load_object(
69
+ backup_path.read_text(encoding="utf-8"), backup_path
70
+ )
71
+ backup_servers = (
72
+ {
73
+ collection_name: servers
74
+ for collection_name, servers in _server_collections(backup_config)
75
+ }
76
+ if backup_config is not None
77
+ else {}
78
+ )
79
+
80
+ changed = 0
81
+ for collection_name, servers in _server_collections(config):
82
+ original_servers = backup_servers.get(collection_name, {})
83
+ for server_name, entry in servers.items():
84
+ if not isinstance(entry, dict):
85
+ continue
86
+ command = entry.get("command")
87
+ if not isinstance(command, str):
88
+ continue
89
+ args = _string_arguments(entry.get("args", []), server_name)
90
+ original = _unwrap(command, args)
91
+ if original is None:
92
+ continue
93
+ old_command, old_args = original
94
+ backup_entry = original_servers.get(server_name)
95
+ if isinstance(backup_entry, dict) and isinstance(
96
+ backup_entry.get("command"), str
97
+ ):
98
+ old_command = backup_entry["command"]
99
+ had_args = "args" in backup_entry
100
+ old_args = _string_arguments(
101
+ backup_entry.get("args", []), server_name
102
+ )
103
+ else:
104
+ had_args = True
105
+ entry["command"] = old_command
106
+ if had_args:
107
+ entry["args"] = old_args
108
+ else:
109
+ entry.pop("args", None)
110
+ changed += 1
111
+
112
+ if changed:
113
+ _write_config(path, config)
114
+ return changed
115
+
116
+
117
+ def _load_object(content: str, path: Path) -> dict[str, Any]:
118
+ try:
119
+ value = json.loads(content)
120
+ except json.JSONDecodeError as error:
121
+ raise ValueError(f"Invalid JSON in '{path}': {error}") from error
122
+ if not isinstance(value, dict):
123
+ raise ValueError(f"Configuration root in '{path}' must be a JSON object.")
124
+ return value
125
+
126
+
127
+ def _server_collections(
128
+ config: dict[str, Any],
129
+ ) -> list[tuple[str, dict[str, Any]]]:
130
+ collections: list[tuple[str, dict[str, Any]]] = []
131
+ for key in _SERVER_COLLECTIONS:
132
+ if key not in config:
133
+ continue
134
+ value = config[key]
135
+ if not isinstance(value, dict):
136
+ raise ValueError(f"'{key}' must contain a JSON object.")
137
+ collections.append((key, value))
138
+ if not collections:
139
+ raise ValueError("Configuration must contain 'mcpServers' or 'servers'.")
140
+ return collections
141
+
142
+
143
+ def _string_arguments(value: object, server_name: str) -> list[str]:
144
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
145
+ raise ValueError(f"Server '{server_name}' args must be a list of strings.")
146
+ return list(value)
147
+
148
+
149
+ def _is_wrapped(command: str, args: list[str]) -> bool:
150
+ executable = command.replace("\\", "/").rsplit("/", 1)[-1].lower()
151
+ if executable in {"intentguard", "intentguard.exe"} and args[:1] == ["wrap"]:
152
+ return True
153
+ if args[:3] == ["-m", "intentguard.cli", "wrap"]:
154
+ return True
155
+ return (
156
+ args[:1] == ["wrap"]
157
+ and "--server-name" in args
158
+ and "--" in args
159
+ )
160
+
161
+
162
+ def _unwrap(command: str, args: list[str]) -> tuple[str, list[str]] | None:
163
+ executable = command.replace("\\", "/").rsplit("/", 1)[-1].lower()
164
+ if executable in {"intentguard", "intentguard.exe"}:
165
+ if args[:1] != ["wrap"]:
166
+ return None
167
+ wrapper_args = args[1:]
168
+ elif args[:3] == ["-m", "intentguard.cli", "wrap"]:
169
+ wrapper_args = args[3:]
170
+ elif args[:1] == ["wrap"] and "--server-name" in args:
171
+ wrapper_args = args[1:]
172
+ else:
173
+ return None
174
+
175
+ try:
176
+ separator = wrapper_args.index("--")
177
+ except ValueError:
178
+ return None
179
+ target = wrapper_args[separator + 1 :]
180
+ if not target:
181
+ return None
182
+ return target[0], target[1:]
183
+
184
+
185
+ def _write_config(path: Path, config: dict[str, Any]) -> None:
186
+ path.write_text(
187
+ json.dumps(config, ensure_ascii=False, indent=2) + "\n",
188
+ encoding="utf-8",
189
+ )
@@ -0,0 +1,5 @@
1
+ """Core policy and taint-analysis engine."""
2
+
3
+ from intentguard.engine.policy_engine import Decision, PolicyEngine, PolicyRequest
4
+
5
+ __all__ = ["Decision", "PolicyEngine", "PolicyRequest"]
@@ -0,0 +1,156 @@
1
+ """Secret extraction and outbound canary matching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import math
7
+ import re
8
+ from collections import deque
9
+ from dataclasses import dataclass, field
10
+ from urllib.parse import parse_qsl, unquote, urlsplit
11
+
12
+ _CANDIDATE = re.compile(r"[A-Za-z0-9_+/=-]{20,}")
13
+ _BASE64_CANDIDATE = re.compile(r"[A-Za-z0-9+/_-]{8,}={0,2}")
14
+ _HEX_CANDIDATE = re.compile(r"(?i)(?:0x)?(?:[0-9a-f]{2}:?){3,}")
15
+ _URL_ENCODED_CANDIDATE = re.compile(r"(?:%[0-9a-fA-F]{2}){2,}")
16
+ _INVISIBLE_CHARACTERS = str.maketrans("", "", "\u200b\u200c\u200d\u2060\ufeff")
17
+ _MAX_DEPTH = 3
18
+ _MAX_VARIANTS = 64
19
+
20
+
21
+ def _entropy(value: str) -> float:
22
+ frequencies = {character: value.count(character) for character in set(value)}
23
+ return -sum(
24
+ (frequency / len(value)) * math.log2(frequency / len(value))
25
+ for frequency in frequencies.values()
26
+ )
27
+
28
+
29
+ def _normalize(value: str) -> str:
30
+ return value.translate(_INVISIBLE_CHARACTERS)
31
+
32
+
33
+ def _extract_candidates(text: str) -> list[str]:
34
+ candidates: list[str] = []
35
+ for pattern in (_BASE64_CANDIDATE, _HEX_CANDIDATE, _URL_ENCODED_CANDIDATE):
36
+ candidates.extend(match.group(0) for match in pattern.finditer(text))
37
+
38
+ for match in re.finditer(r"https?://[^\s\"'<>]+", text, re.IGNORECASE):
39
+ url = match.group(0).rstrip(".,;)")
40
+ try:
41
+ candidates.extend(value for _, value in parse_qsl(urlsplit(url).query))
42
+ except ValueError:
43
+ continue
44
+ return candidates
45
+
46
+
47
+ def _decode_base64(value: str) -> str | None:
48
+ if len(value) < 8:
49
+ return None
50
+ normalized = value.translate(str.maketrans("-_", "+/"))
51
+ padded = normalized + "=" * (-len(normalized) % 4)
52
+ try:
53
+ decoded = base64.b64decode(padded, validate=True)
54
+ except (ValueError, base64.binascii.Error):
55
+ return None
56
+ result = decoded.decode("utf-8", errors="ignore")
57
+ return result or None
58
+
59
+
60
+ def _decode_hex(value: str) -> str | None:
61
+ candidate = value[2:] if value.lower().startswith("0x") else value
62
+ candidate = candidate.replace(":", "")
63
+ if len(candidate) < 6 or len(candidate) % 2 or not re.fullmatch(r"[0-9a-fA-F]+", candidate):
64
+ return None
65
+ try:
66
+ decoded = bytes.fromhex(candidate)
67
+ except ValueError:
68
+ return None
69
+ result = decoded.decode("utf-8", errors="ignore")
70
+ return result or None
71
+
72
+
73
+ def _resolve_variants(value: str) -> list[str]:
74
+ """Return bounded BFS decode candidates, including the original payload."""
75
+ seeds = [_normalize(value)]
76
+ seeds.extend(_normalize(candidate) for candidate in _extract_candidates(value))
77
+
78
+ seen: set[str] = set()
79
+ queue: deque[tuple[str, int]] = deque()
80
+ for seed in seeds:
81
+ if seed and seed not in seen and len(seen) < _MAX_VARIANTS:
82
+ seen.add(seed)
83
+ queue.append((seed, 0))
84
+
85
+ variants: list[str] = []
86
+ while queue and len(variants) < _MAX_VARIANTS:
87
+ current, depth = queue.popleft()
88
+ variants.append(current)
89
+ if depth >= _MAX_DEPTH:
90
+ continue
91
+
92
+ decoded_candidates = [unquote(current)]
93
+ base64_decoded = _decode_base64(current)
94
+ if base64_decoded is not None:
95
+ decoded_candidates.append(base64_decoded)
96
+ hex_decoded = _decode_hex(current)
97
+ if hex_decoded is not None:
98
+ decoded_candidates.append(hex_decoded)
99
+ if len(current) >= 6:
100
+ decoded_candidates.append(current[::-1])
101
+
102
+ for candidate in decoded_candidates:
103
+ candidate = _normalize(candidate)
104
+ if candidate and candidate not in seen and len(seen) < _MAX_VARIANTS:
105
+ seen.add(candidate)
106
+ queue.append((candidate, depth + 1))
107
+ return variants
108
+
109
+
110
+ @dataclass
111
+ class CanaryStore:
112
+ """Keep secret variants in memory without exposing them in object reprs."""
113
+
114
+ _variants: set[bytes] = field(default_factory=set, repr=False)
115
+
116
+ def extract(self, content: str | bytes, min_length: int = 20, min_entropy: float = 3.5) -> int:
117
+ """Extract high-entropy tokens and remember raw, reversed, Base64, and hex forms."""
118
+ text = content.decode("utf-8", errors="ignore") if isinstance(content, bytes) else content
119
+ text = _normalize(text)
120
+ added = 0
121
+ for match in _CANDIDATE.finditer(text):
122
+ token = match.group(0)
123
+ candidates = token.split("=") if "=" in token else (token,)
124
+ for secret in candidates:
125
+ if len(secret) < min_length or _entropy(secret) < min_entropy:
126
+ continue
127
+ raw = secret.encode("utf-8")
128
+ variants = {
129
+ raw,
130
+ raw[::-1],
131
+ base64.b64encode(raw),
132
+ raw.hex().encode("ascii"),
133
+ }
134
+ before = len(self._variants)
135
+ self._variants.update(variants)
136
+ if len(self._variants) > before:
137
+ added += 1
138
+ return added
139
+
140
+ def contains(self, value: object) -> bool:
141
+ """Return whether any nested outbound value contains a stored canary."""
142
+ if isinstance(value, bytes):
143
+ text = value.decode("utf-8", errors="ignore")
144
+ elif isinstance(value, str):
145
+ text = value
146
+ elif isinstance(value, dict):
147
+ return any(self.contains(key) or self.contains(item) for key, item in value.items())
148
+ elif isinstance(value, (list, tuple, set)):
149
+ return any(self.contains(item) for item in value)
150
+ else:
151
+ return False
152
+ for candidate in _resolve_variants(_normalize(text)):
153
+ haystack = candidate.encode("utf-8", errors="ignore")
154
+ if any(variant and variant in haystack for variant in self._variants):
155
+ return True
156
+ return False