mcp-drongo 0.1.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.
Files changed (77) hide show
  1. drongo/__init__.py +3 -0
  2. drongo/cli/__init__.py +5 -0
  3. drongo/cli/audit.py +94 -0
  4. drongo/cli/import_cmd.py +147 -0
  5. drongo/cli/lock.py +233 -0
  6. drongo/cli/main.py +451 -0
  7. drongo/cli/plan.py +442 -0
  8. drongo/cli/probe.py +303 -0
  9. drongo/cli/servers.py +214 -0
  10. drongo/cli/sync_cmd.py +268 -0
  11. drongo/cli/tokens.py +75 -0
  12. drongo/cli/verify.py +231 -0
  13. drongo/cli/wrap.py +318 -0
  14. drongo/config/__init__.py +137 -0
  15. drongo/config/draft.py +316 -0
  16. drongo/config/errors.py +17 -0
  17. drongo/config/fs.py +64 -0
  18. drongo/config/loader.py +631 -0
  19. drongo/config/models.py +126 -0
  20. drongo/config/paths.py +119 -0
  21. drongo/config/resolver.py +100 -0
  22. drongo/config/trust.py +217 -0
  23. drongo/integrity/__init__.py +144 -0
  24. drongo/integrity/canonical.py +43 -0
  25. drongo/integrity/errors.py +55 -0
  26. drongo/integrity/gate.py +48 -0
  27. drongo/integrity/heuristics.py +270 -0
  28. drongo/integrity/l1.py +52 -0
  29. drongo/integrity/l2.py +273 -0
  30. drongo/integrity/local_exec.py +92 -0
  31. drongo/integrity/lockfile.py +341 -0
  32. drongo/integrity/tools.py +153 -0
  33. drongo/policy/__init__.py +26 -0
  34. drongo/policy/engine.py +152 -0
  35. drongo/policy/glob.py +92 -0
  36. drongo/process/__init__.py +21 -0
  37. drongo/process/env.py +36 -0
  38. drongo/process/manager.py +156 -0
  39. drongo/protocol/__init__.py +99 -0
  40. drongo/protocol/errors.py +176 -0
  41. drongo/protocol/jsonrpc.py +191 -0
  42. drongo/protocol/policy_matrix.py +189 -0
  43. drongo/protocol/registry.py +184 -0
  44. drongo/protocol/versions.py +44 -0
  45. drongo/runtime/__init__.py +38 -0
  46. drongo/runtime/launch.py +42 -0
  47. drongo/runtime/session.py +794 -0
  48. drongo/runtime/state.py +90 -0
  49. drongo/runtime/stub.py +76 -0
  50. drongo/storage/__init__.py +60 -0
  51. drongo/storage/audit.py +75 -0
  52. drongo/storage/redact.py +167 -0
  53. drongo/storage/state.py +150 -0
  54. drongo/sync/__init__.py +65 -0
  55. drongo/sync/adapters/__init__.py +29 -0
  56. drongo/sync/adapters/base.py +126 -0
  57. drongo/sync/adapters/codex_toml.py +170 -0
  58. drongo/sync/adapters/json_clients.py +190 -0
  59. drongo/sync/atomic.py +67 -0
  60. drongo/sync/backup.py +67 -0
  61. drongo/sync/digest.py +40 -0
  62. drongo/sync/engine.py +935 -0
  63. drongo/sync/errors.py +50 -0
  64. drongo/sync/journal.py +345 -0
  65. drongo/sync/jsonc.py +471 -0
  66. drongo/sync/jsonpatch.py +341 -0
  67. drongo/sync/lock.py +50 -0
  68. drongo/sync/matrix.py +156 -0
  69. drongo/sync/state.py +124 -0
  70. drongo/transport/__init__.py +19 -0
  71. drongo/transport/bridge.py +433 -0
  72. drongo/transport/stdio.py +178 -0
  73. mcp_drongo-0.1.0.dist-info/METADATA +153 -0
  74. mcp_drongo-0.1.0.dist-info/RECORD +77 -0
  75. mcp_drongo-0.1.0.dist-info/WHEEL +4 -0
  76. mcp_drongo-0.1.0.dist-info/entry_points.txt +2 -0
  77. mcp_drongo-0.1.0.dist-info/licenses/LICENSE +202 -0
drongo/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Drongo: declarative MCP control plane and runtime security gateway."""
2
+
3
+ __version__ = "0.1.0"
drongo/cli/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """CLI entrypoints, exit code mapping, and control/data plane orchestration."""
2
+
3
+ from drongo.cli.main import build_parser, main, run_cli
4
+
5
+ __all__ = ["build_parser", "main", "run_cli"]
drongo/cli/audit.py ADDED
@@ -0,0 +1,94 @@
1
+ """`drongo audit [--tail N] [--denied-only]`: structured, redacted view of audit.jsonl."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from collections import deque
8
+ from collections.abc import Mapping
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from drongo.config import EXIT_OK, ConfigError, load_config
13
+ from drongo.storage import OUTCOME_DENIED, redact
14
+
15
+ _HEAD_FIELDS = ("ts", "outcome", "event")
16
+
17
+
18
+ def read_records(
19
+ path: Path, *, tail: int | None = None, denied_only: bool = False
20
+ ) -> list[dict[str, Any]]:
21
+ """Stream the JSONL audit file, keeping the last `tail` (denied) records; always redacted."""
22
+ limit = tail if tail is not None else None
23
+ kept: deque[dict[str, Any]] = deque(maxlen=limit)
24
+ malformed = 0
25
+ with path.open("r", encoding="utf-8") as handle:
26
+ for line in handle:
27
+ line = line.strip()
28
+ if not line:
29
+ continue
30
+ try:
31
+ record = json.loads(line)
32
+ except json.JSONDecodeError:
33
+ malformed += 1
34
+ continue
35
+ if not isinstance(record, dict):
36
+ malformed += 1
37
+ continue
38
+ if denied_only and record.get("outcome") != OUTCOME_DENIED:
39
+ continue
40
+ # Redact again on display: defense in depth for files not written by us.
41
+ kept.append(redact(record))
42
+ if malformed:
43
+ print(f"drongo: note: skipped {malformed} malformed audit line(s)", file=sys.stderr)
44
+ return list(kept)
45
+
46
+
47
+ def _encode(value: Any) -> str:
48
+ return json.dumps(value, ensure_ascii=True, sort_keys=True)
49
+
50
+
51
+ def format_record(record: Mapping[str, Any]) -> str:
52
+ """One line per record for scalar fields; nested values continue on indented lines."""
53
+ outcome = str(record.get("outcome", "")).upper()
54
+ head = f"{record.get('ts', '')} {outcome:<7} {str(record.get('event', '')):<20}"
55
+ scalars: list[str] = []
56
+ nested: list[str] = []
57
+ for key in sorted(record):
58
+ if key in _HEAD_FIELDS:
59
+ continue
60
+ value = record[key]
61
+ if isinstance(value, (dict, list)):
62
+ nested.append(f" {key}={_encode(value)}")
63
+ else:
64
+ scalars.append(f"{key}={_encode(value)}")
65
+ lines = [head + (" " + " ".join(scalars) if scalars else "")]
66
+ lines.extend(nested)
67
+ return "\n".join(lines)
68
+
69
+
70
+ def run_audit(
71
+ *,
72
+ drongo_home: Path,
73
+ env: Mapping[str, str] | None,
74
+ cwd: Path | None = None,
75
+ tail: int | None = None,
76
+ denied_only: bool = False,
77
+ ) -> int:
78
+ """Print audit records newest-last; `--tail N` keeps the last N, `--denied-only` only denials."""
79
+ if tail is not None and tail < 1:
80
+ raise ConfigError("--tail must be a positive integer.")
81
+ config = load_config(drongo_home / "drongo.yaml", cwd=cwd, env=env)
82
+ path = config.defaults.audit_log
83
+
84
+ if not path.is_file():
85
+ print(f"No audit log at {path}")
86
+ return EXIT_OK
87
+ records = read_records(path, tail=tail, denied_only=denied_only)
88
+ if not records:
89
+ print(f"No {'denied ' if denied_only else ''}audit records in {path}")
90
+ return EXIT_OK
91
+ for record in records:
92
+ print(format_record(record))
93
+ print(f"-- {len(records)} record(s) from {path}")
94
+ return EXIT_OK
@@ -0,0 +1,147 @@
1
+ """`drongo import --client <name> [--write]`: a client's MCP entries as a drongo.yaml draft.
2
+
3
+ Exit codes: 0 success, 3 the client file cannot be read, or the draft is not a valid
4
+ configuration. Nothing that was plaintext in the client file is written anywhere:
5
+ environment variables become `env:<SERVER>_<KEY>` secret references and the values are
6
+ dropped; stderr names the variables the user has to export.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ from collections.abc import Mapping
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from drongo.config import (
17
+ EXIT_OK,
18
+ ConfigError,
19
+ DrongoConfig,
20
+ IntegrityConfig,
21
+ ServerConfig,
22
+ draft_servers,
23
+ load_config,
24
+ merge_servers,
25
+ render_servers,
26
+ secret_references,
27
+ validate_servers,
28
+ write_merged_config,
29
+ )
30
+ from drongo.integrity import assess_l2
31
+ from drongo.storage import register_secrets_in
32
+ from drongo.sync.adapters import looks_managed, make_adapter
33
+ from drongo.sync.engine import SyncEngine
34
+ from drongo.sync.errors import SyncValidationError
35
+
36
+ _PACKAGE_MANAGERS = ("uvx", "npx")
37
+
38
+
39
+ def _raise_substantiated_pins(drafts: dict[str, dict[str, Any]]) -> list[str]:
40
+ """Raise `dev_unpinned` to `version_pinned` where M03's L2 assessment finds an exact pin
41
+ in the arguments; returns the servers that were raised."""
42
+ raised: list[str] = []
43
+ for name, server in drafts.items():
44
+ for manager in _PACKAGE_MANAGERS:
45
+ trial = ServerConfig(
46
+ name=name,
47
+ transport="stdio",
48
+ command=server["command"],
49
+ args=tuple(server["args"]),
50
+ env_allowlist=(),
51
+ env={},
52
+ secrets={},
53
+ integrity=IntegrityConfig(guarantee="version_pinned", package_manager=manager),
54
+ )
55
+ if assess_l2(trial).substantiated:
56
+ server["integrity"] = {"guarantee": "version_pinned", "package_manager": manager}
57
+ raised.append(name)
58
+ break
59
+ return raised
60
+
61
+
62
+ def run_import(
63
+ *,
64
+ drongo_home: Path,
65
+ state_dir: Path,
66
+ env: Mapping[str, str] | None,
67
+ cwd: Path | None = None,
68
+ client_name: str,
69
+ write: bool,
70
+ ) -> int:
71
+ """Print a `servers:` draft for the client's unmanaged entries, or merge it into drongo.yaml."""
72
+ config_path = drongo_home / "drongo.yaml"
73
+ config: DrongoConfig = load_config(config_path, cwd=cwd, env=env)
74
+ client = config.clients.get(client_name)
75
+ if client is None:
76
+ raise ConfigError(
77
+ f"Unknown client '{client_name}'; defined clients: {sorted(config.clients)}."
78
+ )
79
+ engine = SyncEngine(config=config, state_dir=state_dir, env=env, cwd=cwd)
80
+ path = engine.client_path(client)
81
+ if not path.is_file():
82
+ raise ConfigError(f"Client file not found: {path}")
83
+
84
+ adapter = make_adapter(client)
85
+ try:
86
+ entries = adapter.entries(adapter.parse(path.read_bytes()))
87
+ except SyncValidationError as exc:
88
+ raise ConfigError(f"Cannot read '{path}': {exc}") from exc
89
+ # First of all: whatever the file holds is masked from here on, wherever it shows up.
90
+ register_secrets_in(entries, all_env=True)
91
+
92
+ managed = sorted(name for name, entry in entries.items() if looks_managed(entry))
93
+ if managed:
94
+ print(
95
+ f"drongo import: note: {managed} already launch 'drongo wrap'; "
96
+ "Drongo manages them, so there is nothing to import",
97
+ file=sys.stderr,
98
+ )
99
+ drafts, notes = draft_servers(
100
+ {name: entry for name, entry in entries.items() if name not in managed}
101
+ )
102
+ for note in notes:
103
+ print(f"drongo import: note: {note}", file=sys.stderr)
104
+
105
+ existing = sorted(name for name in drafts if name in config.servers)
106
+ if existing:
107
+ print(
108
+ f"drongo import: note: {existing} already defined in drongo.yaml; left unchanged",
109
+ file=sys.stderr,
110
+ )
111
+ new = {name: server for name, server in drafts.items() if name not in config.servers}
112
+ if not new:
113
+ print("drongo import: nothing to import", file=sys.stderr)
114
+ return EXIT_OK
115
+
116
+ raised = _raise_substantiated_pins(new)
117
+ if raised:
118
+ print(
119
+ f"drongo import: note: {raised} drafted as version_pinned: their arguments pin an "
120
+ "exact package version. Check that this is the guarantee you want before 'drongo lock'",
121
+ file=sys.stderr,
122
+ )
123
+
124
+ references = secret_references(new)
125
+ if references:
126
+ print(
127
+ f"drongo import: note: {len(references)} plaintext value(s) were replaced by secret "
128
+ "references and were not written anywhere; export these variables before using them:",
129
+ file=sys.stderr,
130
+ )
131
+ for server, variable, reference in references:
132
+ print(f" {reference} (server '{server}', variable '{variable}')", file=sys.stderr)
133
+
134
+ if write:
135
+ merged = merge_servers(config_path.read_text(encoding="utf-8"), new)
136
+ write_merged_config(config_path, merged, cwd=cwd, env=env)
137
+ print(f"Wrote {config_path}: added {sorted(new)}")
138
+ return EXIT_OK
139
+
140
+ validate_servers(new, cwd=cwd, env=env)
141
+ print(
142
+ f"# drongo import --client {client_name}: {len(new)} server(s) from {path}\n"
143
+ "# Paste this block under `servers:` in drongo.yaml (replacing an empty `servers: {}`),\n"
144
+ "# or run the same command with --write to merge it. Nothing plaintext was copied."
145
+ )
146
+ print(render_servers(new), end="")
147
+ return EXIT_OK
drongo/cli/lock.py ADDED
@@ -0,0 +1,233 @@
1
+ """`drongo lock`: probe trusted servers and atomically update drongo.lock.
2
+
3
+ Exit codes: 0 success, 2 local-exec pin drift (that server is never started), 3 config
4
+ error (unknown server, unbacked L2 claim, missing secret), 4 probe failure or timeout
5
+ (including the max_pages circuit breaker), 6 untrusted probe (zero processes started).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import sys
12
+ from collections.abc import Mapping
13
+ from pathlib import Path
14
+
15
+ from drongo.cli.probe import ProbeFailureError, ProbeResult, probe_server
16
+ from drongo.cli.servers import (
17
+ LocalExecStatus,
18
+ ServerStatus,
19
+ compute_server_status,
20
+ evaluate_local_exec,
21
+ print_warnings,
22
+ worst_exit_code,
23
+ )
24
+ from drongo.config import (
25
+ EXIT_CONFIG_ERROR,
26
+ EXIT_DRIFT,
27
+ EXIT_OK,
28
+ EXIT_PROBE_TIMEOUT,
29
+ ConfigError,
30
+ load_config,
31
+ lookup_local_exec_pin,
32
+ lookup_trusted_server_hash,
33
+ pin_local_exec,
34
+ )
35
+ from drongo.integrity import (
36
+ LOCK_FILENAME,
37
+ STATE_DRIFT,
38
+ STATE_OK,
39
+ STATE_UNVERIFIED,
40
+ IntegrityError,
41
+ LocalExecDriftError,
42
+ LocalExecFingerprint,
43
+ LockEntry,
44
+ LockFile,
45
+ authorize_probe,
46
+ build_lock_entry,
47
+ check_host_binary_digest,
48
+ describe_l2,
49
+ ensure_lockable,
50
+ host_platform_key,
51
+ load_lock_if_present,
52
+ write_lock,
53
+ )
54
+ from drongo.process import ProcessTimeoutError
55
+
56
+ _PER_SERVER_FAILURE_ORDER: tuple[int, ...] = (EXIT_DRIFT, EXIT_PROBE_TIMEOUT, EXIT_CONFIG_ERROR)
57
+
58
+
59
+ def _print_locked_server(
60
+ status: ServerStatus,
61
+ entry: LockEntry,
62
+ result: ProbeResult,
63
+ local_status: LocalExecStatus,
64
+ *,
65
+ digest_check: tuple[str, str] | None,
66
+ pin_recorded: bool,
67
+ ) -> None:
68
+ print(f"Locked server '{status.server.name}' (L1 {entry.l1_launch_hash})")
69
+ print(f" L2 guarantee: {describe_l2(status.l2)}")
70
+ if digest_check is not None:
71
+ print(f" L2 artifact digest: {digest_check[0].upper()} - {digest_check[1]}")
72
+ print(f" L3 tools: {len(entry.l3_tools)} locked across {result.pages} page(s)")
73
+ capabilities = entry.l4_capabilities["capabilities"]
74
+ advertised = sorted(capabilities) if capabilities else "none"
75
+ print(f" L4 protocol: {result.protocol_version}; capabilities: {advertised}")
76
+ print(f" Estimated Tool Definition Tokens: {entry.estimated_tool_def_tokens}")
77
+ if local_status.state == STATE_OK:
78
+ print(f" Local exec pin: OK ({local_status.detail})")
79
+ elif pin_recorded:
80
+ local = status.local
81
+ print(
82
+ f" Local exec pin: recorded for this machine "
83
+ f"({local.realpath}, {local.sha256})"
84
+ )
85
+ else:
86
+ print(f" Local exec pin: UNPINNED - {local_status.detail}")
87
+ print_warnings(entry.static_warnings)
88
+
89
+
90
+ def run_lock(
91
+ *,
92
+ drongo_home: Path,
93
+ state_dir: Path,
94
+ env: Mapping[str, str] | None,
95
+ cwd: Path | None = None,
96
+ server_name: str | None,
97
+ trust_new: bool,
98
+ ) -> int:
99
+ """Probe each target server and atomically rewrite drongo.lock."""
100
+ config = load_config(drongo_home / "drongo.yaml", cwd=cwd, env=env)
101
+ if server_name is not None and server_name not in config.servers:
102
+ raise ConfigError(
103
+ f"Unknown server '{server_name}'; defined servers: {sorted(config.servers)}."
104
+ )
105
+ target_names = (
106
+ (server_name,) if server_name is not None else tuple(sorted(config.servers))
107
+ )
108
+ lock_path = drongo_home / LOCK_FILENAME
109
+ existing = load_lock_if_present(lock_path)
110
+ locked_servers = dict(existing.servers) if existing is not None else {}
111
+ statuses = [compute_server_status(config.servers[name], env=env, cwd=cwd) for name in target_names]
112
+
113
+ # Trust gate for every target before a single upstream process is started (Exit 6).
114
+ for status in statuses:
115
+ locked_entry = locked_servers.get(status.server.name)
116
+ authorize_probe(
117
+ status.server,
118
+ current_l1_launch_hash=status.l1_launch_hash,
119
+ locked_l1_launch_hash=(
120
+ locked_entry.l1_launch_hash if locked_entry is not None else None
121
+ ),
122
+ trusted_l1_launch_hash=lookup_trusted_server_hash(state_dir, status.server.name),
123
+ trust_new=trust_new,
124
+ )
125
+
126
+ if server_name is None:
127
+ # A full re-lock also drops entries of servers removed from drongo.yaml.
128
+ locked_servers = {
129
+ name: entry for name, entry in locked_servers.items() if name in config.servers
130
+ }
131
+
132
+ failures: list[tuple[str, BaseException]] = []
133
+ locked_now: list[str] = []
134
+ to_pin: list[tuple[str, LocalExecFingerprint]] = []
135
+ unpinned: list[str] = []
136
+ host_platform = host_platform_key()
137
+ for status in statuses:
138
+ name = status.server.name
139
+ local_status = evaluate_local_exec(status, lookup_local_exec_pin(state_dir, name))
140
+ digest_check = check_host_binary_digest(
141
+ status.l2,
142
+ host_platform=host_platform,
143
+ local_sha256=status.local.sha256 if status.local is not None else None,
144
+ local_error=status.local_error,
145
+ )
146
+ try:
147
+ if local_status.state == STATE_DRIFT:
148
+ raise LocalExecDriftError(
149
+ f"{local_status.detail}; if this change is intentional run "
150
+ f"'drongo trust server {name}' to re-pin"
151
+ )
152
+ if digest_check is not None and digest_check[0] == STATE_DRIFT:
153
+ raise LocalExecDriftError(
154
+ f"server '{name}': {digest_check[1]}; refusing to lock from an "
155
+ "executable that does not match its pinned digest"
156
+ )
157
+ if digest_check is not None and digest_check[0] == STATE_UNVERIFIED:
158
+ raise ConfigError(
159
+ f"Server '{name}' declares artifact_pinned but {digest_check[1]}; "
160
+ "the guarantee cannot be verified on this machine"
161
+ )
162
+ ensure_lockable(status.l2, server_name=name)
163
+ result = asyncio.run(
164
+ probe_server(
165
+ status.server,
166
+ env=env,
167
+ cwd=cwd,
168
+ timeout_ms=config.defaults.probe_timeout_ms,
169
+ )
170
+ )
171
+ except (IntegrityError, ConfigError, ProbeFailureError, ProcessTimeoutError) as exc:
172
+ failures.append((name, exc))
173
+ continue
174
+
175
+ entry = build_lock_entry(
176
+ l1_launch_hash=status.l1_launch_hash,
177
+ l2=status.l2,
178
+ protocol_version=result.protocol_version,
179
+ capabilities=result.capabilities,
180
+ tools=result.tools,
181
+ )
182
+ locked_servers[name] = entry
183
+ locked_now.append(name)
184
+ if local_status.state == STATE_UNVERIFIED:
185
+ unpinned.append(name)
186
+ # --trust-new is the explicit consent that records a missing pin; an existing
187
+ # mismatching pin is drift (above) and is only re-pinned by `drongo trust server`.
188
+ # (A pin can only be taken when the executable could actually be fingerprinted.)
189
+ pin_recorded = (
190
+ trust_new
191
+ and local_status.state == STATE_UNVERIFIED
192
+ and status.local is not None
193
+ )
194
+ if pin_recorded:
195
+ to_pin.append((name, status.local))
196
+ _print_locked_server(
197
+ status,
198
+ entry,
199
+ result,
200
+ local_status,
201
+ digest_check=digest_check,
202
+ pin_recorded=pin_recorded,
203
+ )
204
+
205
+ if locked_now:
206
+ write_lock(lock_path, LockFile(servers=locked_servers))
207
+ print(f"Wrote {lock_path} ({len(locked_servers)} server(s) locked)")
208
+ for name, local in to_pin:
209
+ pin_local_exec(
210
+ state_dir,
211
+ name,
212
+ command=local.command,
213
+ realpath=local.realpath,
214
+ sha256=local.sha256,
215
+ )
216
+ still_unpinned = [name for name in unpinned if name not in dict(to_pin)]
217
+ if still_unpinned:
218
+ print(
219
+ "drongo lock: note: no local-exec pin on this machine for "
220
+ f"{still_unpinned}; 'drongo verify' will not pass until you run "
221
+ "'drongo trust server <name>' or 'drongo verify --trust-local-exec'",
222
+ file=sys.stderr,
223
+ )
224
+
225
+ if failures:
226
+ for name, exc in failures:
227
+ print(f"drongo: error: server '{name}' was not locked: {exc}", file=sys.stderr)
228
+ print(
229
+ f"drongo lock: {len(failures)} of {len(statuses)} server(s) failed",
230
+ file=sys.stderr,
231
+ )
232
+ return worst_exit_code([exc for _, exc in failures], _PER_SERVER_FAILURE_ORDER)
233
+ return EXIT_OK