Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(doctor): actually launch the MCP server instead of reading its config (#2065)

Raghav Chamadiyabef1e258f2e3
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.py
new file mode 100644
index 000000000..88648fe29
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.py
@@ -0,0 +1,219 @@
+"""Doctor check that actually launches the MCP server and talks to it.
+
+Registration checks answer "is there a config entry pointing somewhere that
+exists". They cannot answer "does the server start", which is the failure the
+field data is dominated by: a host restarting a server that dies on import
+(``ModuleNotFoundError`` from a partial install, ``PermissionError`` on a
+locked ``.repowise/``). Those installs pass every existing doctor check.
+
+This launches the registered command, completes the MCP ``initialize`` round
+trip, and reports what the process actually did - exit code and its own
+stderr - when it does not come up. The caller resolves the registration, so
+nothing here depends on where a registration is stored.
+
+The handshake is hand-rolled rather than driven through the ``mcp`` SDK's
+``stdio_client``, which was considered and does not fit: it writes the child's
+stderr to a real file descriptor rather than handing it back, and that stderr
+is the entire diagnostic here; and it rejects the whole stream on a line it
+cannot parse, where a server that logs to stdout should still be reported as
+working. Two JSON messages is less code than working around either.
+"""
+
+from __future__ import annotations
+
+import collections
+import contextlib
+import json
+import os
+import subprocess
+import threading
+import time
+
+from ._types import DoctorCheck, _check
+
+# The server opens the store and builds the full-text index before it answers,
+# so this is a startup budget, not a round-trip budget. It bounds how long
+# doctor can be delayed by a server that hangs instead of exiting.
+_SMOKE_TIMEOUT_S = 20.0
+
+# Enough of the server's own stderr to carry a traceback's final frames, which
+# is where an import or permission failure names itself.
+_STDERR_TAIL_CHARS = 400
+
+# The child's stderr is drained from the moment it starts, into a bounded ring.
+# It cannot be left in the pipe until the round trip finishes: a pipe buffer is
+# ~4KB on Windows, and the server routes every log sink to stderr and does its
+# noisiest work - opening the store, building the full-text index - before it
+# answers. One warning traceback is enough to fill the buffer and block the
+# child forever in write(), which would report a perfectly healthy server as
+# broken. Lines rather than bytes, so the tail never splits a character.
+_STDERR_RING_LINES = 200
+
+_TEARDOWN_ERRORS = (OSError, ValueError, subprocess.TimeoutExpired)
+
+# A server that dies on import closes its stdout, so the read ends at EOF long
+# before the process is reaped. Polling at that instant reports "still running"
+# for a process that is already on its way out - which is the crash loop, the
+# one case this check exists to name. Wait briefly for the exit status first.
+_EXIT_GRACE_S = 5.0
+
+CHECK_NAME = "MCP server responds"
+
+
+def _read_response(stdout, request_id: int, deadline: float) -> dict | None:
+ """Return the JSON-RPC response for *request_id*, or None if none arrives.
+
+ Lines that are not JSON, or are JSON but not this response, are skipped: a
+ server that logs to stdout is misbehaving but not broken, and skipping is
+ what a real client does.
+ """
+ while time.monotonic() < deadline:
+ line = stdout.readline()
+ if not line:
+ return None
+ try:
+ message = json.loads(line)
+ except ValueError:
+ continue
+ if isinstance(message, dict) and message.get("id") == request_id:
+ return message
+ return None
+
+
+def _initialize(proc: subprocess.Popen, deadline: float) -> dict | None:
+ """Send ``initialize`` and return the response, or None if none arrives.
+
+ The read runs on a worker thread because a blocking ``readline`` against a
+ server that never answers cannot be interrupted portably, and Windows - where
+ the crash loops this check exists for are concentrated - is exactly where the
+ non-blocking pipe tricks do not work.
+ """
+ request = {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2024-11-05",
+ "capabilities": {},
+ "clientInfo": {"name": "repowise-doctor", "version": "1"},
+ },
+ }
+ try:
+ # Text-mode pipes translate "\n" to os.linesep, which would frame the
+ # request with a trailing carriage return on Windows. Real clients send
+ # a bare newline and a strict server is entitled to expect one.
+ proc.stdin.reconfigure(newline="\n")
+ proc.stdin.write(json.dumps(request) + "\n")
+ proc.stdin.flush()
+ except (BrokenPipeError, OSError):
+ # The server died before it could read the request. The caller reports
+ # its exit code and stderr, which say more than this write error does.
+ return None
+
+ holder: list[dict | None] = [None]
+
+ def _reader() -> None:
+ # Teardown can close stdout while this thread is still inside
+ # readline(). Uncaught, that prints a thread traceback into the middle
+ # of the doctor table; the timed-out result is already correct.
+ with contextlib.suppress(*_TEARDOWN_ERRORS):
+ holder[0] = _read_response(proc.stdout, 1, deadline)
+
+ thread = threading.Thread(target=_reader, daemon=True)
+ thread.start()
+ thread.join(timeout=max(0.0, deadline - time.monotonic()))
+ return holder[0]
+
+
+def _drain_stderr(proc: subprocess.Popen) -> collections.deque:
+ """Start draining the child's stderr immediately; return the ring it fills.
+
+ Started before the handshake, not after, so the child can never block
+ writing into a full pipe while we wait for its reply.
+ """
+ ring: collections.deque = collections.deque(maxlen=_STDERR_RING_LINES)
+
+ def _drain() -> None:
+ try:
+ for line in proc.stderr:
+ ring.append(line)
+ except _TEARDOWN_ERRORS:
+ pass
+
+ threading.Thread(target=_drain, daemon=True).start()
+ return ring
+
+
+def _stderr_tail(ring: collections.deque) -> str:
+ """The tail of the server's stderr, collapsed onto one line."""
+ return " ".join("".join(ring).split())[-_STDERR_TAIL_CHARS:]
+
+
+def _shutdown(proc: subprocess.Popen) -> None:
+ """Stop the smoke-tested server and release its pipes."""
+ if proc.poll() is None:
+ proc.kill()
+ with contextlib.suppress(*_TEARDOWN_ERRORS):
+ proc.wait(timeout=5)
+ for stream in (proc.stdin, proc.stdout, proc.stderr):
+ if stream is not None:
+ with contextlib.suppress(*_TEARDOWN_ERRORS):
+ stream.close()
+
+
+def mcp_smoke_check(command: str, args: list[str], env: dict | None = None) -> DoctorCheck:
+ """Launch *command* as an MCP server and complete one ``initialize`` trip."""
+ child_env = None
+ if env:
+ child_env = {**os.environ, **{str(k): str(v) for k, v in env.items()}}
+
+ started = time.monotonic()
+ try:
+ proc = subprocess.Popen(
+ [command, *args],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ env=child_env,
+ )
+ except OSError as exc:
+ return _check(CHECK_NAME, False, f"could not launch {command}: {exc}")
+
+ stderr_ring = _drain_stderr(proc)
+ try:
+ response = _initialize(proc, started + _SMOKE_TIMEOUT_S)
+ elapsed_ms = int((time.monotonic() - started) * 1000)
+
+ if response is not None and "result" in response:
+ server = response["result"].get("serverInfo") or {}
+ return _check(
+ CHECK_NAME, True, f"{server.get('name', 'repowise')} initialised in {elapsed_ms}ms"
+ )
+ if response is not None:
+ error = response.get("error") or {}
+ return _check(
+ CHECK_NAME, False, f"initialize failed: {error.get('message', response)}"
+ )
+
+ # No response. Whether the process is gone (the crash-loop case) or up
+ # and mute changes the remedy, so the detail says which.
+ exit_code = proc.poll()
+ if exit_code is None:
+ with contextlib.suppress(subprocess.TimeoutExpired):
+ exit_code = proc.wait(timeout=_EXIT_GRACE_S)
+ if exit_code is None:
+ return _check(
+ CHECK_NAME,
+ False,
+ f"no initialize response within {int(_SMOKE_TIMEOUT_S)}s (still running)",
+ )
+ detail = f"server exited with code {exit_code}"
+ stderr = _stderr_tail(stderr_ring)
+ if stderr:
+ detail += f": {stderr}"
+ return _check(CHECK_NAME, False, detail)
+ finally:
+ _shutdown(proc)
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
index 3c07a4a8c..c20309e40 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import contextlib
+import functools as _functools
from pathlib import Path as _DoctorPath
from rich.table import Table
@@ -491,6 +492,11 @@ def _run_repo_checks(
registration_check, registration_wedged = _claude_registration_check()
checks.append(registration_check)
+ # 12b. Does that registration actually start? Reported separately, because
+ # a wired-up server that dies on every invocation is a different problem
+ # with a different fix than one that is not wired up at all.
+ checks.append(_mcp_responds_check())
+
# 13. Per-agent health, reported by each agent's own descriptor
agent_checks, agents_need_refresh = _agent_target_checks()
checks.extend(agent_checks)
@@ -786,6 +792,74 @@ def _agent_target_checks() -> tuple[list[DoctorCheck], bool]:
return checks, needs_refresh
+def _registered_mcp_entry() -> dict | None:
+ """The Claude Code ``mcpServers.repowise`` entry, or None if there isn't one.
+
+ Delegates to ``claude_config``, which owns reading this entry, so the two
+ doctor checks and the registration writer cannot drift apart on what counts
+ as registered. Both checks must judge the same entry: a smoke check that
+ launched a *different* command than the one registered would give a clean
+ bill of health to the broken thing.
+ """
+ from repowise.cli.editor_integrations.claude_config import (
+ _claude_code_settings_path,
+ _stored_repowise_entry,
+ )
+
+ return _stored_repowise_entry(_claude_code_settings_path())
+
+
+def _unregistered_detail() -> str:
+ """Why there is no entry: absent, or present but unreadable.
+
+ Those have different fixes, and collapsing them tells a user with a
+ hand-broken settings.json to run ``init``, which will fail on the same
+ file. Only reached when there is no entry, so it costs nothing normally.
+ """
+ from repowise.cli.editor_integrations.claude_config import (
+ _claude_code_settings_path,
+ load_existing_config,
+ )
+
+ settings_path = _claude_code_settings_path()
+ if settings_path.exists():
+ try:
+ load_existing_config(settings_path)
+ except Exception:
+ return f"could not parse {settings_path}"
+ return "not registered (repowise init registers it)"
+
+
+@_functools.cache
+def _mcp_responds_check() -> DoctorCheck:
+ """Launch the registered MCP server and complete one round trip.
+
+ Reported separately from the registration row: registration answers "is it
+ wired up", this answers "does it run". An install whose server dies on
+ every invocation passes the first and fails this one, which is the whole
+ point. Absence of a registration is informational, matching
+ the registration check.
+
+ Cached for the process because there is one global ``mcpServers.repowise``
+ entry and this takes no repo argument, while workspace mode runs the repo
+ checks once per entry. Without the cache a ten-repo workspace would launch
+ the same server ten times and pay the startup cost for each.
+ """
+ from .mcp_smoke import CHECK_NAME, mcp_smoke_check
+
+ try:
+ entry = _registered_mcp_entry()
+ if entry is None:
+ return _check(CHECK_NAME, True, "not registered - nothing to launch")
+ command = entry.get("command")
+ args = entry.get("args")
+ if not isinstance(command, str) or not isinstance(args, list):
+ return _check(CHECK_NAME, True, "registration is hand-shaped - not launching it")
+ return mcp_smoke_check(command, [str(a) for a in args], entry.get("env"))
+ except Exception as exc: # a doctor check must never be the crash
+ return _check(CHECK_NAME, True, f"Could not check: {exc}")
+
+
def _claude_registration_check() -> tuple[DoctorCheck, bool]:
"""Detect a wedged Claude Code MCP registration (stale paths).
@@ -795,24 +869,15 @@ def _claude_registration_check() -> tuple[DoctorCheck, bool]:
server silently fails to start in every Claude Code session. Returns
``(check, wedged)``; ``wedged`` drives the ``--repair`` re-registration.
Absence of a registration is informational, never a failure.
+
+ This is a *static* check. Whether the server actually starts is
+ ``_mcp_responds_check``.
"""
name = "Claude Code MCP entry"
try:
- import json as _json
-
- from repowise.cli.editor_integrations.claude_config import _claude_code_settings_path
-
- settings_path = _claude_code_settings_path()
- if not settings_path.exists():
- return _check(name, True, "not registered (repowise init registers it)"), False
- try:
- settings = _json.loads(settings_path.read_text(encoding="utf-8"))
- except (OSError, _json.JSONDecodeError):
- return _check(name, True, f"could not parse {settings_path}"), False
- servers = settings.get("mcpServers") if isinstance(settings, dict) else None
- entry = servers.get("repowise") if isinstance(servers, dict) else None
- if not isinstance(entry, dict):
- return _check(name, True, "not registered (repowise init registers it)"), False
+ entry = _registered_mcp_entry()
+ if entry is None:
+ return _check(name, True, _unregistered_detail()), False
problems: list[str] = []
command = entry.get("command")
diff --git a/tests/unit/cli/test_doctor_mcp_smoke.py b/tests/unit/cli/test_doctor_mcp_smoke.py
new file mode 100644
index 000000000..bc00c9159
--- /dev/null
+++ b/tests/unit/cli/test_doctor_mcp_smoke.py
@@ -0,0 +1,228 @@
+"""Doctor's MCP smoke check: does the registered server actually start?
+
+The field data this exists for is a crash loop - ``ModuleNotFoundError`` from a
+partial install, ``PermissionError`` on a locked ``.repowise/`` - where the
+host restarts a server that dies instantly. Every install in that state passes
+the registration check, which only reads a config file. These tests drive real
+subprocesses, because the failure being caught is a process-level one that a
+mocked launcher would not reproduce.
+
+The autouse ``_isolated_home`` conftest fixture points ``Path.home()`` at a
+temp dir, so these tests write their own settings.json freely.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.doctor_cmd import mcp_smoke
+from repowise.cli.commands.doctor_cmd.mcp_smoke import mcp_smoke_check
+from repowise.cli.commands.doctor_cmd.repo_checks import (
+ _claude_registration_check,
+ _mcp_responds_check,
+)
+
+# A server that answers ``initialize`` the way a real one does.
+_GOOD_SERVER = (
+ "import sys, json;"
+ "line = sys.stdin.readline();"
+ "req = json.loads(line);"
+ "sys.stdout.write(json.dumps({"
+ "'jsonrpc': '2.0', 'id': req['id'],"
+ "'result': {'protocolVersion': '2024-11-05', 'capabilities': {},"
+ "'serverInfo': {'name': 'repowise', 'version': '0.47.0'}}}) + chr(10));"
+ "sys.stdout.flush()"
+)
+
+# The crash loop: dies on import, before it can read anything.
+_DEAD_SERVER = (
+ "import sys;"
+ "sys.stderr.write('ModuleNotFoundError: No module named ' + chr(39) + 'repowise' + chr(39));"
+ "sys.exit(1)"
+)
+
+# Comes up, never answers.
+_MUTE_SERVER = "import time; time.sleep(30)"
+
+
[email protected](autouse=True)
+def _clear_smoke_cache():
+ """``_mcp_responds_check`` is memoised for the process; each test writes its
+ own settings.json and must not read the previous test's launch."""
+ _mcp_responds_check.cache_clear()
+ yield
+ _mcp_responds_check.cache_clear()
+
+
+def test_a_responding_server_passes() -> None:
+ check = mcp_smoke_check(sys.executable, ["-c", _GOOD_SERVER])
+ assert check.ok is True
+ assert "repowise" in check.detail
+ assert "initialised" in check.detail
+
+
+def test_a_server_that_dies_on_import_fails_and_says_why() -> None:
+ """The whole point: this install passes every other doctor check."""
+ check = mcp_smoke_check(sys.executable, ["-c", _DEAD_SERVER])
+ assert check.ok is False
+ assert "exited with code 1" in check.detail
+ # The server's own stderr is what names the fault; without it the user is
+ # told only that something failed.
+ assert "ModuleNotFoundError" in check.detail
+
+
+def test_a_missing_command_fails() -> None:
+ check = mcp_smoke_check("repowise-does-not-exist", ["mcp"])
+ assert check.ok is False
+ assert "could not launch" in check.detail
+
+
+def test_a_mute_server_fails_without_hanging_doctor(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A server that never answers must be bounded, not waited on forever."""
+ monkeypatch.setattr(mcp_smoke, "_SMOKE_TIMEOUT_S", 1.0)
+ check = mcp_smoke_check(sys.executable, ["-c", _MUTE_SERVER])
+ assert check.ok is False
+ assert "still running" in check.detail
+
+
+def test_an_error_response_fails() -> None:
+ server = (
+ "import sys, json;"
+ "req = json.loads(sys.stdin.readline());"
+ "sys.stdout.write(json.dumps({'jsonrpc': '2.0', 'id': req['id'],"
+ "'error': {'code': -32603, 'message': 'index is unreadable'}}) + chr(10));"
+ "sys.stdout.flush()"
+ )
+ check = mcp_smoke_check(sys.executable, ["-c", server])
+ assert check.ok is False
+ assert "index is unreadable" in check.detail
+
+
+def test_log_lines_on_stdout_do_not_break_the_handshake() -> None:
+ """A server that logs to stdout is misbehaving but not broken; a real
+ client skips what it cannot parse, and so must this."""
+ server = (
+ "import sys, json;"
+ "sys.stdout.write('loading vector store...' + chr(10));"
+ "req = json.loads(sys.stdin.readline());"
+ "sys.stdout.write(json.dumps({'jsonrpc': '2.0', 'id': req['id'],"
+ "'result': {'serverInfo': {'name': 'repowise'}}}) + chr(10));"
+ "sys.stdout.flush()"
+ )
+ check = mcp_smoke_check(sys.executable, ["-c", server])
+ assert check.ok is True
+
+
+def test_no_registration_is_informational() -> None:
+ """Nothing registered means nothing to launch - not a failure. A user on
+ the HTTP transport or another client has nothing here to be broken."""
+ check = _mcp_responds_check()
+ assert check.ok is True
+ assert "not registered" in check.detail
+
+
+def test_a_hand_shaped_registration_is_not_launched() -> None:
+ settings_path = Path.home() / ".claude" / "settings.json"
+ settings_path.parent.mkdir(parents=True, exist_ok=True)
+ settings_path.write_text(
+ json.dumps({"mcpServers": {"repowise": {"url": "http://localhost:8000"}}}),
+ encoding="utf-8",
+ )
+ check = _mcp_responds_check()
+ assert check.ok is True
+ assert "hand-shaped" in check.detail
+
+
+def test_the_registered_command_is_the_one_launched() -> None:
+ """A smoke check that launched something other than the registration would
+ give a clean bill of health to the broken thing."""
+ settings_path = Path.home() / ".claude" / "settings.json"
+ settings_path.parent.mkdir(parents=True, exist_ok=True)
+ settings_path.write_text(
+ json.dumps(
+ {"mcpServers": {"repowise": {"command": sys.executable, "args": ["-c", _DEAD_SERVER]}}}
+ ),
+ encoding="utf-8",
+ )
+ check = _mcp_responds_check()
+ assert check.ok is False
+ assert "ModuleNotFoundError" in check.detail
+
+def test_the_server_is_launched_once_per_doctor_run() -> None:
+ """Workspace mode runs the repo checks once per entry, but there is one
+ global registration - so a ten-repo workspace must not launch ten servers.
+ """
+ marker = Path.home() / "launch-count"
+ server = (
+ "import sys, json, pathlib;"
+ f"p = pathlib.Path(r'{marker}');"
+ "p.write_text(str(int(p.read_text()) + 1) if p.exists() else '1');"
+ "req = json.loads(sys.stdin.readline());"
+ "sys.stdout.write(json.dumps({'jsonrpc': '2.0', 'id': req['id'],"
+ "'result': {'serverInfo': {'name': 'repowise'}}}) + chr(10));"
+ "sys.stdout.flush()"
+ )
+ settings_path = Path.home() / ".claude" / "settings.json"
+ settings_path.parent.mkdir(parents=True, exist_ok=True)
+ settings_path.write_text(
+ json.dumps({"mcpServers": {"repowise": {"command": sys.executable, "args": ["-c", server]}}}),
+ encoding="utf-8",
+ )
+
+ for _ in range(3):
+ assert _mcp_responds_check().ok is True
+ assert marker.read_text() == "1"
+
+
+def test_a_chatty_server_is_not_reported_as_broken() -> None:
+ """A healthy server that logs heavily before answering must still pass.
+
+ The child's stderr is a pipe with a ~4KB buffer on Windows. Leaving it
+ undrained until after the handshake blocks the server inside write() and
+ reports it as dead - a false failure driven purely by log volume, on a
+ server that works. repowise routes every log sink to stderr on the stdio
+ path and does its noisiest work before it answers, so this is the normal
+ case, not an edge one.
+ """
+ server = (
+ "import sys, json;"
+ "sys.stderr.write('x' * 40000);"
+ "sys.stderr.flush();"
+ "req = json.loads(sys.stdin.readline());"
+ "sys.stdout.write(json.dumps({'jsonrpc': '2.0', 'id': req['id'],"
+ "'result': {'serverInfo': {'name': 'repowise'}}}) + chr(10));"
+ "sys.stdout.flush()"
+ )
+ check = mcp_smoke_check(sys.executable, ["-c", server])
+ assert check.ok is True, check.detail
+
+
+def test_a_chatty_server_that_dies_still_reports_its_last_words() -> None:
+ """Draining into a bounded ring must keep the END of stderr - the tail is
+ where the traceback names the fault, and the head is startup noise."""
+ server = (
+ "import sys;"
+ "sys.stderr.write('noise' + chr(10));"
+ "sys.stderr.write(('filler' + chr(10)) * 5000);"
+ "sys.stderr.write('PermissionError: .repowise/wiki.db' + chr(10));"
+ "sys.exit(1)"
+ )
+ check = mcp_smoke_check(sys.executable, ["-c", server])
+ assert check.ok is False
+ assert "PermissionError" in check.detail
+
+
+def test_an_unparseable_settings_file_says_so() -> None:
+ """A hand-broken settings.json is not the same as no registration:
+ telling that user to run init sends them at the same unreadable file."""
+ settings_path = Path.home() / '.claude' / 'settings.json'
+ settings_path.parent.mkdir(parents=True, exist_ok=True)
+ settings_path.write_text('{ not json', encoding='utf-8')
+ check, wedged = _claude_registration_check()
+ assert check.ok is True
+ assert wedged is False
+ assert 'could not parse' in check.detail