fix(mcp): resolve plugin enablement per working directory like Claude Code

Claude Code launches an installed plugin only where `enabledPlugins`
says so for the current directory: `.claude/settings.local.json` beats
`.claude/settings.json` beats the user `settings.json`, a plugin with no
entry anywhere stays off, and the install record's scope/`projectPath`
does not gate it (a subdirectory with its own `.claude` settings launches
it; one without does not). Verified against Claude Code 2.1.238.

Merge the three files in that order and require an explicit `true`
instead of skipping project-scoped records. A `--scope project` install
is now reported inside its project and quiet elsewhere, an installed but
never-enabled plugin no longer warns, and `claude plugin disable` clears
the warning whichever scope it writes to.
This commit is contained in:
Ayushraj06-bit
2026-09-15 01:19:24 +05:30
parent a81f3dc4b9
commit d07ba880e5
4 changed files with 243 additions and 85 deletions
+31 -12
View File
@@ -100,26 +100,22 @@ class ClaudeRegistrar(MCPRegistrar):
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. Only
user-scope installs are considered: a project-scoped record carries
``projectPath`` and is enabled per project.
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 = _read_json(self._settings).get("enabledPlugins")
if not isinstance(enabled, dict):
enabled = {}
enabled = _enabled_plugins(Path.cwd(), self._settings)
found: list[tuple[str, ServerSpec]] = []
for plugin_id, records in installed.items():
# ``claude plugin disable`` flips this flag and keeps the install
# record; a disabled plugin does not start its servers.
if enabled.get(plugin_id) is False or not isinstance(records, list):
if enabled.get(plugin_id) is not True or not isinstance(records, list):
continue
for record in records:
if not isinstance(record, dict) or record.get("projectPath"):
continue
install_path = record.get("installPath")
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)
@@ -341,6 +337,29 @@ 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``.
+9
View File
@@ -28,5 +28,14 @@
"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>"
}
}
+50 -5
View File
@@ -294,11 +294,16 @@ def test_mcp_install_force_preserves_user_managed_serena(monkeypatch, tmp_path:
PLUGIN_FIXTURE = Path(__file__).parents[1] / "fixtures" / "headroom-issue-3570.json"
def _install_plugin_serena(tmp_path: Path, *, enabled: bool = True) -> list[Path]:
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.
Returns the three files Claude Code owns so tests can assert Headroom
never touches them.
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"
@@ -307,10 +312,18 @@ def _install_plugin_serena(tmp_path: Path, *, enabled: bool = True) -> list[Path
mcp_json = install_path / ".mcp.json"
mcp_json.write_text(json.dumps(fixture["plugin_mcp_json"]))
installed = fixture["installed_plugins_json"]
installed["plugins"][fixture["plugin_id"]][0]["installPath"] = str(install_path)
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 = claude_dir / "settings.json"
settings.parent.mkdir(parents=True, exist_ok=True)
settings.write_text(json.dumps({"enabledPlugins": {fixture["plugin_id"]: enabled}}))
return [mcp_json, registry, settings]
@@ -318,6 +331,7 @@ def _install_plugin_serena(tmp_path: Path, *, enabled: bool = True) -> list[Path
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)}
@@ -341,6 +355,7 @@ def test_issue_fixture_plugin_serena_is_reported_base_fail_head_pass(monkeypatch
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"])
@@ -350,8 +365,38 @@ def test_reconcile_is_quiet_once_plugin_serena_is_disabled(monkeypatch, tmp_path
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]
+153 -68
View File
@@ -522,6 +522,13 @@ _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,
*,
@@ -534,7 +541,8 @@ def _install_plugin(
Returns the plugin's install path. ``mcp_json`` overrides the raw
``.mcp.json`` text (``None`` writes the fixture's flat-map form).
``enabled=None`` writes no ``enabledPlugins`` entry at all.
``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)
@@ -554,21 +562,37 @@ def _install_plugin(
registry.write_text(json.dumps(installed), encoding="utf-8")
if enabled is not None:
settings = claude_dir / "settings.json"
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")
_set_enabled(claude_dir / "settings.json", enabled, plugin_id=plugin_id)
return install_path
def test_get_plugin_servers_empty_without_plugins(tmp_path: Path) -> None:
reg = _make_registrar(tmp_path, cli=None)
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(tmp_path: Path) -> None:
_install_plugin(tmp_path / ".claude")
reg = _make_registrar(tmp_path, cli=None)
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") == [
@@ -576,10 +600,10 @@ def test_get_plugin_servers_sees_serena_that_get_server_cannot(tmp_path: Path) -
]
def test_get_plugin_servers_reads_mcp_servers_wrapped_shape(tmp_path: Path) -> None:
def test_get_plugin_servers_reads_mcp_servers_wrapped_shape(home: Path) -> None:
wrapped = json.dumps({"mcpServers": _ISSUE_3570["plugin_mcp_json"]})
_install_plugin(tmp_path / ".claude", mcp_json=wrapped)
reg = _make_registrar(tmp_path, cli=None)
_install_plugin(home / ".claude", mcp_json=wrapped)
reg = _make_registrar(home, cli=None)
got = reg.get_plugin_servers("serena")
@@ -587,89 +611,149 @@ def test_get_plugin_servers_reads_mcp_servers_wrapped_shape(tmp_path: Path) -> N
assert got[0][1].args == _PLUGIN_SERENA_ARGS
def test_get_plugin_servers_skips_disabled_plugin(tmp_path: Path) -> None:
def test_get_plugin_servers_skips_disabled_plugin(home: Path) -> None:
"""``claude plugin disable`` keeps the install record and flips the flag."""
_install_plugin(tmp_path / ".claude", enabled=False)
reg = _make_registrar(tmp_path, cli=None)
_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}', "not json"])
def test_get_plugin_servers_treats_missing_flag_as_enabled(
tmp_path: Path, settings: str | None
) -> None:
claude_dir = tmp_path / ".claude"
@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(tmp_path, cli=None)
assert [plugin_id for plugin_id, _ in reg.get_plugin_servers("serena")] == [_PLUGIN_ID]
def test_get_plugin_servers_skips_project_scoped_record(tmp_path: Path) -> None:
claude_dir = tmp_path / ".claude"
install_path = claude_dir / "plugins" / "cache" / "market" / _PLUGIN_ID / "v1"
_install_plugin(
claude_dir,
records=[
{
"scope": "project",
"installPath": str(install_path),
"projectPath": str(tmp_path / "proj"),
}
],
)
reg = _make_registrar(tmp_path, cli=None)
reg = _make_registrar(home, cli=None)
assert reg.get_plugin_servers("serena") == []
def test_get_plugin_servers_reports_each_plugin_once(tmp_path: Path) -> None:
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)},
{"scope": "managed", "installPath": str(install_path)},
_project_scoped_record(install_path, home),
],
)
reg = _make_registrar(tmp_path, cli=None)
assert [plugin_id for plugin_id, _ in reg.get_plugin_servers("serena")] == [_PLUGIN_ID]
reg = _make_registrar(home, cli=None)
assert _plugin_ids(reg) == [_PLUGIN_ID]
def test_get_plugin_servers_reports_every_plugin_in_registry_order(tmp_path: Path) -> None:
claude_dir = tmp_path / ".claude"
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(tmp_path, cli=None)
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(tmp_path: Path) -> None:
_install_plugin(tmp_path / ".claude")
reg = _make_registrar(tmp_path, cli=None)
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(tmp_path: Path) -> None:
config_dir = tmp_path / "relocated"
def test_get_plugin_servers_reads_explicit_config_dir(home: Path) -> None:
config_dir = home / "relocated"
_install_plugin(config_dir)
_install_plugin(tmp_path / ".claude", plugin_id="serena@home")
reg = ClaudeRegistrar(claude_cli=None, home_dir=tmp_path, config_dir=config_dir)
assert [plugin_id for plugin_id, _ in reg.get_plugin_servers("serena")] == [_PLUGIN_ID]
_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, tmp_path: Path
monkeypatch: pytest.MonkeyPatch, home: Path
) -> None:
config_dir = tmp_path / "relocated"
config_dir = home / "relocated"
_install_plugin(config_dir)
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(config_dir))
monkeypatch.setattr(Path, "home", lambda: tmp_path)
monkeypatch.setattr(Path, "home", lambda: home)
reg = ClaudeRegistrar(claude_cli=None)
assert [plugin_id for plugin_id, _ in reg.get_plugin_servers("serena")] == [_PLUGIN_ID]
assert _plugin_ids(reg) == [_PLUGIN_ID]
@pytest.mark.parametrize(
@@ -686,11 +770,12 @@ def test_get_plugin_servers_reads_claude_config_dir_env(
'{"plugins": {"x": [{"installPath": 5}]}}',
],
)
def test_get_plugin_servers_robust_to_bad_registry(tmp_path: Path, contents: str) -> None:
registry = tmp_path / ".claude" / "plugins" / "installed_plugins.json"
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")
reg = _make_registrar(tmp_path, cli=None)
_set_enabled(home / ".claude" / "settings.json", True, plugin_id="x")
reg = _make_registrar(home, cli=None)
assert reg.get_plugin_servers("serena") == []
@@ -698,16 +783,16 @@ def test_get_plugin_servers_robust_to_bad_registry(tmp_path: Path, contents: str
"mcp_json",
["", "not json", "[]", '{"mcpServers": []}', '{"serena": "oops"}', '{"other": {}}'],
)
def test_get_plugin_servers_robust_to_bad_plugin_mcp_json(tmp_path: Path, mcp_json: str) -> None:
_install_plugin(tmp_path / ".claude", mcp_json=mcp_json)
reg = _make_registrar(tmp_path, cli=None)
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(tmp_path: Path) -> None:
def test_get_plugin_servers_tolerates_missing_install_path(home: Path) -> None:
_install_plugin(
tmp_path / ".claude",
records=[{"scope": "user", "installPath": str(tmp_path / "gone")}],
home / ".claude",
records=[{"scope": "user", "installPath": str(home / "gone")}],
)
reg = _make_registrar(tmp_path, cli=None)
reg = _make_registrar(home, cli=None)
assert reg.get_plugin_servers("serena") == []