codev-mcp 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.
codev_mcp/doctor.py ADDED
@@ -0,0 +1,308 @@
1
+ """Check a codev-mcp install and say how to fix what is wrong.
2
+
3
+ codev-mcp-doctor # checks that need no CODE V session
4
+ codev-mcp-doctor --engine # also starts CODE V once (takes a licence seat)
5
+ codev-mcp-doctor --json # machine-readable
6
+
7
+ Exit code 1 if any check fails (or warns, with --strict).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import ctypes
14
+ import json
15
+ import os
16
+ import platform
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ from dataclasses import asdict, dataclass
21
+ from pathlib import Path
22
+
23
+ from codev_mcp import settings
24
+
25
+ PASS, WARN, FAIL, INFO = "PASS", "WARN", "FAIL", "INFO"
26
+ PROGID_DEFAULT = "CodeV.Application"
27
+
28
+
29
+ @dataclass
30
+ class Check:
31
+ name: str
32
+ status: str
33
+ detail: str
34
+ remedy: str = ""
35
+
36
+
37
+ # -- individual checks -----------------------------------------------------------
38
+
39
+
40
+ def check_python() -> Check:
41
+ v = sys.version_info
42
+ ok = v >= (3, 11)
43
+ return Check("python", PASS if ok else FAIL, f"{platform.python_version()} at {sys.executable}",
44
+ "" if ok else "Use Python 3.11 or later.")
45
+
46
+
47
+ def check_platform() -> Check:
48
+ ok = sys.platform == "win32"
49
+ return Check("platform", PASS if ok else FAIL, platform.platform(),
50
+ "" if ok else "CODE V's COM API is Windows-only.")
51
+
52
+
53
+ def check_packages() -> list[Check]:
54
+ out = []
55
+ from importlib import metadata
56
+
57
+ def version(dist: str) -> str | None:
58
+ try:
59
+ return metadata.version(dist)
60
+ except metadata.PackageNotFoundError:
61
+ return None
62
+
63
+ mcp = version("mcp")
64
+ major_minor = tuple(int(p) for p in (mcp or "0.0").split(".")[:2])
65
+ ok = mcp is not None and (2, 3) <= major_minor < (3, 0)
66
+ out.append(Check("package: mcp", PASS if ok else FAIL, mcp or "not installed",
67
+ "" if ok else 'Install a supported SDK: pip install "mcp>=2.3,<3".'))
68
+ try:
69
+ import win32com.client # noqa: F401
70
+
71
+ out.append(Check("package: pywin32", PASS, version("pywin32") or "installed"))
72
+ except ImportError:
73
+ out.append(Check("package: pywin32", FAIL, "not importable", "pip install pywin32"))
74
+ pil = version("pillow")
75
+ out.append(Check("package: pillow", PASS if pil else FAIL, pil or "not installed",
76
+ "" if pil else "pip install pillow (needed by the plot tool)."))
77
+ return out
78
+
79
+
80
+ def com_registrations(progid: str) -> list[dict]:
81
+ """Every registration of the ProgID's COM server, per-user first (that one wins)."""
82
+ try:
83
+ import winreg
84
+ except ImportError:
85
+ return []
86
+ found = []
87
+ for hive, hive_name in ((winreg.HKEY_CURRENT_USER, "per-user"), (winreg.HKEY_LOCAL_MACHINE, "machine-wide")):
88
+ for view in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY):
89
+ def read(sub: str) -> str | None:
90
+ try:
91
+ with winreg.OpenKey(hive, sub, 0, winreg.KEY_READ | view) as key:
92
+ return winreg.QueryValue(key, None)
93
+ except OSError:
94
+ return None
95
+
96
+ clsid = read(rf"Software\Classes\{progid}\CLSID")
97
+ if not clsid:
98
+ continue
99
+ exe = read(rf"Software\Classes\CLSID\{clsid}\LocalServer32")
100
+ if exe:
101
+ path = exe.strip().strip('"').split('"')[0]
102
+ entry = {"scope": hive_name, "clsid": clsid, "server": path, "exists": Path(path).is_file()}
103
+ if entry not in found:
104
+ found.append(entry)
105
+ return found
106
+
107
+
108
+ def check_com(progid: str) -> list[Check]:
109
+ regs = com_registrations(progid)
110
+ if not regs:
111
+ return [Check("CODE V COM registration", FAIL, f"{progid} is not registered",
112
+ "Install CODE V, or set CODEV_PROGID if your install registers a different name.")]
113
+ active = regs[0]
114
+ status = PASS if active["exists"] else FAIL
115
+ detail = f"{progid} -> {active['server']} ({active['scope']})"
116
+ checks = [Check("CODE V COM registration", status, detail,
117
+ "" if active["exists"] else "The registered server is missing; repair or reinstall CODE V.")]
118
+ others = [r for r in regs[1:] if r["server"].lower() != active["server"].lower()]
119
+ if others:
120
+ listed = "; ".join(f"{r['server']} ({r['scope']}{'' if r['exists'] else ', missing'})" for r in others)
121
+ stale = any(not r["exists"] for r in others)
122
+ checks.append(Check("other registrations", WARN if stale else INFO, listed,
123
+ "A registration points at a CODE V that is no longer installed. It is unused while "
124
+ "the per-user one exists, but would break COM if that were removed; reinstalling "
125
+ "or repairing CODE V fixes it." if stale else
126
+ "The per-user registration wins, so the server drives the install above."))
127
+ return checks
128
+
129
+
130
+ def check_installs() -> Check:
131
+ installs = sorted(str(p.parent) for p in Path("C:/").glob("CODEV*/cvgui.exe"))
132
+ if not installs:
133
+ return Check("CODE V installs", WARN, "none found under C:\\CODEV*",
134
+ "Fine if CODE V is installed elsewhere; set CODEV_DIR for the reference build.")
135
+ return Check("CODE V installs", INFO, ", ".join(installs))
136
+
137
+
138
+ def appdata_redirected() -> str | None:
139
+ """The package whose private store receives this process's new %LOCALAPPDATA% folders.
140
+
141
+ Checked by experiment: a uniquely named folder is created and looked for
142
+ in the Packages folder under %LOCALAPPDATA%, then removed. The package-identity API
143
+ (GetCurrentPackageFullName) misses this case: child processes of the Claude
144
+ desktop app report no package, yet their AppData writes are redirected.
145
+ """
146
+ local = os.environ.get("LOCALAPPDATA")
147
+ if not local:
148
+ return None
149
+ probe = Path(local) / f"codev-mcp-doctor-probe-{os.getpid()}"
150
+ try:
151
+ probe.mkdir(exist_ok=True)
152
+ hits = list(Path(local, "Packages").glob(f"*/LocalCache/Local/{probe.name}"))
153
+ return hits[0].parts[-4] if hits else None
154
+ except OSError:
155
+ return None
156
+ finally:
157
+ try:
158
+ probe.rmdir()
159
+ except OSError:
160
+ pass
161
+
162
+
163
+ def _under(path: Path, root: str | None) -> bool:
164
+ if not root:
165
+ return False
166
+ try:
167
+ path.resolve().relative_to(Path(root).resolve())
168
+ return True
169
+ except ValueError:
170
+ return False
171
+
172
+
173
+ def check_folders() -> list[Check]:
174
+ from codev_mcp import paths
175
+
176
+ start = settings.start_dir()
177
+ data = paths.data_dir()
178
+ checks = []
179
+ pkg = appdata_redirected()
180
+ if pkg:
181
+ checks.append(Check("AppData redirection", INFO, f"new %LOCALAPPDATA% folders go to the private store of {pkg}"))
182
+ redirected = [str(p) for p in (start, data)
183
+ if _under(p, os.environ.get("LOCALAPPDATA")) or _under(p, os.environ.get("APPDATA"))]
184
+ if redirected:
185
+ status = FAIL if pkg else WARN
186
+ checks.append(Check("folder location", status, "under %LOCALAPPDATA% or %APPDATA%: " + ", ".join(redirected),
187
+ "Inside a packaged app such as the Claude desktop app these folders are redirected "
188
+ "where CODE V cannot see them. Point CODEV_MCP_DATA / CODEV_START_DIR elsewhere."))
189
+ if redirected and pkg:
190
+ return checks # do not create folders where CODE V cannot see them
191
+ try:
192
+ start.mkdir(parents=True, exist_ok=True)
193
+ with tempfile.NamedTemporaryFile(dir=start, prefix="doctor-", delete=True):
194
+ pass
195
+ checks.append(Check("working folder", PASS, str(start)))
196
+ except OSError as exc:
197
+ checks.append(Check("working folder", FAIL, f"{start}: {exc}", "Make it writable or set CODEV_START_DIR."))
198
+ return checks
199
+
200
+
201
+ def check_reference() -> Check:
202
+ from codev_mcp import reference
203
+
204
+ st = reference.status()
205
+ if not st.get("built"):
206
+ return Check("reference data", WARN, f"not built ({st['database']})",
207
+ "Use the build_reference_data tool or run codev-mcp-build-data; until then manual search and "
208
+ "glass lookup are unavailable.")
209
+ return Check("reference data", PASS,
210
+ f"{st.get('manual_pages', 0)} manual pages, {st.get('glasses', 0)} glasses; built {st.get('built_at')} "
211
+ f"from {st.get('install_dir')} ({st['database']})")
212
+
213
+
214
+ def com_launched_codev() -> int | None:
215
+ """How many cvgui.exe processes COM started (-Embedding), or None if unknown."""
216
+ try:
217
+ out = subprocess.run(
218
+ ["powershell", "-NoProfile", "-Command",
219
+ "@(Get-CimInstance Win32_Process -Filter \"Name='cvgui.exe'\" | "
220
+ "Where-Object { $_.CommandLine -match 'Embedding' }).Count"],
221
+ capture_output=True, text=True, timeout=30)
222
+ return int(out.stdout.strip())
223
+ except (OSError, ValueError, subprocess.SubprocessError):
224
+ return None
225
+
226
+
227
+ def check_processes() -> Check:
228
+ n = com_launched_codev()
229
+ if n is None:
230
+ return Check("background CODE V processes", INFO, "could not count")
231
+ if n <= 2:
232
+ return Check("background CODE V processes", PASS, f"{n} running")
233
+ return Check("background CODE V processes", WARN, f"{n} COM-launched CODE V sessions running",
234
+ "Each codev-mcp server runs at most one. If no server is in use, these are left over and may hold "
235
+ "licence seats; see the README for how to stop them.")
236
+
237
+
238
+ def check_settings() -> Check:
239
+ from codev_mcp.engine import _idle_seconds_from_env
240
+
241
+ idle = _idle_seconds_from_env()
242
+ progid = settings.env("CODEV_PROGID") or PROGID_DEFAULT
243
+ detail = f"progid {progid}; idle timeout " + (f"{idle / 60:g} min" if idle else "off")
244
+ problems = settings.warnings()
245
+ if problems:
246
+ return Check("settings", WARN, detail + "; " + " ".join(problems),
247
+ "Change the setting in the extension or plugin settings, or the environment variable.")
248
+ return Check("settings", INFO, detail)
249
+
250
+
251
+ def check_engine() -> Check:
252
+ """Start CODE V once, the way the server does, and stop it."""
253
+ from codev_mcp.engine import CodeVEngine
254
+
255
+ print("Starting CODE V; if the licence server cannot be reached this can take a few minutes...",
256
+ file=sys.stderr, flush=True)
257
+ eng = CodeVEngine(idle_seconds=None)
258
+ try:
259
+ r = eng.start()
260
+ if not r["ok"]:
261
+ # CODE V's own messages (e.g. the licence error naming the version) say the most.
262
+ codev = "; ".join(r.get("errors", []))
263
+ detail = codev or r.get("exception", "")
264
+ licence = "license" in detail.lower() or "licence" in detail.lower()
265
+ return Check("engine start", FAIL, detail,
266
+ "No licence was available for this CODE V version: check the licence server and that it "
267
+ "serves this version, or point COM at an install you are licensed for."
268
+ if licence else
269
+ "A COM error at start usually means the working folder is not visible to CODE V "
270
+ "(see 'folder location').")
271
+ return Check("engine start", PASS, f"CODE V {r['version']}, events {'on' if r['events_attached'] else 'off'}")
272
+ finally:
273
+ eng.shutdown()
274
+ eng.stop()
275
+
276
+
277
+ def run(engine: bool = False) -> list[Check]:
278
+ checks = [check_python(), check_platform(), *check_packages()]
279
+ if sys.platform == "win32":
280
+ progid = settings.env("CODEV_PROGID") or PROGID_DEFAULT
281
+ checks += [*check_com(progid), check_installs(), *check_folders(), check_reference(),
282
+ check_processes(), check_settings()]
283
+ if engine:
284
+ checks.append(check_engine())
285
+ return checks
286
+
287
+
288
+ def main(argv: list[str] | None = None) -> int:
289
+ ap = argparse.ArgumentParser(prog="codev-mcp-doctor", description=__doc__.splitlines()[0])
290
+ ap.add_argument("--engine", action="store_true", help="also start CODE V once (takes a licence seat)")
291
+ ap.add_argument("--json", action="store_true", help="print the results as JSON")
292
+ ap.add_argument("--strict", action="store_true", help="exit 1 on warnings too")
293
+ args = ap.parse_args(argv)
294
+ checks = run(engine=args.engine)
295
+ if args.json:
296
+ print(json.dumps([asdict(c) for c in checks], indent=2))
297
+ else:
298
+ width = max(len(c.name) for c in checks)
299
+ for c in checks:
300
+ print(f"{c.status:<5} {c.name:<{width}} {c.detail}")
301
+ if c.remedy and c.status in (WARN, FAIL):
302
+ print(f"{'':<5} {'':<{width}} -> {c.remedy}")
303
+ bad = {FAIL, WARN} if args.strict else {FAIL}
304
+ return 1 if any(c.status in bad for c in checks) else 0
305
+
306
+
307
+ if __name__ == "__main__":
308
+ raise SystemExit(main())