devtrace-cli 1.0.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.
- devtrace/__init__.py +4 -0
- devtrace/__main__.py +8 -0
- devtrace/cli.py +631 -0
- devtrace/collectors/__init__.py +0 -0
- devtrace/collectors/node_deps.py +110 -0
- devtrace/collectors/node_runtime.py +37 -0
- devtrace/collectors/python_deps.py +136 -0
- devtrace/collectors/python_runtime.py +18 -0
- devtrace/collectors/system.py +46 -0
- devtrace/core/__init__.py +0 -0
- devtrace/core/agent.py +297 -0
- devtrace/core/ai_explainer.py +96 -0
- devtrace/core/collector.py +62 -0
- devtrace/core/comparator.py +199 -0
- devtrace/core/diagnostics.py +216 -0
- devtrace/core/healer.py +218 -0
- devtrace/core/models.py +86 -0
- devtrace/core/reporter.py +85 -0
- devtrace/core/serializer.py +13 -0
- devtrace/mcp_server.py +175 -0
- devtrace/project/__init__.py +0 -0
- devtrace/project/detector.py +44 -0
- devtrace/storage/__init__.py +0 -0
- devtrace/storage/history_store.py +108 -0
- devtrace/storage/json_store.py +51 -0
- devtrace_cli-1.0.0.dist-info/METADATA +341 -0
- devtrace_cli-1.0.0.dist-info/RECORD +30 -0
- devtrace_cli-1.0.0.dist-info/WHEEL +4 -0
- devtrace_cli-1.0.0.dist-info/entry_points.txt +2 -0
- devtrace_cli-1.0.0.dist-info/licenses/LICENSE +21 -0
devtrace/core/healer.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Isolated sandbox repair & verification engine for DevTrace (`devtrace heal`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
import venv
|
|
10
|
+
from dataclasses import asdict, dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from devtrace.core.collector import capture_environment
|
|
15
|
+
from devtrace.core.diagnostics import _PY_MISSING_MOD_RE, _normalize_py, run_diagnostics
|
|
16
|
+
|
|
17
|
+
# Common import-name -> PyPI distribution mappings
|
|
18
|
+
IMPORT_TO_PYPI: dict[str, str] = {
|
|
19
|
+
"cv2": "opencv-python",
|
|
20
|
+
"pil": "pillow",
|
|
21
|
+
"sklearn": "scikit-learn",
|
|
22
|
+
"yaml": "pyyaml",
|
|
23
|
+
"bs4": "beautifulsoup4",
|
|
24
|
+
"dotenv": "python-dotenv",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class HealPlan:
|
|
30
|
+
"""Deterministic repair plan derived from environment snapshot and error log."""
|
|
31
|
+
|
|
32
|
+
missing_packages: list[str] = field(default_factory=list)
|
|
33
|
+
proposed_pip_args: list[str] = field(default_factory=list)
|
|
34
|
+
verify_command: str | None = None
|
|
35
|
+
notes: list[str] = field(default_factory=list)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class HealResult:
|
|
40
|
+
"""Outcome of sandbox verification and optional host application."""
|
|
41
|
+
|
|
42
|
+
plan: HealPlan
|
|
43
|
+
sandbox_tested: bool
|
|
44
|
+
install_succeeded: bool | None = None
|
|
45
|
+
verify_succeeded: bool | None = None
|
|
46
|
+
applied_to_host: bool = False
|
|
47
|
+
logs: list[str] = field(default_factory=list)
|
|
48
|
+
|
|
49
|
+
def to_dict(self) -> dict[str, Any]:
|
|
50
|
+
"""Convert HealResult into a JSON-serializable dict."""
|
|
51
|
+
return asdict(self)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def build_heal_plan(
|
|
55
|
+
project_dir: Path,
|
|
56
|
+
error_text: str | None = None,
|
|
57
|
+
verify_command: str | None = None,
|
|
58
|
+
) -> HealPlan:
|
|
59
|
+
"""Build a safe, deterministic repair plan from snapshot and optional error log."""
|
|
60
|
+
snap = capture_environment(project_dir).to_dict()
|
|
61
|
+
diag = run_diagnostics(snap, error_text=error_text)
|
|
62
|
+
|
|
63
|
+
py_deps = (snap.get("dependencies") or {}).get("python") or {}
|
|
64
|
+
declared: dict[str, str] = py_deps.get("declared") or {}
|
|
65
|
+
missing: list[str] = list(py_deps.get("missing_from_env") or [])
|
|
66
|
+
|
|
67
|
+
candidates: set[str] = set(missing)
|
|
68
|
+
notes: list[str] = []
|
|
69
|
+
|
|
70
|
+
if error_text:
|
|
71
|
+
for raw_mod in _PY_MISSING_MOD_RE.findall(error_text):
|
|
72
|
+
top = raw_mod.split(".")[0].lower()
|
|
73
|
+
mapped = IMPORT_TO_PYPI.get(top, _normalize_py(top))
|
|
74
|
+
if mapped not in candidates:
|
|
75
|
+
candidates.add(mapped)
|
|
76
|
+
notes.append(f"Inferred package '{mapped}' from import '{raw_mod}'.")
|
|
77
|
+
|
|
78
|
+
for f in diag.findings:
|
|
79
|
+
if f.rule_id == "ENV-PY-001":
|
|
80
|
+
notes.append(f"Triggered {f.rule_id}: {f.title}")
|
|
81
|
+
|
|
82
|
+
pip_specs: list[str] = []
|
|
83
|
+
for pkg in sorted(candidates):
|
|
84
|
+
spec = declared.get(pkg, "*")
|
|
85
|
+
if spec and spec != "*":
|
|
86
|
+
pip_specs.append(f"{pkg}{spec}")
|
|
87
|
+
else:
|
|
88
|
+
pip_specs.append(pkg)
|
|
89
|
+
|
|
90
|
+
return HealPlan(
|
|
91
|
+
missing_packages=sorted(candidates),
|
|
92
|
+
proposed_pip_args=pip_specs,
|
|
93
|
+
verify_command=verify_command,
|
|
94
|
+
notes=notes,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _venv_python(venv_dir: Path) -> Path:
|
|
99
|
+
"""Return path to Python executable inside a virtual environment."""
|
|
100
|
+
if sys.platform == "win32":
|
|
101
|
+
return venv_dir / "Scripts" / "python.exe"
|
|
102
|
+
return venv_dir / "bin" / "python"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def execute_sandbox_heal(
|
|
106
|
+
project_dir: Path,
|
|
107
|
+
plan: HealPlan,
|
|
108
|
+
dry_run: bool = False,
|
|
109
|
+
apply_to_host: bool = False,
|
|
110
|
+
timeout_seconds: float = 120.0,
|
|
111
|
+
) -> HealResult:
|
|
112
|
+
"""Verify proposed package fixes inside an isolated temporary virtualenv."""
|
|
113
|
+
resolved_project = project_dir.resolve()
|
|
114
|
+
logs: list[str] = []
|
|
115
|
+
|
|
116
|
+
if not plan.proposed_pip_args and not plan.verify_command:
|
|
117
|
+
logs.append("Environment has no missing packages to heal.")
|
|
118
|
+
return HealResult(
|
|
119
|
+
plan=plan,
|
|
120
|
+
sandbox_tested=False,
|
|
121
|
+
install_succeeded=True,
|
|
122
|
+
verify_succeeded=True,
|
|
123
|
+
logs=logs,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
if dry_run:
|
|
127
|
+
logs.append("Dry-run mode: skipped sandbox creation and package installation.")
|
|
128
|
+
return HealResult(plan=plan, sandbox_tested=False, logs=logs)
|
|
129
|
+
|
|
130
|
+
tmp_root = Path(tempfile.mkdtemp(prefix="devtrace-sandbox-"))
|
|
131
|
+
sandbox_venv = tmp_root / "venv"
|
|
132
|
+
install_ok = True
|
|
133
|
+
verify_ok: bool | None = None
|
|
134
|
+
applied = False
|
|
135
|
+
|
|
136
|
+
try:
|
|
137
|
+
logs.append(f"Creating isolated sandbox virtualenv at {sandbox_venv}")
|
|
138
|
+
venv.create(sandbox_venv, with_pip=True, system_site_packages=True)
|
|
139
|
+
sb_python = _venv_python(sandbox_venv)
|
|
140
|
+
|
|
141
|
+
if plan.proposed_pip_args:
|
|
142
|
+
cmd = [str(sb_python), "-m", "pip", "install", *plan.proposed_pip_args]
|
|
143
|
+
logs.append(f"Sandbox install: {' '.join(cmd)}")
|
|
144
|
+
proc = subprocess.run(
|
|
145
|
+
cmd,
|
|
146
|
+
cwd=str(resolved_project),
|
|
147
|
+
capture_output=True,
|
|
148
|
+
text=True,
|
|
149
|
+
timeout=timeout_seconds,
|
|
150
|
+
check=False,
|
|
151
|
+
)
|
|
152
|
+
install_ok = proc.returncode == 0
|
|
153
|
+
if not install_ok:
|
|
154
|
+
logs.append(f"Sandbox pip install failed (exit {proc.returncode}).")
|
|
155
|
+
if proc.stderr.strip():
|
|
156
|
+
logs.append(proc.stderr.strip().splitlines()[-1])
|
|
157
|
+
return HealResult(
|
|
158
|
+
plan=plan,
|
|
159
|
+
sandbox_tested=True,
|
|
160
|
+
install_succeeded=False,
|
|
161
|
+
verify_succeeded=False,
|
|
162
|
+
logs=logs,
|
|
163
|
+
)
|
|
164
|
+
logs.append("Sandbox package installation succeeded.")
|
|
165
|
+
|
|
166
|
+
if plan.verify_command:
|
|
167
|
+
# Run verification command with sandbox venv bin prepended to PATH
|
|
168
|
+
import os
|
|
169
|
+
|
|
170
|
+
env = os.environ.copy()
|
|
171
|
+
env["VIRTUAL_ENV"] = str(sandbox_venv)
|
|
172
|
+
env["PATH"] = f"{sb_python.parent}{os.pathsep}{env.get('PATH', '')}"
|
|
173
|
+
logs.append(f"Running sandbox verification command: {plan.verify_command}")
|
|
174
|
+
v_proc = subprocess.run(
|
|
175
|
+
plan.verify_command,
|
|
176
|
+
shell=True,
|
|
177
|
+
cwd=str(resolved_project),
|
|
178
|
+
env=env,
|
|
179
|
+
capture_output=True,
|
|
180
|
+
text=True,
|
|
181
|
+
timeout=timeout_seconds,
|
|
182
|
+
check=False,
|
|
183
|
+
)
|
|
184
|
+
verify_ok = v_proc.returncode == 0
|
|
185
|
+
logs.append(
|
|
186
|
+
f"Verification command exited with code {v_proc.returncode} "
|
|
187
|
+
f"({'PASSED' if verify_ok else 'FAILED'})."
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
if apply_to_host and install_ok and (verify_ok is not False) and plan.proposed_pip_args:
|
|
191
|
+
host_cmd = [sys.executable, "-m", "pip", "install", *plan.proposed_pip_args]
|
|
192
|
+
logs.append(f"Applying verified fix to active environment: {' '.join(host_cmd)}")
|
|
193
|
+
h_proc = subprocess.run(
|
|
194
|
+
host_cmd,
|
|
195
|
+
cwd=str(resolved_project),
|
|
196
|
+
capture_output=True,
|
|
197
|
+
text=True,
|
|
198
|
+
timeout=timeout_seconds,
|
|
199
|
+
check=False,
|
|
200
|
+
)
|
|
201
|
+
applied = h_proc.returncode == 0
|
|
202
|
+
logs.append(
|
|
203
|
+
"Applied fix to host environment."
|
|
204
|
+
if applied
|
|
205
|
+
else f"Host apply failed with code {h_proc.returncode}."
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
return HealResult(
|
|
209
|
+
plan=plan,
|
|
210
|
+
sandbox_tested=True,
|
|
211
|
+
install_succeeded=install_ok,
|
|
212
|
+
verify_succeeded=verify_ok,
|
|
213
|
+
applied_to_host=applied,
|
|
214
|
+
logs=logs,
|
|
215
|
+
)
|
|
216
|
+
finally:
|
|
217
|
+
shutil.rmtree(tmp_root, ignore_errors=True)
|
|
218
|
+
logs.append("Cleaned up temporary sandbox.")
|
devtrace/core/models.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Core data models for DevTrace environment snapshots."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from dataclasses import asdict, dataclass, field
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
|
|
9
|
+
from devtrace import SCHEMA_VERSION, __version__
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _utc_now_iso() -> str:
|
|
13
|
+
"""Return current UTC timestamp in ISO-8601 format."""
|
|
14
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class SystemInfo:
|
|
19
|
+
"""Host operating system and hardware architecture details."""
|
|
20
|
+
|
|
21
|
+
os: str
|
|
22
|
+
os_release: str
|
|
23
|
+
architecture: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class RuntimeInfo:
|
|
28
|
+
"""Availability and version metadata for a language runtime."""
|
|
29
|
+
|
|
30
|
+
available: bool
|
|
31
|
+
version: str | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class RuntimesInfo:
|
|
36
|
+
"""Collection of detected language runtimes."""
|
|
37
|
+
|
|
38
|
+
python: RuntimeInfo
|
|
39
|
+
node: RuntimeInfo
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class ProjectInfo:
|
|
44
|
+
"""Safe, non-invasive project metadata summary."""
|
|
45
|
+
|
|
46
|
+
path_policy: str = "redacted"
|
|
47
|
+
detected_languages: list[str] = field(default_factory=list)
|
|
48
|
+
metadata_files: list[str] = field(default_factory=list)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class LanguageDependencies:
|
|
53
|
+
"""Declared vs installed packages and drift summary for one ecosystem."""
|
|
54
|
+
|
|
55
|
+
declared: dict[str, str] = field(default_factory=dict)
|
|
56
|
+
installed: dict[str, str] = field(default_factory=dict)
|
|
57
|
+
missing_from_env: list[str] = field(default_factory=list)
|
|
58
|
+
undeclared_in_manifest: list[str] = field(default_factory=list)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class DependenciesInfo:
|
|
63
|
+
"""Dependency breakdown across supported project ecosystems."""
|
|
64
|
+
|
|
65
|
+
python: LanguageDependencies = field(default_factory=LanguageDependencies)
|
|
66
|
+
node: LanguageDependencies = field(default_factory=LanguageDependencies)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True)
|
|
70
|
+
class EnvironmentSnapshot:
|
|
71
|
+
"""Versioned, language-neutral snapshot of a development environment."""
|
|
72
|
+
|
|
73
|
+
system: SystemInfo
|
|
74
|
+
runtimes: RuntimesInfo
|
|
75
|
+
project: ProjectInfo
|
|
76
|
+
dependencies: DependenciesInfo = field(default_factory=DependenciesInfo)
|
|
77
|
+
tag: str | None = None
|
|
78
|
+
collection_warnings: list[str] = field(default_factory=list)
|
|
79
|
+
schema_version: str = SCHEMA_VERSION
|
|
80
|
+
devtrace_version: str = __version__
|
|
81
|
+
snapshot_id: str = field(default_factory=lambda: str(uuid.uuid4()))
|
|
82
|
+
captured_at: str = field(default_factory=_utc_now_iso)
|
|
83
|
+
|
|
84
|
+
def to_dict(self) -> dict:
|
|
85
|
+
"""Convert snapshot dataclass tree into a plain JSON-serializable dict."""
|
|
86
|
+
return asdict(self)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Shareable Markdown diagnostic report generator."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from devtrace.core.comparator import SnapshotComparison
|
|
8
|
+
from devtrace.core.diagnostics import DiagnosticReport
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def render_markdown_report(
|
|
12
|
+
snapshot: dict[str, Any],
|
|
13
|
+
diagnostics: DiagnosticReport,
|
|
14
|
+
comparison: SnapshotComparison | None = None,
|
|
15
|
+
) -> str:
|
|
16
|
+
"""Render a clean, privacy-safe Markdown report for GitHub issues or team sharing."""
|
|
17
|
+
sys_info = snapshot.get("system", {}) or {}
|
|
18
|
+
rt_info = snapshot.get("runtimes", {}) or {}
|
|
19
|
+
proj_info = snapshot.get("project", {}) or {}
|
|
20
|
+
py_rt = rt_info.get("python", {}) or {}
|
|
21
|
+
node_rt = rt_info.get("node", {}) or {}
|
|
22
|
+
|
|
23
|
+
schema_ver = snapshot.get("schema_version")
|
|
24
|
+
cli_ver = snapshot.get("devtrace_version")
|
|
25
|
+
os_rel = sys_info.get("os_release", "unknown")
|
|
26
|
+
arch = sys_info.get("architecture", "unknown")
|
|
27
|
+
|
|
28
|
+
lines: list[str] = [
|
|
29
|
+
"# DevTrace Diagnostic Report",
|
|
30
|
+
"",
|
|
31
|
+
f"- **Snapshot ID:** `{snapshot.get('snapshot_id', 'unknown')}`",
|
|
32
|
+
f"- **Captured At (UTC):** `{snapshot.get('captured_at', 'unknown')}`",
|
|
33
|
+
f"- **Schema / CLI Version:** `{schema_ver}` / `{cli_ver}`",
|
|
34
|
+
"",
|
|
35
|
+
"## Environment Summary",
|
|
36
|
+
"",
|
|
37
|
+
f"- **OS:** {os_rel} (`{arch}`)",
|
|
38
|
+
f"- **Python:** `{py_rt.get('version') or 'not available'}`",
|
|
39
|
+
f"- **Node.js:** `{node_rt.get('version') or 'not available'}`",
|
|
40
|
+
f"- **Detected Languages:** {', '.join(proj_info.get('detected_languages', [])) or 'none'}",
|
|
41
|
+
f"- **Metadata Files:** {', '.join(proj_info.get('metadata_files', [])) or 'none'}",
|
|
42
|
+
"",
|
|
43
|
+
"## Diagnostic Findings",
|
|
44
|
+
"",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
if not diagnostics.findings:
|
|
48
|
+
lines.append("No deterministic issues or dependency drift findings detected.")
|
|
49
|
+
else:
|
|
50
|
+
for finding in diagnostics.findings:
|
|
51
|
+
lines.extend(
|
|
52
|
+
[
|
|
53
|
+
f"### [{finding.severity.upper()}] {finding.rule_id}: {finding.title}",
|
|
54
|
+
f"- **Explanation:** {finding.explanation}",
|
|
55
|
+
f"- **Evidence:** {'; '.join(finding.evidence)}",
|
|
56
|
+
f"- **Suggested Next Check:** {finding.next_check}",
|
|
57
|
+
f"- **Limitation / Uncertainty:** {finding.uncertainty}",
|
|
58
|
+
"",
|
|
59
|
+
]
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
if comparison is not None:
|
|
63
|
+
lines.extend(["", "## Snapshot Comparison Diff", ""])
|
|
64
|
+
if not comparison.has_differences():
|
|
65
|
+
lines.append("No meaningful environment differences between snapshots.")
|
|
66
|
+
else:
|
|
67
|
+
for ch in [
|
|
68
|
+
*comparison.system_changes,
|
|
69
|
+
*comparison.runtime_changes,
|
|
70
|
+
*comparison.project_changes,
|
|
71
|
+
]:
|
|
72
|
+
lines.append(f"- `{ch.field}`: `{ch.left}` -> `{ch.right}`")
|
|
73
|
+
for pkg, vers in comparison.python_dependencies.changed_installed.items():
|
|
74
|
+
lines.append(f"- Python `{pkg}`: `{vers['left']}` -> `{vers['right']}`")
|
|
75
|
+
for pkg, vers in comparison.node_dependencies.changed_installed.items():
|
|
76
|
+
lines.append(f"- Node `{pkg}`: `{vers['left']}` -> `{vers['right']}`")
|
|
77
|
+
|
|
78
|
+
lines.extend(
|
|
79
|
+
[
|
|
80
|
+
"",
|
|
81
|
+
"---",
|
|
82
|
+
"*Generated locally by DevTrace. Absolute project paths are redacted by default.*",
|
|
83
|
+
]
|
|
84
|
+
)
|
|
85
|
+
return "\n".join(lines) + "\n"
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""JSON serialization utilities for DevTrace snapshots."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from devtrace.core.models import EnvironmentSnapshot
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def serialize_snapshot(snapshot: EnvironmentSnapshot, indent: int = 2) -> str:
|
|
11
|
+
"""Serialize an EnvironmentSnapshot into a formatted, deterministic JSON string."""
|
|
12
|
+
payload = snapshot.to_dict()
|
|
13
|
+
return json.dumps(payload, indent=indent, ensure_ascii=False) + "\n"
|
devtrace/mcp_server.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Lightweight stdio Model Context Protocol (MCP) server for DevTrace."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from devtrace import __version__
|
|
11
|
+
from devtrace.core.collector import capture_environment
|
|
12
|
+
from devtrace.core.comparator import compare_snapshots, load_snapshot_file
|
|
13
|
+
from devtrace.core.diagnostics import load_error_file, run_diagnostics
|
|
14
|
+
|
|
15
|
+
MCP_PROTOCOL_VERSION = "2024-11-05"
|
|
16
|
+
|
|
17
|
+
TOOLS_SPEC: list[dict[str, Any]] = [
|
|
18
|
+
{
|
|
19
|
+
"name": "capture_environment",
|
|
20
|
+
"description": (
|
|
21
|
+
"Capture a structured, privacy-safe snapshot of the local OS, "
|
|
22
|
+
"Python/Node runtimes, and declared vs installed dependencies."
|
|
23
|
+
),
|
|
24
|
+
"inputSchema": {
|
|
25
|
+
"type": "object",
|
|
26
|
+
"properties": {
|
|
27
|
+
"project_dir": {
|
|
28
|
+
"type": "string",
|
|
29
|
+
"description": "Path to the project directory (defaults to '.').",
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"name": "diagnose_environment",
|
|
36
|
+
"description": (
|
|
37
|
+
"Run deterministic diagnostic rules on a project environment and "
|
|
38
|
+
"an optional error log file to identify dependency drift or import errors."
|
|
39
|
+
),
|
|
40
|
+
"inputSchema": {
|
|
41
|
+
"type": "object",
|
|
42
|
+
"properties": {
|
|
43
|
+
"project_dir": {
|
|
44
|
+
"type": "string",
|
|
45
|
+
"description": "Path to project directory (defaults to '.').",
|
|
46
|
+
},
|
|
47
|
+
"error_file": {
|
|
48
|
+
"type": "string",
|
|
49
|
+
"description": "Optional path to crash log or stack trace file.",
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"name": "compare_snapshots",
|
|
56
|
+
"description": (
|
|
57
|
+
"Compare two DevTrace snapshot JSON files and return structured "
|
|
58
|
+
"runtime, system, and dependency differences."
|
|
59
|
+
),
|
|
60
|
+
"inputSchema": {
|
|
61
|
+
"type": "object",
|
|
62
|
+
"properties": {
|
|
63
|
+
"left_snapshot": {"type": "string", "description": "First JSON path."},
|
|
64
|
+
"right_snapshot": {
|
|
65
|
+
"type": "string",
|
|
66
|
+
"description": "Second JSON path.",
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
"required": ["left_snapshot", "right_snapshot"],
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def execute_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
|
|
76
|
+
"""Execute a DevTrace MCP tool call and return structured JSON payload."""
|
|
77
|
+
if name == "capture_environment":
|
|
78
|
+
proj = Path(str(arguments.get("project_dir") or "."))
|
|
79
|
+
snap = capture_environment(proj)
|
|
80
|
+
return snap.to_dict()
|
|
81
|
+
|
|
82
|
+
if name == "diagnose_environment":
|
|
83
|
+
proj = Path(str(arguments.get("project_dir") or "."))
|
|
84
|
+
snap_dict = capture_environment(proj).to_dict()
|
|
85
|
+
err_arg = arguments.get("error_file")
|
|
86
|
+
err_text = load_error_file(Path(str(err_arg))) if err_arg else None
|
|
87
|
+
report = run_diagnostics(snap_dict, error_text=err_text)
|
|
88
|
+
return report.to_dict()
|
|
89
|
+
|
|
90
|
+
if name == "compare_snapshots":
|
|
91
|
+
left = load_snapshot_file(Path(str(arguments["left_snapshot"])))
|
|
92
|
+
right = load_snapshot_file(Path(str(arguments["right_snapshot"])))
|
|
93
|
+
return compare_snapshots(left, right).to_dict()
|
|
94
|
+
|
|
95
|
+
raise ValueError(f"Unknown MCP tool: {name}")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def handle_jsonrpc_message(message: dict[str, Any]) -> dict[str, Any] | None:
|
|
99
|
+
"""Process a single JSON-RPC 2.0 request and return a response dict (or None)."""
|
|
100
|
+
msg_id = message.get("id")
|
|
101
|
+
method = message.get("method", "")
|
|
102
|
+
params = message.get("params") or {}
|
|
103
|
+
|
|
104
|
+
if method == "notifications/initialized":
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
if method == "initialize":
|
|
108
|
+
return {
|
|
109
|
+
"jsonrpc": "2.0",
|
|
110
|
+
"id": msg_id,
|
|
111
|
+
"result": {
|
|
112
|
+
"protocolVersion": MCP_PROTOCOL_VERSION,
|
|
113
|
+
"capabilities": {"tools": {}},
|
|
114
|
+
"serverInfo": {"name": "devtrace", "version": __version__},
|
|
115
|
+
},
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if method == "tools/list":
|
|
119
|
+
return {
|
|
120
|
+
"jsonrpc": "2.0",
|
|
121
|
+
"id": msg_id,
|
|
122
|
+
"result": {"tools": TOOLS_SPEC},
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if method == "tools/call":
|
|
126
|
+
tool_name = str(params.get("name", ""))
|
|
127
|
+
tool_args = params.get("arguments") or {}
|
|
128
|
+
try:
|
|
129
|
+
output = execute_mcp_tool(tool_name, tool_args)
|
|
130
|
+
return {
|
|
131
|
+
"jsonrpc": "2.0",
|
|
132
|
+
"id": msg_id,
|
|
133
|
+
"result": {
|
|
134
|
+
"content": [{"type": "text", "text": json.dumps(output, indent=2)}],
|
|
135
|
+
"isError": False,
|
|
136
|
+
},
|
|
137
|
+
}
|
|
138
|
+
except Exception as exc:
|
|
139
|
+
return {
|
|
140
|
+
"jsonrpc": "2.0",
|
|
141
|
+
"id": msg_id,
|
|
142
|
+
"result": {
|
|
143
|
+
"content": [{"type": "text", "text": f"Error: {exc}"}],
|
|
144
|
+
"isError": True,
|
|
145
|
+
},
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if msg_id is not None:
|
|
149
|
+
return {
|
|
150
|
+
"jsonrpc": "2.0",
|
|
151
|
+
"id": msg_id,
|
|
152
|
+
"error": {"code": -32601, "message": f"Method not found: {method}"},
|
|
153
|
+
}
|
|
154
|
+
return None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def serve_stdio() -> int:
|
|
158
|
+
"""Run the blocking stdio JSON-RPC loop for MCP clients."""
|
|
159
|
+
for raw_line in sys.stdin:
|
|
160
|
+
line = raw_line.strip()
|
|
161
|
+
if not line:
|
|
162
|
+
continue
|
|
163
|
+
try:
|
|
164
|
+
msg = json.loads(line)
|
|
165
|
+
except json.JSONDecodeError:
|
|
166
|
+
continue
|
|
167
|
+
|
|
168
|
+
if not isinstance(msg, dict):
|
|
169
|
+
continue
|
|
170
|
+
|
|
171
|
+
response = handle_jsonrpc_message(msg)
|
|
172
|
+
if response is not None:
|
|
173
|
+
sys.stdout.write(json.dumps(response) + "\n")
|
|
174
|
+
sys.stdout.flush()
|
|
175
|
+
return 0
|
|
File without changes
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Safe, non-invasive project metadata detector."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from devtrace.core.models import ProjectInfo
|
|
8
|
+
|
|
9
|
+
SUPPORTED_METADATA_FILES: dict[str, str] = {
|
|
10
|
+
"pyproject.toml": "python",
|
|
11
|
+
"requirements.txt": "python",
|
|
12
|
+
"setup.py": "python",
|
|
13
|
+
"Pipfile": "python",
|
|
14
|
+
"package.json": "node",
|
|
15
|
+
"package-lock.json": "node",
|
|
16
|
+
"yarn.lock": "node",
|
|
17
|
+
"pnpm-lock.yaml": "node",
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def detect_project_info(project_dir: Path) -> tuple[ProjectInfo, list[str]]:
|
|
22
|
+
"""Inspect top-level project directory for known metadata files safely."""
|
|
23
|
+
if not project_dir.exists():
|
|
24
|
+
raise FileNotFoundError(f"Project directory does not exist: {project_dir}")
|
|
25
|
+
if not project_dir.is_dir():
|
|
26
|
+
raise NotADirectoryError(f"Project path is not a directory: {project_dir}")
|
|
27
|
+
|
|
28
|
+
detected_files: list[str] = []
|
|
29
|
+
detected_languages: set[str] = set()
|
|
30
|
+
|
|
31
|
+
for filename, language in SUPPORTED_METADATA_FILES.items():
|
|
32
|
+
candidate = project_dir / filename
|
|
33
|
+
if candidate.is_file():
|
|
34
|
+
detected_files.append(filename)
|
|
35
|
+
detected_languages.add(language)
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
ProjectInfo(
|
|
39
|
+
path_policy="redacted",
|
|
40
|
+
detected_languages=sorted(detected_languages),
|
|
41
|
+
metadata_files=sorted(detected_files),
|
|
42
|
+
),
|
|
43
|
+
[],
|
|
44
|
+
)
|
|
File without changes
|