mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(mcp): report a plugin-provided Serena that reconcile cannot see (#3578)
## Description **Problem.** With the `serena` plugin from the `claude-plugins-official` marketplace installed, Claude Code runs **two** Serena MCP servers: the `mcpServers` entry Headroom manages and the plugin's own (`plugin:serena:serena` in `claude mcp list`). `headroom mcp reconcile` reports the Headroom entry as consistent and never mentions the second one. The plugin's spec is the worse of the two — `uvx --from git+https://github.com/oraios/serena serena start-mcp-server` with no `--project-from-cwd`, no `--context claude-code`, and no `--open-web-dashboard False` (so the #1003 popup returns), tracking `main` instead of a PyPI release. **Cause.** `ClaudeRegistrar.get_server` only reads the `mcpServers` object in `~/.claude.json` / `~/.claude/mcp.json`. A plugin-provided server is declared in the plugin's own `.mcp.json` under `<claude_dir>/plugins/cache/...`, indexed by `<claude_dir>/plugins/installed_plugins.json` and gated by `enabledPlugins` in Claude's settings files. Nothing in Headroom reads any of that, so `reconcile` structurally cannot see the duplicate. **Approach.** Add a read-only `ClaudeRegistrar.get_plugin_servers(server_name)` that walks `installed_plugins.json` (v2 shape) and reads each plugin's `.mcp.json` in both shapes the official marketplace uses (flat `{name: entry}` and `{"mcpServers": {...}}`). Whether Claude will actually launch a plugin is resolved the way Claude Code itself does it — verified probe by probe against Claude Code 2.1.238 with real `claude plugin install/disable` runs: - `enabledPlugins` is merged from the user `settings.json`, then `<cwd>/.claude/settings.json`, then `<cwd>/.claude/settings.local.json`; the most specific scope wins. - The plugin must be explicitly `true`; an installed plugin with no entry anywhere is **not** launched. - The install record's `scope` / `projectPath` do not gate anything: a subdirectory with its own `.claude` settings launches it, one without does not. So a `--scope project` install is reported inside its project and silent elsewhere, an installed-but-never-enabled plugin does not warn, and `claude plugin disable <id>` (which writes `false` to whichever of those three files matches the scope and keeps the install record) reliably clears the warning. `headroom mcp reconcile` prints the plugin entry and that disable command. Per the issue, **nothing is removed** — Headroom does not mutate third-party plugins. Plugin state and the user `settings.json` follow `CLAUDE_CONFIG_DIR` the same way the modern config already does in this registrar. **Alternatives considered.** - Read the plugin files directly in `cli/mcp.py` next to `find_headroom_registration` — shorter, but that module's path constants ignore `CLAUDE_CONFIG_DIR`, so it would duplicate (and get wrong) the resolution the registrar already has. - Fold the plugin entry into `get_server` / `register_server` `MISMATCH` — would change `headroom wrap` behaviour for every user and could steer `--adopt`/force paths at a plugin; the issue explicitly asks for no automatic removal. - Gate project-scoped records by comparing the resolved cwd against `projectPath` (exact or containment). Measured against Claude: it is neither necessary nor sufficient — `proj/sub` does *not* launch a plugin installed at `proj` unless `proj/sub` has its own `.claude` settings, and a project-level `false` silences a *user-scope* install. Reading the three settings files is both simpler and exact. - Also warn from `mcp status`, `doctor`, or at wrap time — left for follow-ups to keep this diff to the command the issue reproduces with (`reconcile` is the Serena command; `status` reports Headroom's own server). Closes #3570 ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - `headroom/mcp_registry/claude.py`: new `ClaudeRegistrar.get_plugin_servers(server_name) -> list[tuple[plugin_id, ServerSpec]]`, `_enabled_plugins(project_dir, user_settings)` (merges the three `enabledPlugins` sources in Claude's precedence) and `_read_plugin_mcp_entry` (both `.mcp.json` shapes). Resolves the user `settings.json` / `plugins/installed_plugins.json` under `CLAUDE_CONFIG_DIR` when set, else `~/.claude`. Reuses the existing read-only `_read_json` (any unreadable/malformed file → no match). No change to `get_server`, `register_server`, or `wrap`. - `headroom/cli/mcp.py`: `mcp reconcile` (inspect path) prints `plugin: <id> also provides a Serena MCP server (<command>)` and `action: ... claude plugin disable <id>` for each plugin bundling Serena that Claude would launch from the current directory. - `tests/fixtures/headroom-issue-3570.json`: the exact on-disk shapes Claude Code 2.1.238 wrote for `claude plugin install serena@claude-plugins-official` at user and project scope (`installed_plugins.json` v2 with per-scope record list incl. `projectPath`, `enabledPlugins`, the plugin's flat `.mcp.json`) — this layout is not in the Claude Code docs. - `tests/test_mcp_registry/test_claude_registrar.py`: 19 tests / 43 cases for `get_plugin_servers` — flat and `mcpServers` shapes; disabled plugin skipped; absent / `{}` / `null` / unparseable `enabledPlugins` → not launched; project-scope install reported inside its project and quiet in `$HOME`, an unrelated dir and a subdirectory; project `false` silences a user install; project `true` overrides user `false`; `settings.local.json` overrides `settings.json` both ways; one report per plugin; multiple plugins in registry order; name filter; explicit `config_dir` and `CLAUDE_CONFIG_DIR` env; 9 malformed-registry inputs; 6 malformed `.mcp.json` inputs; missing install dir. Every test pins cwd to an isolated directory. - `tests/test_cli/test_mcp_reconcile.py`: regression `test_issue_fixture_plugin_serena_is_reported_base_fail_head_pass` (fails on `main`, passes here; also asserts the Claude-owned plugin files keep identical bytes and mtimes), quiet-once-disabled, `--adopt` leaves plugin files untouched, and `test_reconcile_reports_project_scoped_plugin_only_inside_its_project` (in-project positive, `$HOME` and subdirectory negatives, remedy clears it). - `docs/content/docs/mcp.mdx`: one sentence on the new warning. `CHANGELOG.md` not touched. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text # Regression test on unpatched main (aa4739e5) — source stashed, tests kept $ pytest tests/test_cli/test_mcp_reconcile.py::test_issue_fixture_plugin_serena_is_reported_base_fail_head_pass -q E AssertionError: assert 'plugin: serena@claude-plugins-official also provides a Serena MCP server (uvx --from git+https://github.com/oraios/serena serena start-mcp-server)' in 'Serena reconciliation for Claude\n observed: present\n recommendation: uvx --from serena-agent serena start-mcp-server --project-from-cwd --context claude-code --open-web-dashboard False\n' FAILED tests/test_cli/test_mcp_reconcile.py::test_issue_fixture_plugin_serena_is_reported_base_fail_head_pass 1 failed in 0.91s # Second commit (d07ba880) — its 10 new scope/precedence cases fail against the first commit's source (a81f3dc4) $ pytest tests/test_cli/test_mcp_reconcile.py tests/test_mcp_registry/test_claude_registrar.py -k plugin -q FAILED ...::test_reconcile_reports_project_scoped_plugin_only_inside_its_project FAILED ...::test_get_plugin_servers_requires_an_explicit_enable[None|{}|{"enabledPlugins": null}|{"enabledPlugins": {}}|not json] FAILED ...::test_get_plugin_servers_project_install_reports_inside_its_project FAILED ...::test_get_plugin_servers_project_disable_silences_user_install FAILED ...::test_get_plugin_servers_project_enable_overrides_user_disable FAILED ...::test_get_plugin_servers_local_settings_override_project[False] 10 failed, 30 passed, 69 deselected in 1.53s # Patched (d07ba880) $ pytest tests/test_cli/test_mcp_reconcile.py tests/test_mcp_registry/ tests/test_cli/test_mcp.py tests/test_cli/test_mcp_status.py tests/test_cli/test_serena_reconcile.py tests/test_cli/test_serena_migrate.py tests/test_cli/test_serena_disable.py -q 228 passed in 9.08s $ ruff check . All checks passed! $ ruff format --check . 1580 files already formatted $ mypy headroom --ignore-missing-imports Success: no issues found in 531 source files $ coverage report --include=headroom/mcp_registry/claude.py,headroom/cli/mcp.py --show-missing headroom\mcp_registry\claude.py 243 20 102 14 90% 73, 136-137, 147, 184, 217, 249-250, 258-259, 266-267, 275-276, 315->317, 398, 417->419, 420, 429, 432->434, 456, 458, 459->461, 462 # none of the missing lines fall in the changed ranges (mcp.py 263-274; claude.py 67-71, 96-126, 340-376) => changed lines 100% covered # Full suite, Windows 11 / Python 3.11.9, first commit (deselecting the pre-existing Windows-only failures in # test_recover_codex.py, test_unwrap_claude.py, test_wrap_stale_marker.py::...SIGHUP, and files that # need the built Rust core / langchain_core, none of which this PR touches) $ pytest tests -q #a81f3dc4197 failed, 10927 passed, 792 skipped, 46 deselected, 19 warnings, 192 errors in 3216.17s (0:53:36) # 0 of the 389 failing IDs are in tests/test_cli/test_mcp*.py, test_serena*.py or tests/test_mcp_registry/. # 364 of them fail identically on unpatched upstream/main (aa4739e5) in a clean worktree with the same # local env (52 affected files: 182 failed, 741 passed, 183 errors) - missing sentence-transformers / # playwright / matching Rust core, i.e. environment, not this change. # The other 24 (dashboard playwright, test_proxy_health, test_read_maturation_handler_nobust, # test_savings_ledger_offload) pass on this branch when their 8 files run alone: 52 passed in 59.13s. # CI ona81f3dc4: test (1)..(4) shards, lint (ruff + mypy), template, commitlint all green; codecov: # "All modified and coverable lines are covered by tests." CI ond07ba880: see the checks on this PR. ``` ## Real Behavior Proof - Environment: Windows 11 Home 10.0.26200, Python 3.11.9, Claude Code CLI 2.1.238, checkout atd07ba880run via `PYTHONPATH=$(pwd) python -m headroom.cli`, isolated `CLAUDE_CONFIG_DIR` (no real config touched) - Exact command / steps: `claude plugin marketplace add anthropics/claude-plugins-official` → `claude plugin install serena@claude-plugins-official` → `claude mcp add serena -s user -- uvx --from serena-agent serena start-mcp-server --project-from-cwd --context claude-code --open-web-dashboard False` (Headroom's spec) → `claude mcp list | grep -i serena` → `headroom mcp reconcile` on unpatched main → on this branch → `claude plugin disable serena@claude-plugins-official` (the printed remedy) → `headroom mcp reconcile` again. Then, to derive the launch rule, each row of the matrix below was set up by editing the three settings files / reinstalling at `--scope project|local`, and checked with both `claude mcp list | grep -ic serena` (what Claude does) and `headroom mcp reconcile | grep -c "plugin: serena@"` (what this branch reports), from `proj`, `proj/sub` and outside. - Observed result: `claude mcp list` shows two lines, `plugin:serena:serena: uvx --from git+https://github.com/oraios/serena serena start-mcp-server` and `serena: uvx --from serena-agent ...` (issue step 3 confirmed). Unpatched main printed only `observed: present` + `recommendation: ...` (issue step 4 confirmed). Patched printed the same two lines plus `plugin: serena@claude-plugins-official also provides a Serena MCP server (uvx --from git+https://github.com/oraios/serena serena start-mcp-server)` and `action: disable it so only one Serena runs: claude plugin disable serena@claude-plugins-official`, exit 0. After the disable command the warning disappeared and `claude mcp list` showed one Serena. Launch-rule matrix, Claude vs this branch (identical in every row): user `true` → 1/1 in and out of proj; no `enabledPlugins` entry anywhere → 0/0; user `true` + proj `false` → 0/0 in proj, 1/1 outside; proj `true` + local `false` → 0/0; user `false` + proj `true` → 1/1 in proj, 0/0 outside; `proj/sub` without own settings → 0/0; `proj/sub` with its own `.claude/settings.json` `true` → 1/1. `--scope project` install: `claude mcp list` 1 inside / 0 outside, this branch warns inside / silent outside; `claude plugin disable serena@claude-plugins-official` run inside wrote `false` to `proj/.claude/settings.json` (user file untouched) and both Claude and this branch went to 0. `--scope local` behaves the same via `.claude/settings.local.json`. `installed_plugins.json` records for user and project scope were captured verbatim into the fixture. - Not tested: macOS/Linux paths (only via CI); a plugin that inlines `mcpServers` in `.claude-plugin/plugin.json` instead of `.mcp.json` (0 of 39 official-marketplace manifests do; not read); enterprise managed settings (`managed-settings.json`) as a fourth `enabledPlugins` source (not consulted); Claude Code releases other than 2.1.238 (an older `installed_plugins.json` shape, if it differs, yields no warning rather than an error). ## Runtime Rollout Safety - Rollout-managed feature(s): none — this is a read-only CLI diagnostic in `headroom mcp reconcile`, not a proxy/runtime path - Minimum rollout channel: n/a - Stable/default behavior changed: `headroom mcp reconcile` (inspect path) prints up to two extra lines per plugin bundling a `serena` server that Claude would launch from the current directory; no change when no such plugin is installed or it is not enabled there. `--adopt`, `mcp install`, `mcp status`, `wrap`, `get_server` and `register_server` are unchanged. - Kill switch / disable path: `claude plugin disable <id>` (the printed remedy) or `claude plugin uninstall <id>` removes the lines; no Headroom flag needed - Unsafe override required: no - Qualification impact: none - Rollback path: revert the commits; no persisted state, files, or config are written by this change ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Screenshots (if applicable) N/A — terminal output is quoted verbatim above. ## Additional Notes - Second commit `d07ba880` (after the first approval) replaces the "user-scope records only" simplification with Claude's actual per-directory `enabledPlugins` resolution, per the project-scope point raised on #3576. It is a strict superset: every previously covered case behaves the same, plus project/local-scope installs are reported where Claude launches them, and an installed-but-never-enabled plugin no longer produces a false positive. - Deliberately out of scope, happy to follow up if wanted: the same warning in `mcp status` / `doctor` / at `wrap` time; managed settings as an `enabledPlugins` source; the inline `plugin.json` `mcpServers` form. - `--adopt` intentionally keeps its one-line confirmation; the warning is on the inspect path the issue reproduces with. If you would rather have it on both, it is a two-line change. - The detector fails open: any missing or malformed plugin or settings file yields no warning rather than an error, matching how `get_server` treats `~/.claude.json`.
This commit is contained in:
@@ -187,7 +187,7 @@ Install Headroom so it's globally on PATH — `uv tool install "headroom-ai[mcp]
|
||||
|
||||
## Architecture
|
||||
|
||||
For user-managed Serena drift, run `headroom mcp reconcile` to inspect the current recommendation. Add `--adopt` only when you want Headroom to replace the Serena entry.
|
||||
For user-managed Serena drift, run `headroom mcp reconcile` to inspect the current recommendation. Add `--adopt` only when you want Headroom to replace the Serena entry. If an enabled Claude Code plugin (such as `serena` from the `claude-plugins-official` marketplace) also bundles a Serena server, `reconcile` reports it and prints the `claude plugin disable` command; Headroom never edits third-party plugins.
|
||||
|
||||
### MCP only (no proxy)
|
||||
|
||||
|
||||
@@ -260,6 +260,18 @@ def mcp_reconcile(adopt: bool) -> None:
|
||||
click.echo(f" recommendation: {recommended.command} {' '.join(recommended.args)}")
|
||||
if observed is not None and observed != recommended:
|
||||
click.echo(" action: use --adopt to replace it")
|
||||
# A Serena bundled by an enabled Claude Code plugin runs alongside the
|
||||
# entry above (``claude mcp list`` shows it as ``plugin:serena:serena``)
|
||||
# with none of Headroom's flags. It is a third-party plugin, so it is
|
||||
# never removed here — point at the command that disables it (#3570).
|
||||
for plugin_id, spec in registrar.get_plugin_servers("serena"):
|
||||
click.echo(
|
||||
f" plugin: {plugin_id} also provides a Serena MCP server "
|
||||
f"({spec.command} {' '.join(spec.args)})"
|
||||
)
|
||||
click.echo(
|
||||
f" action: disable it so only one Serena runs: claude plugin disable {plugin_id}"
|
||||
)
|
||||
|
||||
|
||||
@mcp.command("status")
|
||||
|
||||
@@ -64,6 +64,11 @@ class ClaudeRegistrar(MCPRegistrar):
|
||||
self._isolated_cli_env = home_dir is not None or config_dir is not None
|
||||
self._modern_config = modern_dir / ".claude.json"
|
||||
self._legacy_config = self._claude_dir / "mcp.json"
|
||||
# Unlike the legacy file, plugin state and settings.json do move with
|
||||
# CLAUDE_CONFIG_DIR; without the override they live under ``~/.claude``.
|
||||
state_dir = modern_dir if modern_dir != home else self._claude_dir
|
||||
self._settings = state_dir / "settings.json"
|
||||
self._installed_plugins = state_dir / "plugins" / "installed_plugins.json"
|
||||
if claude_cli is ...:
|
||||
self._claude_cli = shutil.which("claude")
|
||||
else:
|
||||
@@ -88,6 +93,37 @@ class ClaudeRegistrar(MCPRegistrar):
|
||||
return entry
|
||||
return None
|
||||
|
||||
def get_plugin_servers(self, server_name: str) -> list[tuple[str, ServerSpec]]:
|
||||
"""Return ``(plugin_id, spec)`` for each enabled plugin bundling ``server_name``.
|
||||
|
||||
Claude Code also launches MCP servers declared in an installed
|
||||
plugin's ``.mcp.json`` (``claude mcp list`` shows them as
|
||||
``plugin:<plugin>:<server>``). They never appear under ``mcpServers``,
|
||||
so :meth:`get_server` cannot see them and Headroom cannot tell that a
|
||||
plugin duplicates an entry it manages (#3570). Read-only.
|
||||
|
||||
Whether Claude launches a plugin is decided by ``enabledPlugins`` as
|
||||
resolved for the current working directory, not by the install
|
||||
record's scope or ``projectPath``; see :func:`_enabled_plugins`.
|
||||
"""
|
||||
installed = _read_json(self._installed_plugins).get("plugins")
|
||||
if not isinstance(installed, dict):
|
||||
return []
|
||||
enabled = _enabled_plugins(Path.cwd(), self._settings)
|
||||
found: list[tuple[str, ServerSpec]] = []
|
||||
for plugin_id, records in installed.items():
|
||||
if enabled.get(plugin_id) is not True or not isinstance(records, list):
|
||||
continue
|
||||
for record in records:
|
||||
install_path = record.get("installPath") if isinstance(record, dict) else None
|
||||
if not isinstance(install_path, str) or not install_path:
|
||||
continue
|
||||
entry = _read_plugin_mcp_entry(Path(install_path) / ".mcp.json", server_name)
|
||||
if entry is not None:
|
||||
found.append((plugin_id, _entry_to_spec(server_name, entry)))
|
||||
break
|
||||
return found
|
||||
|
||||
def validate_configs_for_mutation(self) -> None:
|
||||
"""Validate every Claude config root before an explicit mutation."""
|
||||
seen: set[Path] = set()
|
||||
@@ -301,6 +337,43 @@ def _read_json(path: Path) -> dict[str, Any]:
|
||||
return data
|
||||
|
||||
|
||||
def _enabled_plugins(project_dir: Path, user_settings: Path) -> dict[str, Any]:
|
||||
"""Merge ``enabledPlugins`` the way Claude Code resolves it for ``project_dir``.
|
||||
|
||||
Verified against Claude Code 2.1.238: the most specific scope wins
|
||||
(``.claude/settings.local.json`` over ``.claude/settings.json`` in the
|
||||
working directory, over the user ``settings.json``), a plugin with no
|
||||
entry anywhere stays off even when installed, and a subdirectory only
|
||||
counts through its own ``.claude`` settings. ``claude plugin disable``
|
||||
writes ``false`` to one of these files and keeps the install record, so
|
||||
reading all three is what makes that remedy reliably clear a warning.
|
||||
"""
|
||||
merged: dict[str, Any] = {}
|
||||
for path in (
|
||||
user_settings,
|
||||
project_dir / ".claude" / "settings.json",
|
||||
project_dir / ".claude" / "settings.local.json",
|
||||
):
|
||||
flags = _read_json(path).get("enabledPlugins")
|
||||
if isinstance(flags, dict):
|
||||
merged.update(flags)
|
||||
return merged
|
||||
|
||||
|
||||
def _read_plugin_mcp_entry(path: Path, server_name: str) -> dict[str, Any] | None:
|
||||
"""Look up ``server_name`` in a plugin's ``.mcp.json``.
|
||||
|
||||
Plugins in the official marketplace use both documented shapes: a
|
||||
top-level ``mcpServers`` object and a flat ``{name: entry}`` map.
|
||||
"""
|
||||
config = _read_json(path)
|
||||
servers = config.get("mcpServers", config)
|
||||
if not isinstance(servers, dict):
|
||||
return None
|
||||
entry = servers.get(server_name)
|
||||
return entry if isinstance(entry, dict) else None
|
||||
|
||||
|
||||
class _MalformedConfigError(Exception):
|
||||
"""The target config file exists but is not a parseable JSON object.
|
||||
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"issue": 3570,
|
||||
"url": "https://github.com/headroomlabs-ai/headroom/issues/3570",
|
||||
"captured_from": "claude plugin install serena@claude-plugins-official (Claude Code 2.1.238)",
|
||||
"plugin_id": "serena@claude-plugins-official",
|
||||
"plugin_mcp_json": {
|
||||
"serena": {
|
||||
"command": "uvx",
|
||||
"args": ["--from", "git+https://github.com/oraios/serena", "serena", "start-mcp-server"]
|
||||
}
|
||||
},
|
||||
"installed_plugins_json": {
|
||||
"version": 2,
|
||||
"plugins": {
|
||||
"serena@claude-plugins-official": [
|
||||
{
|
||||
"scope": "user",
|
||||
"installPath": "<installPath>",
|
||||
"version": "022b3c274938",
|
||||
"installedAt": "2026-09-13T23:38:36.229Z",
|
||||
"lastUpdated": "2026-09-13T23:38:36.229Z",
|
||||
"gitCommitSha": "022b3c274938ddfb9fd928fc582eb9b9ed0f537f"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"settings_json": {
|
||||
"enabledPlugins": {
|
||||
"serena@claude-plugins-official": true
|
||||
}
|
||||
},
|
||||
"project_scoped_record": {
|
||||
"scope": "project",
|
||||
"installPath": "<installPath>",
|
||||
"version": "da823e86c8fe",
|
||||
"installedAt": "2026-09-14T19:41:37.899Z",
|
||||
"lastUpdated": "2026-09-14T19:41:37.899Z",
|
||||
"gitCommitSha": "da823e86c8feef13b73b6712af11eadd38c992f6",
|
||||
"projectPath": "<projectPath>"
|
||||
}
|
||||
}
|
||||
@@ -289,3 +289,118 @@ def test_mcp_install_force_preserves_user_managed_serena(monkeypatch, tmp_path:
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert json.loads(config.read_text())["mcpServers"]["serena"] == before
|
||||
|
||||
|
||||
PLUGIN_FIXTURE = Path(__file__).parents[1] / "fixtures" / "headroom-issue-3570.json"
|
||||
|
||||
|
||||
def _install_plugin_serena(
|
||||
tmp_path: Path, *, enabled: bool = True, project: Path | None = None
|
||||
) -> list[Path]:
|
||||
"""Mirror ``claude plugin install serena@claude-plugins-official`` on disk.
|
||||
|
||||
A user-scope install writes its ``enabledPlugins`` flag to the user
|
||||
``settings.json``; ``project`` switches to a ``--scope project`` install,
|
||||
whose record carries ``projectPath`` and whose flag lives in that
|
||||
project's ``.claude/settings.json``. Returns the files Claude Code owns so
|
||||
tests can assert Headroom never touches them.
|
||||
"""
|
||||
fixture = json.loads(PLUGIN_FIXTURE.read_text())
|
||||
claude_dir = tmp_path / ".claude"
|
||||
install_path = claude_dir / "plugins" / "cache" / "claude-plugins-official" / "serena" / "v1"
|
||||
install_path.mkdir(parents=True)
|
||||
mcp_json = install_path / ".mcp.json"
|
||||
mcp_json.write_text(json.dumps(fixture["plugin_mcp_json"]))
|
||||
installed = fixture["installed_plugins_json"]
|
||||
if project is None:
|
||||
record = installed["plugins"][fixture["plugin_id"]][0]
|
||||
settings = claude_dir / "settings.json"
|
||||
else:
|
||||
record = fixture["project_scoped_record"]
|
||||
record["projectPath"] = str(project)
|
||||
installed["plugins"][fixture["plugin_id"]] = [record]
|
||||
settings = project / ".claude" / "settings.json"
|
||||
record["installPath"] = str(install_path)
|
||||
registry = claude_dir / "plugins" / "installed_plugins.json"
|
||||
registry.write_text(json.dumps(installed))
|
||||
settings.parent.mkdir(parents=True, exist_ok=True)
|
||||
settings.write_text(json.dumps({"enabledPlugins": {fixture["plugin_id"]: enabled}}))
|
||||
return [mcp_json, registry, settings]
|
||||
|
||||
|
||||
def test_issue_fixture_plugin_serena_is_reported_base_fail_head_pass(monkeypatch, tmp_path: Path):
|
||||
"""#3570: a plugin-provided Serena is invisible to ``get_server`` but must be reported."""
|
||||
config, _ = _setup(monkeypatch, tmp_path)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
data = json.loads(config.read_text())
|
||||
recommended = build_serena_spec("claude-code")
|
||||
data["mcpServers"]["serena"] = {"command": recommended.command, "args": list(recommended.args)}
|
||||
config.write_text(json.dumps(data))
|
||||
plugin_files = _install_plugin_serena(tmp_path)
|
||||
fixture = json.loads(PLUGIN_FIXTURE.read_text())
|
||||
before = [(p.read_bytes(), os.stat(p).st_mtime_ns) for p in plugin_files]
|
||||
|
||||
result = CliRunner().invoke(main, ["mcp", "reconcile"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "observed: present" in result.output
|
||||
plugin_cmd = " ".join(["uvx", *fixture["plugin_mcp_json"]["serena"]["args"]])
|
||||
assert f"plugin: {fixture['plugin_id']} also provides a Serena MCP server ({plugin_cmd})" in (
|
||||
result.output
|
||||
)
|
||||
assert f"claude plugin disable {fixture['plugin_id']}" in result.output
|
||||
assert "use --adopt" not in result.output
|
||||
assert [(p.read_bytes(), os.stat(p).st_mtime_ns) for p in plugin_files] == before
|
||||
|
||||
|
||||
def test_reconcile_is_quiet_once_plugin_serena_is_disabled(monkeypatch, tmp_path: Path):
|
||||
_setup(monkeypatch, tmp_path)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
_install_plugin_serena(tmp_path, enabled=False)
|
||||
|
||||
result = CliRunner().invoke(main, ["mcp", "reconcile"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "plugin:" not in result.output
|
||||
assert "claude plugin disable" not in result.output
|
||||
|
||||
|
||||
def test_reconcile_reports_project_scoped_plugin_only_inside_its_project(
|
||||
monkeypatch, tmp_path: Path
|
||||
):
|
||||
"""Claude launches a ``--scope project`` plugin only where its settings enable it."""
|
||||
_setup(monkeypatch, tmp_path)
|
||||
project = tmp_path / "proj"
|
||||
plugin_files = _install_plugin_serena(tmp_path, project=project)
|
||||
before = [p.read_bytes() for p in plugin_files]
|
||||
|
||||
monkeypatch.chdir(project)
|
||||
inside = CliRunner().invoke(main, ["mcp", "reconcile"])
|
||||
assert inside.exit_code == 0, inside.output
|
||||
assert "claude plugin disable serena@claude-plugins-official" in inside.output
|
||||
|
||||
for elsewhere in (tmp_path, project / "sub"):
|
||||
elsewhere.mkdir(exist_ok=True)
|
||||
monkeypatch.chdir(elsewhere)
|
||||
outside = CliRunner().invoke(main, ["mcp", "reconcile"])
|
||||
assert outside.exit_code == 0, outside.output
|
||||
assert "plugin:" not in outside.output, elsewhere
|
||||
|
||||
# The printed remedy, run inside the project, writes the project scope.
|
||||
settings = project / ".claude" / "settings.json"
|
||||
settings.write_text(json.dumps({"enabledPlugins": {"serena@claude-plugins-official": False}}))
|
||||
monkeypatch.chdir(project)
|
||||
assert "plugin:" not in CliRunner().invoke(main, ["mcp", "reconcile"]).output
|
||||
assert [p.read_bytes() for p in plugin_files[:2]] == before[:2]
|
||||
|
||||
|
||||
def test_adopt_leaves_plugin_serena_files_untouched(monkeypatch, tmp_path: Path):
|
||||
_setup(monkeypatch, tmp_path)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
plugin_files = _install_plugin_serena(tmp_path)
|
||||
before = [p.read_bytes() for p in plugin_files]
|
||||
|
||||
result = CliRunner().invoke(main, ["mcp", "reconcile", "--adopt"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert [p.read_bytes() for p in plugin_files] == before
|
||||
|
||||
@@ -509,3 +509,290 @@ def test_register_via_file_merges_into_existing_valid_config(tmp_path: Path) ->
|
||||
assert data["projects"] == {"/x": {"y": 1}}
|
||||
assert data["oauthAccount"] == {"id": "abc"}
|
||||
assert "headroom" in data["mcpServers"]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# get_plugin_servers() — servers bundled by Claude Code plugins (#3570)
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
_ISSUE_3570 = json.loads(
|
||||
(Path(__file__).parents[1] / "fixtures" / "headroom-issue-3570.json").read_text()
|
||||
)
|
||||
_PLUGIN_ID = _ISSUE_3570["plugin_id"]
|
||||
_PLUGIN_SERENA_ARGS = tuple(_ISSUE_3570["plugin_mcp_json"]["serena"]["args"])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Isolated ``$HOME`` that is also the working directory (no project settings)."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
return tmp_path
|
||||
|
||||
|
||||
def _install_plugin(
|
||||
claude_dir: Path,
|
||||
*,
|
||||
plugin_id: str = _PLUGIN_ID,
|
||||
mcp_json: str | None = None,
|
||||
enabled: bool | None = True,
|
||||
records: list[dict] | None = None,
|
||||
) -> Path:
|
||||
"""Lay out a plugin the way ``claude plugin install`` does under ``claude_dir``.
|
||||
|
||||
Returns the plugin's install path. ``mcp_json`` overrides the raw
|
||||
``.mcp.json`` text (``None`` writes the fixture's flat-map form).
|
||||
``enabled`` is written to the user ``settings.json``; ``None`` writes no
|
||||
``enabledPlugins`` entry at all.
|
||||
"""
|
||||
install_path = claude_dir / "plugins" / "cache" / "market" / plugin_id / "v1"
|
||||
install_path.mkdir(parents=True, exist_ok=True)
|
||||
if mcp_json is None:
|
||||
mcp_json = json.dumps(_ISSUE_3570["plugin_mcp_json"])
|
||||
(install_path / ".mcp.json").write_text(mcp_json, encoding="utf-8")
|
||||
|
||||
registry = claude_dir / "plugins" / "installed_plugins.json"
|
||||
installed = (
|
||||
json.loads(registry.read_text()) if registry.exists() else {"version": 2, "plugins": {}}
|
||||
)
|
||||
if records is None:
|
||||
record = dict(_ISSUE_3570["installed_plugins_json"]["plugins"][_PLUGIN_ID][0])
|
||||
record["installPath"] = str(install_path)
|
||||
records = [record]
|
||||
installed["plugins"][plugin_id] = records
|
||||
registry.write_text(json.dumps(installed), encoding="utf-8")
|
||||
|
||||
if enabled is not None:
|
||||
_set_enabled(claude_dir / "settings.json", enabled, plugin_id=plugin_id)
|
||||
return install_path
|
||||
|
||||
|
||||
def _set_enabled(settings: Path, enabled: bool, *, plugin_id: str = _PLUGIN_ID) -> None:
|
||||
"""Write ``enabledPlugins[plugin_id]`` into a Claude settings file."""
|
||||
settings.parent.mkdir(parents=True, exist_ok=True)
|
||||
data = json.loads(settings.read_text()) if settings.exists() else {}
|
||||
data.setdefault("enabledPlugins", {})[plugin_id] = enabled
|
||||
settings.write_text(json.dumps(data), encoding="utf-8")
|
||||
|
||||
|
||||
def _project_scoped_record(install_path: Path, project: Path) -> dict:
|
||||
record = dict(_ISSUE_3570["project_scoped_record"])
|
||||
record["installPath"] = str(install_path)
|
||||
record["projectPath"] = str(project)
|
||||
return record
|
||||
|
||||
|
||||
def _plugin_ids(reg: ClaudeRegistrar) -> list[str]:
|
||||
return [plugin_id for plugin_id, _ in reg.get_plugin_servers("serena")]
|
||||
|
||||
|
||||
def test_get_plugin_servers_empty_without_plugins(home: Path) -> None:
|
||||
reg = _make_registrar(home, cli=None)
|
||||
assert reg.get_plugin_servers("serena") == []
|
||||
|
||||
|
||||
def test_get_plugin_servers_sees_serena_that_get_server_cannot(home: Path) -> None:
|
||||
_install_plugin(home / ".claude")
|
||||
reg = _make_registrar(home, cli=None)
|
||||
|
||||
assert reg.get_server("serena") is None
|
||||
assert reg.get_plugin_servers("serena") == [
|
||||
(_PLUGIN_ID, ServerSpec(name="serena", command="uvx", args=_PLUGIN_SERENA_ARGS))
|
||||
]
|
||||
|
||||
|
||||
def test_get_plugin_servers_reads_mcp_servers_wrapped_shape(home: Path) -> None:
|
||||
wrapped = json.dumps({"mcpServers": _ISSUE_3570["plugin_mcp_json"]})
|
||||
_install_plugin(home / ".claude", mcp_json=wrapped)
|
||||
reg = _make_registrar(home, cli=None)
|
||||
|
||||
got = reg.get_plugin_servers("serena")
|
||||
|
||||
assert [plugin_id for plugin_id, _ in got] == [_PLUGIN_ID]
|
||||
assert got[0][1].args == _PLUGIN_SERENA_ARGS
|
||||
|
||||
|
||||
def test_get_plugin_servers_skips_disabled_plugin(home: Path) -> None:
|
||||
"""``claude plugin disable`` keeps the install record and flips the flag."""
|
||||
_install_plugin(home / ".claude", enabled=False)
|
||||
reg = _make_registrar(home, cli=None)
|
||||
assert reg.get_plugin_servers("serena") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"settings", [None, "{}", '{"enabledPlugins": null}', '{"enabledPlugins": {}}', "not json"]
|
||||
)
|
||||
def test_get_plugin_servers_requires_an_explicit_enable(home: Path, settings: str | None) -> None:
|
||||
"""An installed plugin with no ``enabledPlugins`` entry anywhere is not launched."""
|
||||
claude_dir = home / ".claude"
|
||||
_install_plugin(claude_dir, enabled=None)
|
||||
if settings is not None:
|
||||
(claude_dir / "settings.json").write_text(settings, encoding="utf-8")
|
||||
reg = _make_registrar(home, cli=None)
|
||||
assert reg.get_plugin_servers("serena") == []
|
||||
|
||||
|
||||
def test_get_plugin_servers_project_install_reports_inside_its_project(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A ``--scope project`` install is enabled by the project's own settings only."""
|
||||
claude_dir = tmp_path / ".claude"
|
||||
project = tmp_path / "proj"
|
||||
install_path = claude_dir / "plugins" / "cache" / "market" / _PLUGIN_ID / "v1"
|
||||
_install_plugin(
|
||||
claude_dir, enabled=None, records=[_project_scoped_record(install_path, project)]
|
||||
)
|
||||
_set_enabled(project / ".claude" / "settings.json", True)
|
||||
reg = _make_registrar(tmp_path, cli=None)
|
||||
|
||||
monkeypatch.chdir(project)
|
||||
assert _plugin_ids(reg) == [_PLUGIN_ID]
|
||||
|
||||
|
||||
def test_get_plugin_servers_project_install_is_quiet_outside_its_project(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
claude_dir = tmp_path / ".claude"
|
||||
project = tmp_path / "proj"
|
||||
install_path = claude_dir / "plugins" / "cache" / "market" / _PLUGIN_ID / "v1"
|
||||
_install_plugin(
|
||||
claude_dir, enabled=None, records=[_project_scoped_record(install_path, project)]
|
||||
)
|
||||
_set_enabled(project / ".claude" / "settings.json", True)
|
||||
reg = _make_registrar(tmp_path, cli=None)
|
||||
|
||||
for elsewhere in (tmp_path, tmp_path / "other", project / "sub"):
|
||||
elsewhere.mkdir(exist_ok=True)
|
||||
monkeypatch.chdir(elsewhere)
|
||||
assert reg.get_plugin_servers("serena") == [], elsewhere
|
||||
|
||||
|
||||
def test_get_plugin_servers_project_disable_silences_user_install(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""``claude plugin disable`` run inside a project writes the project scope."""
|
||||
_install_plugin(tmp_path / ".claude", enabled=True)
|
||||
project = tmp_path / "proj"
|
||||
_set_enabled(project / ".claude" / "settings.json", False)
|
||||
reg = _make_registrar(tmp_path, cli=None)
|
||||
|
||||
monkeypatch.chdir(project)
|
||||
assert reg.get_plugin_servers("serena") == []
|
||||
monkeypatch.chdir(tmp_path)
|
||||
assert _plugin_ids(reg) == [_PLUGIN_ID]
|
||||
|
||||
|
||||
def test_get_plugin_servers_project_enable_overrides_user_disable(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
_install_plugin(tmp_path / ".claude", enabled=False)
|
||||
project = tmp_path / "proj"
|
||||
_set_enabled(project / ".claude" / "settings.json", True)
|
||||
reg = _make_registrar(tmp_path, cli=None)
|
||||
|
||||
monkeypatch.chdir(project)
|
||||
assert _plugin_ids(reg) == [_PLUGIN_ID]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("local", [False, True])
|
||||
def test_get_plugin_servers_local_settings_override_project(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, local: bool
|
||||
) -> None:
|
||||
_install_plugin(tmp_path / ".claude", enabled=None)
|
||||
project = tmp_path / "proj"
|
||||
_set_enabled(project / ".claude" / "settings.json", not local)
|
||||
_set_enabled(project / ".claude" / "settings.local.json", local)
|
||||
reg = _make_registrar(tmp_path, cli=None)
|
||||
|
||||
monkeypatch.chdir(project)
|
||||
assert _plugin_ids(reg) == ([_PLUGIN_ID] if local else [])
|
||||
|
||||
|
||||
def test_get_plugin_servers_reports_each_plugin_once(home: Path) -> None:
|
||||
claude_dir = home / ".claude"
|
||||
install_path = claude_dir / "plugins" / "cache" / "market" / _PLUGIN_ID / "v1"
|
||||
_install_plugin(
|
||||
claude_dir,
|
||||
records=[
|
||||
{"scope": "user", "installPath": str(install_path)},
|
||||
_project_scoped_record(install_path, home),
|
||||
],
|
||||
)
|
||||
reg = _make_registrar(home, cli=None)
|
||||
assert _plugin_ids(reg) == [_PLUGIN_ID]
|
||||
|
||||
|
||||
def test_get_plugin_servers_reports_every_plugin_in_registry_order(home: Path) -> None:
|
||||
claude_dir = home / ".claude"
|
||||
_install_plugin(claude_dir, plugin_id="serena@other")
|
||||
_install_plugin(claude_dir)
|
||||
reg = _make_registrar(home, cli=None)
|
||||
got = reg.get_plugin_servers("serena")
|
||||
assert [plugin_id for plugin_id, _ in got] == ["serena@other", _PLUGIN_ID]
|
||||
assert all(spec.args == _PLUGIN_SERENA_ARGS for _, spec in got)
|
||||
|
||||
|
||||
def test_get_plugin_servers_matches_only_the_requested_name(home: Path) -> None:
|
||||
_install_plugin(home / ".claude")
|
||||
reg = _make_registrar(home, cli=None)
|
||||
assert reg.get_plugin_servers("headroom") == []
|
||||
|
||||
|
||||
def test_get_plugin_servers_reads_explicit_config_dir(home: Path) -> None:
|
||||
config_dir = home / "relocated"
|
||||
_install_plugin(config_dir)
|
||||
_install_plugin(home / ".claude", plugin_id="serena@home")
|
||||
reg = ClaudeRegistrar(claude_cli=None, home_dir=home, config_dir=config_dir)
|
||||
assert _plugin_ids(reg) == [_PLUGIN_ID]
|
||||
|
||||
|
||||
def test_get_plugin_servers_reads_claude_config_dir_env(
|
||||
monkeypatch: pytest.MonkeyPatch, home: Path
|
||||
) -> None:
|
||||
config_dir = home / "relocated"
|
||||
_install_plugin(config_dir)
|
||||
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(config_dir))
|
||||
monkeypatch.setattr(Path, "home", lambda: home)
|
||||
reg = ClaudeRegistrar(claude_cli=None)
|
||||
assert _plugin_ids(reg) == [_PLUGIN_ID]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"contents",
|
||||
[
|
||||
"",
|
||||
"not json",
|
||||
"[]",
|
||||
'{"plugins": []}',
|
||||
'{"plugins": {"x": {}}}',
|
||||
'{"plugins": {"x": [null]}}',
|
||||
'{"plugins": {"x": [{}]}}',
|
||||
'{"plugins": {"x": [{"installPath": ""}]}}',
|
||||
'{"plugins": {"x": [{"installPath": 5}]}}',
|
||||
],
|
||||
)
|
||||
def test_get_plugin_servers_robust_to_bad_registry(home: Path, contents: str) -> None:
|
||||
registry = home / ".claude" / "plugins" / "installed_plugins.json"
|
||||
registry.parent.mkdir(parents=True)
|
||||
registry.write_text(contents, encoding="utf-8")
|
||||
_set_enabled(home / ".claude" / "settings.json", True, plugin_id="x")
|
||||
reg = _make_registrar(home, cli=None)
|
||||
assert reg.get_plugin_servers("serena") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mcp_json",
|
||||
["", "not json", "[]", '{"mcpServers": []}', '{"serena": "oops"}', '{"other": {}}'],
|
||||
)
|
||||
def test_get_plugin_servers_robust_to_bad_plugin_mcp_json(home: Path, mcp_json: str) -> None:
|
||||
_install_plugin(home / ".claude", mcp_json=mcp_json)
|
||||
reg = _make_registrar(home, cli=None)
|
||||
assert reg.get_plugin_servers("serena") == []
|
||||
|
||||
|
||||
def test_get_plugin_servers_tolerates_missing_install_path(home: Path) -> None:
|
||||
_install_plugin(
|
||||
home / ".claude",
|
||||
records=[{"scope": "user", "installPath": str(home / "gone")}],
|
||||
)
|
||||
reg = _make_registrar(home, cli=None)
|
||||
assert reg.get_plugin_servers("serena") == []
|
||||
|
||||
Reference in New Issue
Block a user