Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(wrap): scope Serena's MCP registration to the wrapped project (#2787) (#2992)

Parideboy8cfeb692ca0c
diff --git a/README.md b/README.md
index 389d919b7..c6cf1659b 100644
--- a/README.md
+++ b/README.md
@@ -121,9 +121,10 @@ print(f"Saved {result.tokens_saved} tokens ({result.compression_ratio:.0%})")
Launch a wrapped agent session each time, so the setup runs. `headroom wrap`
starts a local proxy, installs **[Serena](https://github.com/oraios/serena)** for
semantic code navigation, and launches the agent configured to route through
-Headroom. Serena is registered at user scope (for Claude Code, in
-`~/.claude.json`), so it stays available in your other projects until you run
-`headroom unwrap`. Skip it with `--code-memory none`.
+Headroom. For Claude Code, Serena is registered for the wrapped project only
+(as a `local`-scope MCP server in `~/.claude.json`). Use
+`--code-memory-scope user` to make it available in every project, or
+`--code-memory none` to skip it. `headroom unwrap` removes either registration.
The `headroom` CLI ships only in the PyPI package. The npm `headroom-ai` package
is the TypeScript SDK — a library you import
diff --git a/docs/content/docs/proxy.mdx b/docs/content/docs/proxy.mdx
index 19fc5447c..ffc1dc9d3 100644
--- a/docs/content/docs/proxy.mdx
+++ b/docs/content/docs/proxy.mdx
@@ -91,6 +91,8 @@ Avoid setting process-wide variables such as `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_P
`headroom wrap` registers **[Serena](https://github.com/oraios/serena)** as the code-memory MCP for semantic, symbol-level code navigation. Serena runs on demand via `uvx` — Headroom downloads and executes no binary of its own — and indexes the current project locally. Pass `--code-memory none` to register no code-memory MCP.
+For Claude Code, the entry is written at `local` scope, which means it applies to the directory you wrapped and nothing else. That keeps a Serena that cannot start from breaking Claude Code sessions in unrelated projects. Pass `--code-memory-scope user` (or set `HEADROOM_CODE_MEMORY_SCOPE=user`) to register it machine-wide instead, which is how releases before this change behaved. If an earlier version already registered Serena machine-wide, the next `headroom wrap claude` moves it into the project scope for you — but only when Headroom installed that entry itself; a Serena you registered by hand is left alone.
+
> **Upgrading from tokensave?** Earlier releases registered a `tokensave` MCP server (a downloaded Rust binary). tokensave has been retired in favour of Serena. On your next `headroom wrap` / `headroom unwrap`, Headroom removes the `tokensave` MCP entry it installed and switches you to Serena — nothing to migrate, since both are just indexes rebuilt from your source. The leftover `tokensave` binary in `~/.local/bin` and any `.tokensave/` folders are unused and safe to delete.
By default, the proxy uses the shared **ContentRouter** pipeline. It routes text, logs, JSON, code, images, and tool outputs through the currently enabled compressors and preserves reversible CCR markers where applicable.
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index e350d9cc4..210b1b368 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -1070,6 +1070,64 @@ _code_memory_option = click.option(
)
+# --- Code-memory MCP scope (Claude Code only) --------------------------------
+# Where the code-memory MCP entry is written. Claude Code is the only agent we
+# wrap that has scopes: 'project' keeps the entry in ``projects[<cwd>]`` of
+# ~/.claude.json, 'user' puts it in the machine-wide map. Project is the default
+# because a code-memory server that fails to start at user scope degrades every
+# Claude Code session on the machine, including projects Headroom never touched
+# (#2787). Flows through an env var for the same reason as _code_memory_option.
+_CODE_MEMORY_SCOPE_ENV = "HEADROOM_CODE_MEMORY_SCOPE"
+_CODE_MEMORY_SCOPE_PROJECT = "project"
+_CODE_MEMORY_SCOPE_USER = "user"
+_VALID_CODE_MEMORY_SCOPES = {_CODE_MEMORY_SCOPE_PROJECT, _CODE_MEMORY_SCOPE_USER}
+
+
+def _resolve_code_memory_scope() -> str:
+ """Resolve the requested code-memory scope ('project' by default)."""
+ env = os.environ.get(_CODE_MEMORY_SCOPE_ENV, "").strip().lower()
+ if env:
+ if env not in _VALID_CODE_MEMORY_SCOPES:
+ raise click.ClickException(
+ f"{_CODE_MEMORY_SCOPE_ENV} must be one of: "
+ f"{', '.join(sorted(_VALID_CODE_MEMORY_SCOPES))}"
+ )
+ return env
+ return _CODE_MEMORY_SCOPE_PROJECT
+
+
+def _claude_code_memory_scope() -> str:
+ """Translate the requested scope into Claude Code's own scope name."""
+ from headroom.mcp_registry.claude import SCOPE_LOCAL, SCOPE_USER
+
+ if _resolve_code_memory_scope() == _CODE_MEMORY_SCOPE_USER:
+ return SCOPE_USER
+ return SCOPE_LOCAL
+
+
+def _code_memory_scope_flag_callback(ctx: Any, param: Any, value: str | None) -> str | None:
+ """Click eager callback: mirror ``--code-memory-scope`` into the env var the
+ resolver reads, so no subcommand signature changes."""
+ if value:
+ os.environ[_CODE_MEMORY_SCOPE_ENV] = value
+ return value
+
+
+_code_memory_scope_option = click.option(
+ "--code-memory-scope",
+ type=click.Choice([_CODE_MEMORY_SCOPE_PROJECT, _CODE_MEMORY_SCOPE_USER]),
+ default=None,
+ expose_value=False,
+ is_eager=True,
+ callback=_code_memory_scope_flag_callback,
+ help=(
+ "Where to register the code-memory MCP: 'project' (default, this "
+ "directory only) or 'user' (every Claude Code session on the machine). "
+ "Also set by HEADROOM_CODE_MEMORY_SCOPE."
+ ),
+)
+
+
# Hook-command markers Headroom manages in Claude settings.json. unwrap drops
# any hook entry whose command contains one of these. (Retired rtk / lean-ctx
# hooks are removed separately, by
@@ -2460,6 +2518,8 @@ def _setup_serena_mcp(
from headroom.mcp_registry.base import RegisterStatus
from headroom.mcp_registry.ledger import headroom_installed_matching, record_install
+ ownership_key = getattr(registrar, "ownership_key", lambda name: name)("serena")
+
if not registrar.detect():
if verbose:
click.echo(f" Serena MCP: {registrar.display_name} not detected — skipping")
@@ -2477,7 +2537,9 @@ def _setup_serena_mcp(
owned_drift = (
result.status == RegisterStatus.MISMATCH
and not force
- and headroom_installed_matching(registrar.name, registrar.get_server("serena"))
+ and headroom_installed_matching(
+ registrar.name, registrar.get_server("serena"), ownership_key=ownership_key
+ )
)
# Migrate a stale Headroom-installed entry. register_server won't overwrite
@@ -2490,8 +2552,15 @@ def _setup_serena_mcp(
if result.status == RegisterStatus.REGISTERED:
click.echo(" Serena MCP: migrated previously-installed entry to current spec")
+ # Retire the machine-wide entry once the project-scoped one is in place.
+ # Must run before record_install below: the ledger still holds the
+ # fingerprint of the entry that was installed globally, which is how we
+ # recognise it as ours.
+ if result.ok:
+ _retire_user_scope_serena(registrar)
+
if result.status == RegisterStatus.REGISTERED:
- record_install(registrar.name, spec)
+ record_install(registrar.name, spec, ownership_key=ownership_key)
line = format_result(
registrar.name,
@@ -2510,6 +2579,11 @@ def _setup_serena_mcp(
if line is not None:
click.echo(line)
+ # Say where it landed, so the scope is discoverable without reading docs.
+ # Only on an actual write (or in verbose): re-wraps should stay quiet.
+ if result.status == RegisterStatus.REGISTERED or verbose:
+ _echo_serena_scope_note(registrar)
+
# Serena is the active engine here (we passed the detect/uvx guards): steer
# the agent toward symbol-level tools, then warm the symbol cache. Both are
# best-effort and non-fatal, and neither blocks the launch: the pre-index
@@ -2535,10 +2609,90 @@ def _setup_serena_mcp(
_index_serena_project(verbose=verbose)
+def _echo_serena_scope_note(registrar: Any) -> None:
+ """Tell the user which sessions the Serena entry will load in."""
+ from headroom.mcp_registry.claude import SCOPE_LOCAL, SCOPE_USER
+
+ scope = getattr(registrar, "scope", None)
+ if scope == SCOPE_LOCAL:
+ click.echo(
+ " scoped to this project — pass --code-memory-scope user to register it "
+ "for every Claude Code session"
+ )
+ elif scope == SCOPE_USER:
+ click.echo(
+ " registered for every Claude Code session on this machine "
+ "(--code-memory-scope user)"
+ )
+
+
+def _retire_user_scope_serena(registrar: Any) -> None:
+ """Remove a machine-wide Serena entry left by a pre-#2787 wrap.
+
+ Headroom used to register Serena at Claude Code's user scope, where a
+ Serena that fails to start breaks *every* Claude Code session on the
+ machine — including projects that were never wrapped (#2783). Now that the
+ entry is written per project, the global one is redundant, so an upgrading
+ user gets it cleaned up on their next wrap instead of carrying the blast
+ radius forever.
+
+ Only entries the ledger proves Headroom installed are removed; a Serena the
+ user registered globally themselves is left exactly where it is. No-ops for
+ registrars without scopes (Codex, Grok, OpenCode) and when the user asked
+ for user scope explicitly.
+ """
+ from headroom.mcp_registry.claude import SCOPE_LOCAL, SCOPE_USER
+ from headroom.mcp_registry.ledger import clear_install, headroom_installed_matching
+
+ if getattr(registrar, "scope", None) != SCOPE_LOCAL:
+ return
+ try:
+ global_entry = registrar.get_server("serena", scope=SCOPE_USER)
+ except TypeError: # registrar predates scoped reads
+ return
+ if not headroom_installed_matching(registrar.name, global_entry):
+ return
+ if registrar.unregister_server("serena", scope=SCOPE_USER):
+ # Clear the legacy ledger record along with the config entry it
+ # authorized — otherwise its fingerprint outlives the migration and
+ # can later be mistaken for proof that Headroom owns a same-named
+ # entry the user installs globally themselves.
+ clear_install(registrar.name, "serena")
+ click.echo(
+ " Serena MCP: removed the machine-wide entry an earlier wrap installed "
+ "(it now loads only in this project)"
+ )
+
+
def _remove_headroom_installed_serena_mcp(registrar: Any) -> str:
"""Remove Serena MCP only if the ledger proves Headroom installed it."""
from headroom.mcp_registry.ledger import clear_install, headroom_installed_matching
+ # Claude can own one Serena entry per project plus a legacy user entry.
+ # Examine each relevant scope independently: an unscoped delete would
+ # remove entries whose scope-specific ledger record did not authorize it.
+ if hasattr(registrar, "ownership_key"):
+ from headroom.mcp_registry.claude import SCOPE_LOCAL, SCOPE_USER
+
+ found_owned = False
+ for scope in (SCOPE_LOCAL, SCOPE_USER):
+ current = registrar.get_server("serena", scope=scope)
+ ownership_key = registrar.ownership_key("serena", scope=scope)
+ if current is None:
+ # Nothing left to protect — an ownership record must not
+ # outlive the entry it authorized.
+ clear_install(registrar.name, "serena", ownership_key=ownership_key)
+ continue
+ if not headroom_installed_matching(
+ registrar.name, current, ownership_key=ownership_key
+ ):
+ continue
+ found_owned = True
+ if not registrar.unregister_server("serena", scope=scope):
+ return "failed"
+ clear_install(registrar.name, "serena", ownership_key=ownership_key)
+ return "removed" if found_owned else "not_headroom_owned"
+
current = registrar.get_server("serena")
if not headroom_installed_matching(registrar.name, current):
return "not_headroom_owned"
@@ -2596,10 +2750,21 @@ def _remove_headroom_installed_tokensave_mcp(registrar: Any) -> str:
"""Remove the tokensave MCP entry only if the ledger proves Headroom installed it."""
from headroom.mcp_registry.ledger import clear_install, headroom_installed_matching
- current = registrar.get_server("tokensave")
+ # Headroom only ever installed tokensave machine-wide: it was retired before
+ # #2787 introduced project scope, so its ledger key is the pre-scope (user
+ # scope) one. Pin the ownership check and the delete to that scope — an
+ # unscoped delete now also takes the project entry, which no ledger record
+ # authorizes, and an unscoped read lets a project entry shadow ours.
+ at_user_scope: dict[str, Any] = {}
+ if hasattr(registrar, "ownership_key"): # Claude; the others have no scopes
+ from headroom.mcp_registry.claude import SCOPE_USER
+
+ at_user_scope = {"scope": SCOPE_USER}
+
+ current = registrar.get_server("tokensave", **at_user_scope)
if not headroom_installed_matching(registrar.name, current):
return "not_headroom_owned"
- if registrar.unregister_server("tokensave"):
+ if registrar.unregister_server("tokensave", **at_user_scope):
clear_install(registrar.name, "tokensave")
return "removed"
return "failed"
@@ -5460,6 +5625,7 @@ def wrap_selfheal(marker: str | None) -> None:
help="Skip headroom MCP server registration (compression markers will be unactionable)",
)
@_code_memory_option
+@_code_memory_scope_option
@click.option(
"--no-tokensave",
is_flag=True,
@@ -5559,6 +5725,7 @@ def claude(
headroom wrap claude -- -p # Claude in print mode
headroom wrap claude --no-mcp # Skip MCP retrieve tool registration
headroom wrap claude --code-memory none # No code-memory MCP
+ headroom wrap claude --code-memory-scope user # Serena in every session, not just here
headroom wrap claude --1m # Preserve the 1M context window
"""
if prepare_only:
@@ -5700,10 +5867,15 @@ def claude(
click.echo(" Skipping MCP retrieve tool (--no-mcp)")
# Coding-task compressor: Serena (retires any legacy tokensave entry).
+ # Registered per project by default so a Serena that cannot start takes
+ # down this project's sessions only, never every Claude Code session on
+ # the machine (#2787). --code-memory-scope user restores the old
+ # machine-wide registration. The Headroom MCP registrar above keeps user
+ # scope: it is our own server and every wrap exercises it.
from headroom.mcp_registry import CLAUDE_SERENA_CONTEXT, ClaudeRegistrar
_setup_coding_compressor(
- ClaudeRegistrar(),
+ ClaudeRegistrar(scope=_claude_code_memory_scope()),
serena_context=CLAUDE_SERENA_CONTEXT,
serena=serena,
no_serena=no_serena,
diff --git a/headroom/mcp_registry/claude.py b/headroom/mcp_registry/claude.py
index dd4402b72..64a9afab4 100644
--- a/headroom/mcp_registry/claude.py
+++ b/headroom/mcp_registry/claude.py
@@ -1,13 +1,28 @@
"""Claude Code MCP registrar.
-Claude Code 2.x stores user-scope MCP server configuration in
-``~/.claude.json``, directly under the home directory. The ``claude`` CLI
-(``claude mcp add/remove/list/get``) owns this file; setting
-``CLAUDE_CONFIG_DIR`` relocates it to ``$CLAUDE_CONFIG_DIR/.claude.json``.
-Older Claude Code releases (and the Claude Desktop app) read
-``~/.claude/mcp.json`` instead. This registrar prefers the CLI for writes
-when available, and reads the underlying JSON files directly for compare /
-``get_server`` so it is robust to CLI output format changes.
+Claude Code 2.x stores MCP server configuration in ``~/.claude.json``,
+directly under the home directory. The ``claude`` CLI (``claude mcp
+add/remove/list/get``) owns this file; setting ``CLAUDE_CONFIG_DIR``
+relocates it to ``$CLAUDE_CONFIG_DIR/.claude.json``. Older Claude Code
+releases (and the Claude Desktop app) read ``~/.claude/mcp.json`` instead.
+This registrar prefers the CLI for writes when available, and reads the
+underlying JSON files directly for compare / ``get_server`` so it is robust
+to CLI output format changes.
+
+Two of Claude Code's scopes matter here (see ``claude mcp add --scope``):
+
+``user``
+ The top-level ``mcpServers`` map. Loads in **every** Claude Code session
+ on the machine, in every directory.
+``local``
+ ``projects[<cwd>].mcpServers``. Loads only for sessions started in that
+ one directory, and takes precedence over a user-scope entry of the same
+ name.
+
+Scope is a blast-radius decision, not a preference: a server registered at
+user scope that fails to start degrades every session on the machine, not
+just the project it was installed for (#2787). Servers whose failure modes
+we do not control belong at ``local``.
"""
from __future__ import annotations
@@ -25,6 +40,14 @@ from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec
logger = logging.getLogger(__name__)
+#: Claude Code scope covering every session on the machine.
+SCOPE_USER = "user"
+
+#: Claude Code scope covering only sessions started in one directory.
+SCOPE_LOCAL = "local"
+
+_VALID_SCOPES = (SCOPE_USER, SCOPE_LOCAL)
+
class ClaudeConfigMutationError(ValueError):
"""Raised when a Claude config cannot be safely changed."""
@@ -42,6 +65,8 @@ class ClaudeRegistrar(MCPRegistrar):
claude_cli: str | None | object = ...,
home_dir: Path | None = None,
config_dir: Path | None = None,
+ scope: str = SCOPE_USER,
+ project_dir: Path | None = None,
) -> None:
"""Allow overrides for testing.
@@ -53,7 +78,20 @@ class ClaudeRegistrar(MCPRegistrar):
is passed explicitly. It does not isolate CLI subprocess calls (see
``claude_cli``) — pass ``claude_cli=None`` alongside ``home_dir`` to
keep a test fully off the real ``claude`` binary.
+
+ ``scope`` selects where :meth:`register_server` writes: ``"user"``
+ (default, machine-wide) or ``"local"`` (the current project only).
+ Reads and removals span both scopes unless told otherwise, so a
+ caller that switches scope still finds — and can clean up — an entry
+ an earlier release installed elsewhere. ``project_dir`` overrides the
+ directory ``local`` scope resolves to (test seam); real callers rely
+ on the process working directory, which is what Claude Code itself
+ keys sessions by.
"""
+ if scope not in _VALID_SCOPES:
+ raise ValueError(f"scope must be one of {_VALID_SCOPES}, got {scope!r}")
+ self.scope = scope
+ self._project_dir_override = project_dir
home = home_dir if home_dir is not None else Path.home()
modern_dir = _resolve_claude_config_dir(home, config_dir, honor_env=home_dir is None)
# Legacy config lives under the real ``.claude`` directory regardless
@@ -84,13 +122,22 @@ class ClaudeRegistrar(MCPRegistrar):
return True
return self._claude_dir.is_dir() or self._modern_config.exists()
- def get_server(self, server_name: str) -> ServerSpec | None:
+ def get_server(self, server_name: str, *, scope: str | None = None) -> ServerSpec | None:
+ """Return the registered spec, or ``None``.
+
+ With no ``scope``, search project scope first, then user scope — the
+ order Claude Code itself resolves them in, so the answer is the entry
+ the agent would actually launch. Pass ``scope`` to ask about one
+ specific location (e.g. "is there still a user-scope entry to clean
+ up?").
+ """
# Read from disk regardless of whether the CLI is present — the file
# format is stable and easier to compare than CLI output.
- for config_path in (self._modern_config, self._legacy_config):
- entry = self._read_server_entry(config_path, server_name)
- if entry is not None:
- return entry
+ for search_scope in self._scopes(scope):
+ for config_path in self._config_paths(search_scope):
+ entry = self._read_server_entry(config_path, server_name, search_scope)
+ if entry is not None:
+ return entry
return None
def get_plugin_servers(self, server_name: str) -> list[tuple[str, ServerSpec]]:
@@ -153,7 +200,10 @@ class ClaudeRegistrar(MCPRegistrar):
)
def register_server(self, spec: ServerSpec, *, force: bool = False) -> RegisterResult:
- existing = self.get_server(spec.name)
+ # Compare against the entry in the scope we are about to write, not
+ # against any entry anywhere: a leftover user-scope copy must not make
+ # a project-scope registration look like a no-op.
+ existing = self.get_server(spec.name, scope=self.scope)
if existing is not None:
if _specs_equivalent(existing, spec):
return RegisterResult(RegisterStatus.ALREADY, "matches current configuration")
@@ -162,30 +212,42 @@ class ClaudeRegistrar(MCPRegistrar):
RegisterStatus.MISMATCH,
_diff_specs(existing, spec),
)
- # force=True: remove first, then write fresh below.
- self.unregister_server(spec.name)
+ # force=True: remove first, then write fresh below. Restricted to
+ # the scope we are writing — overwriting the project entry must not
+ # also delete a machine-wide one the user registered themselves.
+ self.unregister_server(spec.name, scope=self.scope)
if self._claude_cli:
return self._register_via_cli(spec)
return self._register_via_file(spec)
- def unregister_server(self, server_name: str) -> bool:
+ def unregister_server(self, server_name: str, *, scope: str | None = None) -> bool:
+ """Remove the named server. Returns True if anything was removed.
+
+ With no ``scope``, remove from user scope *and* the current project's
+ scope, so ``unwrap`` cleans up no matter which one installed the entry
+ (a pre-#2787 release put Serena at user scope). Only the current
+ project is touched — unwrapping one project must not deregister the
+ server in every other project it was wrapped into.
+ """
removed = False
- if self._claude_cli:
- result = run(
- [str(self._claude_cli), "mcp", "remove", server_name, "-s", "user"],
- capture_output=True,
- text=True,
- env=self._claude_cli_env(),
- )
- if result.returncode == 0:
- removed = True
- else:
- logger.debug("claude mcp remove failed: %s", result.stderr.strip())
- # Always clean up both files too — the CLI only touches the modern
- # config, so a legacy entry (or one it didn't know about) can remain.
- for config_path in (self._modern_config, self._legacy_config):
- removed = self._remove_from_file(config_path, server_name) or removed
+ for target_scope in self._scopes(scope):
+ if self._claude_cli:
+ result = run(
+ [str(self._claude_cli), "mcp", "remove", server_name, "-s", target_scope],
+ capture_output=True,
+ text=True,
+ env=self._claude_cli_env(),
+ cwd=self._cli_cwd(target_scope),
+ )
+ if result.returncode == 0:
+ removed = True
+ else:
+ logger.debug("claude mcp remove failed: %s", result.stderr.strip())
+ # Always clean up the files too — the CLI only touches the modern
+ # config, so a legacy entry (or one it didn't know about) can remain.
+ for config_path in self._config_paths(target_scope):
+ removed = self._remove_from_file(config_path, server_name, target_scope) or removed
return removed
# ------------------------------------------------------------------
@@ -193,7 +255,7 @@ class ClaudeRegistrar(MCPRegistrar):
# ------------------------------------------------------------------
def _register_via_cli(self, spec: ServerSpec) -> RegisterResult:
- cmd = [str(self._claude_cli), "mcp", "add", spec.name, "-s", "user"]
+ cmd = [str(self._claude_cli), "mcp", "add", spec.name, "-s", self.scope]
for k, v in spec.env.items():
cmd += ["-e", f"{k}={v}"]
cmd += ["--", spec.command, *spec.args]
@@ -203,9 +265,12 @@ class ClaudeRegistrar(MCPRegistrar):
capture_output=True,
text=True,
env=self._claude_cli_env(),
+ cwd=self._cli_cwd(self.scope),
)
if result.returncode == 0:
- return RegisterResult(RegisterStatus.REGISTERED, "via `claude mcp add` (scope: user)")
+ return RegisterResult(
+ RegisterStatus.REGISTERED, f"via `claude mcp add` (scope: {self.scope})"
+ )
# CLI failed — try the file fallback rather than giving up.
logger.warning("claude mcp add failed: %s", result.stderr.strip())
file_result = self._register_via_file(spec)
@@ -225,17 +290,20 @@ class ClaudeRegistrar(MCPRegistrar):
def _register_via_file(self, spec: ServerSpec) -> RegisterResult:
# Prefer the modern config path. If only the legacy file exists,
- # write to that to avoid surprising older clients.
+ # write to that to avoid surprising older clients — but project scope
+ # only exists in the modern config, so it always goes there.
target = self._modern_config
- if not self._modern_config.exists() and self._legacy_config.exists():
+ if (
+ self.scope == SCOPE_USER
+ and not self._modern_config.exists()
+ and self._legacy_config.exists()
+ ):
target = self._legacy_config
try:
target.parent.mkdir(parents=True, exist_ok=True)
config = _read_json_for_write(target)
- servers = config.get("mcpServers")
- if not isinstance(servers, dict):
- config["mcpServers"] = servers = {}
+ servers = self._servers_map_for_write(config)
servers[spec.name] = _spec_to_entry(spec)
_write_json(target, config)
except _MalformedConfigError as exc:
@@ -248,17 +316,17 @@ class ClaudeRegistrar(MCPRegistrar):
)
except OSError as exc:
return RegisterResult(RegisterStatus.FAILED, f"could not write {target}: {exc}")
- return RegisterResult(RegisterStatus.REGISTERED, f"wrote to {target}")
+ return RegisterResult(RegisterStatus.REGISTERED, f"wrote to {target} (scope: {self.scope})")
- def _remove_from_file(self, path: Path, server_name: str) -> bool:
+ def _remove_from_file(self, path: Path, server_name: str, scope: str) -> bool:
if not path.exists():
return False
try:
config = _read_json(path)
except OSError:
return False
- servers = config.get("mcpServers")
- if not isinstance(servers, dict) or server_name not in servers:
+ servers = self._servers_map(config, scope)
+ if servers is None or server_name not in servers:
return False
del servers[server_name]
try:
@@ -267,25 +335,125 @@ class ClaudeRegistrar(MCPRegistrar):
return False
return True
- def _read_server_entry(self, path: Path, server_name: str) -> ServerSpec | None:
+ def _read_server_entry(self, path: Path, server_name: str, scope: str) -> ServerSpec | None:
if not path.exists():
return None
try:
config = _read_json(path)
except OSError:
return None
- servers = config.get("mcpServers")
- if not isinstance(servers, dict):
+ servers = self._servers_map(config, scope)
+ if servers is None:
return None
entry = servers.get(server_name)
if not isinstance(entry, dict):
return None
return _entry_to_spec(server_name, entry)
+ # ----------------------------------------------------------------------
+ # Scope helpers
+ # ----------------------------------------------------------------------
+
+ def _scopes(self, scope: str | None) -> tuple[str, ...]:
+ """Scopes to act on: the one requested, or project-then-user."""
+ if scope is not None:
+ if scope not in _VALID_SCOPES:
+ raise ValueError(f"scope must be one of {_VALID_SCOPES}, got {scope!r}")
+ return (scope,)
+ return (SCOPE_LOCAL, SCOPE_USER)
+
+ def _config_paths(self, scope: str) -> tuple[Path, ...]:
+ """Config files that can hold an entry at ``scope``.
+
+ The legacy ``~/.claude/mcp.json`` has no notion of projects, so it is
+ only consulted for user scope.
+ """
+ if scope == SCOPE_LOCAL:
+ return (self._modern_config,)
+ return (self._modern_config, self._legacy_config)
+
+ def _project_dir(self) -> Path:
+ """Directory project scope applies to (the session's working directory)."""
+ if self._project_dir_override is not None:
+ return self._project_dir_override
+ return Path.cwd()
+
+ def ownership_key(self, server_name: str, *, scope: str | None = None) -> str:
+ """Stable ledger key for one Claude scope without exposing config paths."""
+ target_scope = scope or self.scope
+ if target_scope == SCOPE_USER:
+ # Preserve the pre-scope key so existing installs migrate safely.
+ return server_name
+ project = os.path.normcase(os.path.normpath(str(self._project_dir().resolve())))
+ return f"{server_name}:local:{project}"
+
+ def _project_key(self, config: dict[str, Any]) -> str:
+ """Key under ``projects`` naming the current directory.
+
+ Claude Code keys this map by the session's working directory as a
+ string — with forward slashes even on Windows. Reuse whatever key an
+ existing entry already uses when it names the same directory, so we
+ never add a second entry Claude Code will not read; otherwise write
+ the forward-slash form it would write itself.
+ """
+ cwd = self._project_dir()
+ target = os.path.normcase(os.path.normpath(str(cwd)))
+ projects = config.get("projects")
+ if isinstance(projects, dict):
+ for key in projects:
+ if isinstance(key, str) and os.path.normcase(os.path.normpath(key)) == target:
+ return key
+ return cwd.as_posix()
+
+ def _servers_map(self, config: dict[str, Any], scope: str) -> dict[str, Any] | None:
+ """Return the ``mcpServers`` map for ``scope``, or ``None`` if absent.
+
+ Read-only: the returned dict is the one inside ``config``, so callers
+ on the write path can mutate it, but nothing is created here.
+ """
+ container: Any = config
+ if scope == SCOPE_LOCAL:
+ projects = config.get("projects")
+ if not isinstance(projects, dict):
+ return None
+ container = projects.get(self._project_key(config))
+ if not isinstance(container, dict):
+ return None
+ servers = container.get("mcpServers")
+ return servers if isinstance(servers, dict) else None
+
+ def _servers_map_for_write(self, config: dict[str, Any]) -> dict[str, Any]:
+ """Return the ``mcpServers`` map for this registrar's scope, creating it."""
+ container: dict[str, Any] = config
+ if self.scope == SCOPE_LOCAL:
+ projects = config.get("projects")
+ if not isinstance(projects, dict):
+ config["projects"] = projects = {}
+ key = self._project_key(config)
+ project = projects.get(key)
+ if not isinstance(project, dict):
+ projects[key] = project = {}
+ container = project
+ servers = container.get("mcpServers")
+ if not isinstance(servers, dict):
+ container["mcpServers"] = servers = {}
+ return servers
+
# ----------------------------------------------------------------------
# Helpers
# ----------------------------------------------------------------------
+ def _cli_cwd(self, scope: str) -> str | None:
+ """Working directory for a CLI call, or ``None`` to inherit ours.
+
+ ``claude mcp add -s local`` keys the entry by the *CLI process's*
+ working directory, so a registrar pointed at a different project
+ directory has to move the subprocess with it.
+ """
+ if scope != SCOPE_LOCAL or self._project_dir_override is None:
+ return None
+ return str(self._project_dir_override)
+
def _claude_cli_env(self) -> dict[str, str] | None:
if not self._isolated_cli_env:
return None
diff --git a/headroom/mcp_registry/ledger.py b/headroom/mcp_registry/ledger.py
index b7fcdba91..af1d1b634 100644
--- a/headroom/mcp_registry/ledger.py
+++ b/headroom/mcp_registry/ledger.py
@@ -42,7 +42,13 @@ def spec_fingerprint(spec: ServerSpec) -> str:
return hashlib.sha256(raw).hexdigest()
-def record_install(agent: str, spec: ServerSpec, *, path: Path | None = None) -> None:
+def record_install(
+ agent: str,
+ spec: ServerSpec,
+ *,
+ path: Path | None = None,
+ ownership_key: str | None = None,
+) -> None:
"""Record that Headroom installed ``spec`` for ``agent``."""
ledger_file = path or ledger_path()
# Automatic installs must recover from a stale or damaged ledger. The
@@ -56,14 +62,20 @@ def record_install(agent: str, spec: ServerSpec, *, path: Path | None = None) ->
if not isinstance(agent_entry, dict):
agent_entry = {}
agents[agent] = agent_entry
- agent_entry[spec.name] = {
+ agent_entry[ownership_key or spec.name] = {
"fingerprint": spec_fingerprint(spec),
"installed_at": datetime.now(timezone.utc).isoformat(),
}
_write_ledger(ledger_file, data)
-def clear_install(agent: str, server_name: str, *, path: Path | None = None) -> None:
+def clear_install(
+ agent: str,
+ server_name: str,
+ *,
+ path: Path | None = None,
+ ownership_key: str | None = None,
+) -> None:
"""Remove one ledger entry if present."""
ledger_file = path or ledger_path()
data = _read_ledger(ledger_file)
@@ -71,9 +83,10 @@ def clear_install(agent: str, server_name: str, *, path: Path | None = None) ->
if not isinstance(agents, dict):
return
agent_entry = agents.get(agent)
- if not isinstance(agent_entry, dict) or server_name not in agent_entry:
+ key = ownership_key or server_name
+ if not isinstance(agent_entry, dict) or key not in agent_entry:
return
- del agent_entry[server_name]
+ del agent_entry[key]
if not agent_entry:
del agents[agent]
if not agents:
@@ -86,6 +99,7 @@ def headroom_installed_matching(
current_spec: ServerSpec | None,
*,
path: Path | None = None,
+ ownership_key: str | None = None,
) -> bool:
"""Return True when the ledger says Headroom installed ``current_spec``."""
if current_spec is None:
@@ -93,7 +107,7 @@ def headroom_installed_matching(
ledger_file = path or ledger_path()
data = _read_ledger(ledger_file)
try:
- entry = data["agents"][agent][current_spec.name]
+ entry = data["agents"][agent][ownership_key or current_spec.name]
except (KeyError, TypeError):
return False
if not isinstance(entry, dict):
diff --git a/tests/test_cli/test_serena_scope.py b/tests/test_cli/test_serena_scope.py
new file mode 100644
index 000000000..a3f3e0a19
--- /dev/null
+++ b/tests/test_cli/test_serena_scope.py
@@ -0,0 +1,329 @@
+"""Serena is registered for the wrapped project, not the whole machine (#2787).
+
+Headroom used to register Serena at Claude Code's ``user`` scope, so every
+Claude Code session on the machine launched it — including sessions in
+projects that were never wrapped. When Serena could not start, that took down
+Claude Code everywhere, and the only recovery was ``headroom unwrap claude``
+(#2783).
+
+``headroom wrap claude`` now registers Serena at ``local`` scope: it loads
+only in the directory that was wrapped. ``--code-memory-scope user`` restores
+the old machine-wide behaviour, and an existing global entry that Headroom
+installed is retired on the next wrap.
+
+These tests drive ``_setup_serena_mcp`` with a real ``ClaudeRegistrar`` whose
+home directory is a tmp_path, so the assertions are about the JSON Claude Code
+actually reads.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from headroom.cli import wrap as wrap_cli
+from headroom.mcp_registry import build_serena_spec
+from headroom.mcp_registry.base import ServerSpec
+from headroom.mcp_registry.claude import SCOPE_LOCAL, SCOPE_USER, ClaudeRegistrar
+from headroom.mcp_registry.ledger import record_install
+
+
[email protected](autouse=True)
+def _isolate_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / ".headroom"))
+ monkeypatch.delenv("HEADROOM_CODE_MEMORY_SCOPE", raising=False)
+ # ``_setup_serena_mcp`` bails out early when uvx is missing, which would
+ # skip every path under test on runners without uv installed.
+ real_which = shutil.which
+ monkeypatch.setattr(
+ wrap_cli.shutil,
+ "which",
+ lambda name, *a, **k: "/usr/bin/uvx" if name == "uvx" else real_which(name, *a, **k),
+ )
+ # Everything past registration touches the real home directory or shells
+ # out to uvx. Covered elsewhere; neutralise it so these stay hermetic.
+ monkeypatch.setattr(wrap_cli, "_ensure_serena_dashboard_disabled", lambda *a, **k: None)
+ monkeypatch.setattr(wrap_cli, "_inject_serena_instructions", lambda *a, **k: True)
+ monkeypatch.setattr(wrap_cli, "_index_serena_project", lambda *a, **k: None)
+
+
+def _registrar(tmp_path: Path, *, scope: str = SCOPE_LOCAL) -> ClaudeRegistrar:
+ """Real registrar writing into ``tmp_path`` instead of the user's home."""
+ # With no CLI, ``detect`` looks for a ~/.claude directory or config file.
+ (tmp_path / ".claude").mkdir(exist_ok=True)
+ return ClaudeRegistrar(
+ claude_cli=None, # force the file path; never touch the real CLI
+ home_dir=tmp_path,
+ scope=scope,
+ project_dir=tmp_path / "proj",
+ )
+
+
+def _config(tmp_path: Path) -> dict[str, Any]:
+ return json.loads((tmp_path / ".claude.json").read_text(encoding="utf-8"))
+
+
+def _project_servers(tmp_path: Path) -> dict[str, Any]:
+ project_key = (tmp_path / "proj").as_posix()
+ return _config(tmp_path)["projects"][project_key]["mcpServers"]
+
+
+def _seed_global_serena(tmp_path: Path, spec: ServerSpec) -> None:
+ """Write ``spec`` into the machine-wide map, as a pre-#2787 wrap did."""
+ entry: dict[str, Any] = {"command": spec.command, "args": list(spec.args)}
+ if spec.env:
+ entry["env"] = dict(spec.env)
+ (tmp_path / ".claude.json").write_text(
+ json.dumps({"mcpServers": {"serena": entry}}), encoding="utf-8"
+ )
+
+
+def test_wrap_registers_serena_for_this_project_only(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ registrar = _registrar(tmp_path)
+
+ wrap_cli._setup_serena_mcp(registrar, context="claude-code", verbose=True)
+
+ assert "serena" in _project_servers(tmp_path)
+ # The machine-wide map is what broke unrelated sessions — stay out of it.
+ assert "mcpServers" not in _config(tmp_path)
+ assert "scoped to this project" in capsys.readouterr().out
+
+
+def test_rewrap_retires_the_global_entry_headroom_installed(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """An upgrading user gets the machine-wide entry cleaned up automatically."""
+ old_spec = build_serena_spec("claude-code")
+ _seed_global_serena(tmp_path, old_spec)
+ record_install("claude", old_spec) # ledger proves Headroom installed it
+
+ wrap_cli._setup_serena_mcp(_registrar(tmp_path), context="claude-code", verbose=True)
+
+ config = _config(tmp_path)
+ assert config["mcpServers"] == {}
+ assert "serena" in _project_servers(tmp_path)
+ assert "removed the machine-wide entry" in capsys.readouterr().out
+
+
+def test_rewrap_retires_a_stale_global_entry(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """The global entry can predate the current spec and still be ours.
+
+ Its fingerprint is the one recorded when it was installed, so the ledger
+ check has to run before the new registration overwrites that record.
+ """
+ stale = ServerSpec(
+ name="serena",
+ command="uvx",
+ args=("--from", "git+https://github.com/oraios/serena", "serena", "start-mcp-server"),
+ )
+ _seed_global_serena(tmp_path, stale)
+ record_install("claude", stale)
+
+ wrap_cli._setup_serena_mcp(_registrar(tmp_path), context="claude-code", verbose=True)
+
+ assert _config(tmp_path)["mcpServers"] == {}
+ assert "serena" in _project_servers(tmp_path)
+ assert "removed the machine-wide entry" in capsys.readouterr().out
+
+
+def test_rewrap_migration_clears_the_ledger_so_a_reinstall_is_never_deleted(
+ tmp_path: Path,
+) -> None:
+ """The migration must retire its own ownership claim, not just the entry.
+
+ If the ledger record survived, a user who later installs the *same*
+ Serena command globally themselves would collide with the old
+ fingerprint, and a subsequent wrap would mistake their entry for one
+ Headroom still owns and delete it out from under them.
+ """
+ from headroom.mcp_registry.ledger import headroom_installed_matching
+
+ old_spec = build_serena_spec("claude-code")
+ _seed_global_serena(tmp_path, old_spec)
+ record_install("claude", old_spec)
+
+ (tmp_path / ".claude").mkdir(exist_ok=True)
+ project_a = tmp_path / "project-a"
+ project_a.mkdir()
+ registrar_a = ClaudeRegistrar(
+ claude_cli=None, home_dir=tmp_path, scope=SCOPE_LOCAL, project_dir=project_a
+ )
+ wrap_cli._setup_serena_mcp(registrar_a, context="claude-code")
+
+ # The migration removed the config entry - the ownership record backing
+ # it must be gone too, not just the entry it pointed at.
+ assert not headroom_installed_matching("claude", old_spec)
+
+ # The user reinstalls the identical command globally themselves.
+ _seed_global_serena(tmp_path, old_spec)
+
+ project_b = tmp_path / "project-b"
+ project_b.mkdir()
+ registrar_b = ClaudeRegistrar(
+ claude_cli=None, home_dir=tmp_path, scope=SCOPE_LOCAL, project_dir=project_b
+ )
+ wrap_cli._setup_serena_mcp(registrar_b, context="claude-code")
+
+ assert _config(tmp_path)["mcpServers"]["serena"]["command"] == old_spec.command
+
+
+def test_remove_serena_clears_a_stale_ownership_record_with_no_live_entry(
+ tmp_path: Path,
+) -> None:
+ """An ownership record must not outlive the config entry it authorized."""
+ from headroom.mcp_registry.ledger import headroom_installed_matching
+
+ registrar = _registrar(tmp_path)
+ ownership_key = registrar.ownership_key("serena", scope=SCOPE_LOCAL)
+ stale_spec = ServerSpec(name="serena", command="uvx", args=("start-mcp-server",))
+ record_install("claude", stale_spec, ownership_key=ownership_key)
+ # Deliberately no live entry: simulates one removed by another path
+ # (e.g. the user's own agent config edit) without going through us.
+
+ status = wrap_cli._remove_headroom_installed_serena_mcp(registrar)
+
+ assert status == "not_headroom_owned"
+ assert not headroom_installed_matching("claude", stale_spec, ownership_key=ownership_key)
+
+
+def test_rewrap_leaves_a_user_managed_global_entry_alone(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """A Serena the user registered globally is theirs, not ours to remove."""
+ user_spec = ServerSpec(name="serena", command="/usr/local/bin/custom-serena")
+ _seed_global_serena(tmp_path, user_spec)
+ # Deliberately no record_install: the ledger has never seen this entry.
+
+ wrap_cli._setup_serena_mcp(_registrar(tmp_path), context="claude-code", verbose=True)
+
+ config = _config(tmp_path)
+ assert config["mcpServers"]["serena"]["command"] == "/usr/local/bin/custom-serena"
+ # The project entry is still written: local scope wins for this directory,
+ # so the user's global Serena keeps working everywhere else.
+ assert "serena" in _project_servers(tmp_path)
+ assert "removed the machine-wide entry" not in capsys.readouterr().out
+
+
+def test_user_scope_reproduces_the_previous_behaviour(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ registrar = _registrar(tmp_path, scope=SCOPE_USER)
+
+ wrap_cli._setup_serena_mcp(registrar, context="claude-code", verbose=True)
+
+ config = _config(tmp_path)
+ assert "serena" in config["mcpServers"]
+ assert "projects" not in config
+ out = capsys.readouterr().out
+ assert "every Claude Code session on this machine" in out
+ assert "removed the machine-wide entry" not in out
+
+
+def test_project_ownership_records_do_not_clobber_each_other(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Wrapping and unwrapping one project must not orphan another project."""
+ project_a = tmp_path / "project-a"
+ project_b = tmp_path / "project-b"
+ project_a.mkdir()
+ project_b.mkdir()
+ (tmp_path / ".claude").mkdir()
+ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / ".headroom"))
+ registrar_a = ClaudeRegistrar(
+ claude_cli=None, home_dir=tmp_path, scope=SCOPE_LOCAL, project_dir=project_a
+ )
+ registrar_b = ClaudeRegistrar(
+ claude_cli=None, home_dir=tmp_path, scope=SCOPE_LOCAL, project_dir=project_b
+ )
+
+ wrap_cli._setup_serena_mcp(registrar_a, context="claude-code")
+ wrap_cli._setup_serena_mcp(registrar_b, context="claude-code")
+
+ from headroom.mcp_registry.ledger import headroom_installed_matching
+
+ assert set(_config(tmp_path)["projects"]) == {project_a.as_posix(), project_b.as_posix()}
+ assert headroom_installed_matching(
+ "claude",
+ registrar_a.get_server("serena", scope=SCOPE_LOCAL),
+ ownership_key=registrar_a.ownership_key("serena", scope=SCOPE_LOCAL),
+ )
+ assert wrap_cli._remove_headroom_installed_serena_mcp(registrar_a) == "removed"
+ assert registrar_a.get_server("serena", scope=SCOPE_LOCAL) is None
+ assert registrar_b.get_server("serena", scope=SCOPE_LOCAL) is not None
+ assert wrap_cli._remove_headroom_installed_serena_mcp(registrar_b) == "removed"
+
+
+def test_project_unwrap_does_not_remove_unowned_global_serena(tmp_path: Path) -> None:
+ """Scope-specific cleanup must not turn project ownership into global authority."""
+ user_spec = ServerSpec(name="serena", command="custom-serena")
+ _seed_global_serena(tmp_path, user_spec)
+ registrar = _registrar(tmp_path)
+ wrap_cli._setup_serena_mcp(registrar, context="claude-code")
+
+ assert wrap_cli._remove_headroom_installed_serena_mcp(registrar) == "removed"
+ assert registrar.get_server("serena", scope=SCOPE_LOCAL) is None
+ assert registrar.get_server("serena", scope=SCOPE_USER) == user_spec
+
+
+def test_scope_migration_is_skipped_for_registrars_without_scopes(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """Codex/Grok/OpenCode registrars have no scope and no scoped reads."""
+
+ class _FakeRegistrar:
+ name = "codex"
+ display_name = "Codex"
+
+ def __init__(self) -> None:
+ self.server: ServerSpec | None = None
+
+ def detect(self) -> bool:
+ return True
+
+ def get_server(self, server_name: str) -> ServerSpec | None:
+ return self.server if server_name == "serena" else None
+
+ def register_server(self, spec: ServerSpec, *, force: bool = False) -> Any:
+ from headroom.mcp_registry.base import RegisterResult, RegisterStatus
+
+ self.server = spec
+ return RegisterResult(RegisterStatus.REGISTERED, "registered")
+
+ registrar = _FakeRegistrar()
+ wrap_cli._setup_serena_mcp(registrar, context="claude-code", verbose=True)
+
+ assert registrar.server is not None
+ out = capsys.readouterr().out
+ assert "removed the machine-wide entry" not in out
+ assert "scoped to this project" not in out
+
+
+# ----------------------------------------------------------------------
+# Flag / environment resolution
+# ----------------------------------------------------------------------
+
+
+def test_default_scope_is_project(monkeypatch: pytest.MonkeyPatch) -> None:
+ assert wrap_cli._resolve_code_memory_scope() == "project"
+ assert wrap_cli._claude_code_memory_scope() == SCOPE_LOCAL
+
+
+def test_env_var_selects_user_scope(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("HEADROOM_CODE_MEMORY_SCOPE", "user")
+ assert wrap_cli._resolve_code_memory_scope() == "user"
+ assert wrap_cli._claude_code_memory_scope() == SCOPE_USER
+
+
+def test_invalid_env_var_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("HEADROOM_CODE_MEMORY_SCOPE", "global")
+ with pytest.raises(Exception) as excinfo:
+ wrap_cli._resolve_code_memory_scope()
+ assert "HEADROOM_CODE_MEMORY_SCOPE" in str(excinfo.value)
diff --git a/tests/test_cli/test_tokensave_scope.py b/tests/test_cli/test_tokensave_scope.py
new file mode 100644
index 000000000..5728d6b69
--- /dev/null
+++ b/tests/test_cli/test_tokensave_scope.py
@@ -0,0 +1,148 @@
+"""Retiring the legacy tokensave entry stays at user scope (#2992 review).
+
+tokensave was replaced by Serena and is only ever cleaned up now: ``wrap``
+retires the entry a prior release installed so the agent stops launching it,
+and ``unwrap`` does the same. Headroom only ever installed tokensave
+machine-wide — it was retired before #2787 gave Claude registrations a project
+scope — so the ledger record authorizing the removal is the pre-scope,
+user-scope one.
+
+``ClaudeRegistrar.unregister_server()`` with no scope now deletes from the
+project *and* the user scope, so an unscoped retirement would take a
+project-local tokensave the user registered themselves, which no ledger record
+authorizes. An unscoped read has the mirror problem: a project entry is found
+first and shadows the machine-wide one Headroom owns, leaving ours behind
+forever.
+
+These tests drive the real helpers with a real ``ClaudeRegistrar`` whose home
+directory is a tmp_path, so the assertions are about the JSON Claude Code
+actually reads.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from headroom.cli import wrap as wrap_cli
+from headroom.mcp_registry.base import ServerSpec
+from headroom.mcp_registry.claude import SCOPE_LOCAL, SCOPE_USER, ClaudeRegistrar
+from headroom.mcp_registry.ledger import record_install
+
+HEADROOM_SPEC = ServerSpec(name="tokensave", command="tokensave", args=("mcp",))
+USER_SPEC = ServerSpec(name="tokensave", command="/usr/local/bin/my-own-tokensave")
+
+
[email protected](autouse=True)
+def _isolate_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / ".headroom"))
+
+
+def _registrar(tmp_path: Path, *, scope: str = SCOPE_LOCAL) -> ClaudeRegistrar:
+ """A real registrar pointed at ``tmp_path`` instead of the user's home."""
+ (tmp_path / ".claude").mkdir(exist_ok=True)
+ return ClaudeRegistrar(
+ claude_cli=None, # no CLI path; never touch the real one
+ home_dir=tmp_path,
+ scope=scope,
+ project_dir=tmp_path / "proj",
+ )
+
+
+def _entry(spec: ServerSpec) -> dict[str, Any]:
+ entry: dict[str, Any] = {"command": spec.command, "args": list(spec.args)}
+ if spec.env:
+ entry["env"] = dict(spec.env)
+ return entry
+
+
+def _seed(tmp_path: Path, *, global_spec: ServerSpec, project_spec: ServerSpec) -> None:
+ """A machine-wide tokensave plus a project-scoped one, as Claude Code stores them."""
+ config = {
+ "mcpServers": {"tokensave": _entry(global_spec)},
+ "projects": {
+ (tmp_path / "proj").as_posix(): {"mcpServers": {"tokensave": _entry(project_spec)}}
+ },
+ }
+ (tmp_path / ".claude.json").write_text(json.dumps(config), encoding="utf-8")
+
+
+def test_retirement_spares_an_identical_user_managed_project_entry(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """Same command in both scopes: only the one the ledger authorized goes."""
+ _seed(tmp_path, global_spec=HEADROOM_SPEC, project_spec=HEADROOM_SPEC)
+ record_install("claude", HEADROOM_SPEC) # pre-scope ledger key: "tokensave"
+ registrar = _registrar(tmp_path)
+
+ wrap_cli._disable_tokensave_mcp(registrar)
+
+ assert registrar.get_server("tokensave", scope=SCOPE_USER) is None
+ assert registrar.get_server("tokensave", scope=SCOPE_LOCAL) == HEADROOM_SPEC
+ assert "Removed retired tokensave MCP" in capsys.readouterr().out
+
+
+def test_a_user_managed_project_entry_does_not_shadow_the_global_one(
+ tmp_path: Path,
+) -> None:
+ """A project entry we do not own must not block retiring the one we do."""
+ _seed(tmp_path, global_spec=HEADROOM_SPEC, project_spec=USER_SPEC)
+ record_install("claude", HEADROOM_SPEC)
+ registrar = _registrar(tmp_path)
+
+ assert wrap_cli._remove_headroom_installed_tokensave_mcp(registrar) == "removed"
+ assert registrar.get_server("tokensave", scope=SCOPE_USER) is None
+ assert registrar.get_server("tokensave", scope=SCOPE_LOCAL) == USER_SPEC
+
+
+def test_unwrap_leaves_a_user_managed_project_entry_alone(tmp_path: Path) -> None:
+ """unwrap builds a user-scope registrar; it still must not reach into the project."""
+ _seed(tmp_path, global_spec=HEADROOM_SPEC, project_spec=HEADROOM_SPEC)
+ record_install("claude", HEADROOM_SPEC)
+ registrar = _registrar(tmp_path, scope=SCOPE_USER)
+
+ assert wrap_cli._remove_headroom_installed_tokensave_mcp(registrar) == "removed"
+ assert registrar.get_server("tokensave", scope=SCOPE_USER) is None
+ assert registrar.get_server("tokensave", scope=SCOPE_LOCAL) == HEADROOM_SPEC
+
+
+def test_a_user_managed_global_entry_is_left_in_place(tmp_path: Path) -> None:
+ """Unchanged behaviour: no ledger record, no removal."""
+ _seed(tmp_path, global_spec=USER_SPEC, project_spec=USER_SPEC)
+ registrar = _registrar(tmp_path)
+
+ assert wrap_cli._remove_headroom_installed_tokensave_mcp(registrar) == "not_headroom_owned"
+ assert registrar.get_server("tokensave", scope=SCOPE_USER) == USER_SPEC
+ assert registrar.get_server("tokensave", scope=SCOPE_LOCAL) == USER_SPEC
+
+
+def test_registrars_without_scopes_still_retire_tokensave(tmp_path: Path) -> None:
+ """Codex/Grok/OpenCode registrars have no scope and reject a scoped read."""
+
+ class _FakeRegistrar:
+ name = "codex"
+ display_name = "Codex"
+
+ def __init__(self) -> None:
+ self.server: ServerSpec | None = HEADROOM_SPEC
+
+ def detect(self) -> bool:
+ return True
+
+ def get_server(self, server_name: str) -> ServerSpec | None:
+ return self.server if server_name == "tokensave" else None
+
+ def unregister_server(self, server_name: str) -> bool:
+ if server_name != "tokensave" or self.server is None:
+ return False
+ self.server = None
+ return True
+
+ record_install("codex", HEADROOM_SPEC)
+ registrar = _FakeRegistrar()
+
+ assert wrap_cli._remove_headroom_installed_tokensave_mcp(registrar) == "removed"
+ assert registrar.server is None
diff --git a/tests/test_cli/test_unwrap_claude.py b/tests/test_cli/test_unwrap_claude.py
index e3b688196..6d5811eb4 100644
--- a/tests/test_cli/test_unwrap_claude.py
+++ b/tests/test_cli/test_unwrap_claude.py
@@ -205,6 +205,66 @@ def test_unwrap_claude_removes_headroom_installed_serena(
assert "Removed Headroom-installed Serena MCP server" in result.output
+def test_unwrap_claude_removes_project_scoped_serena(
+ runner: CliRunner,
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """Unwrap must find the Serena entry wherever wrap put it (#2787).
+
+ Wrap now registers Serena under ``projects[<cwd>].mcpServers`` rather than
+ the machine-wide map, so this runs against a real registrar and real config
+ JSON — a fake registrar would not catch a scope mismatch between the two.
+ """
+ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / ".headroom"))
+
+ from headroom.mcp_registry import build_serena_spec
+ from headroom.mcp_registry.claude import ClaudeRegistrar
+ from headroom.mcp_registry.ledger import record_install
+
+ project = tmp_path / "proj"
+ project.mkdir()
+ monkeypatch.chdir(project)
+
+ serena_spec = build_serena_spec("claude-code")
+ registrar = ClaudeRegistrar(
+ claude_cli=None, home_dir=tmp_path, scope="local", project_dir=project
+ )
+ record_install(
+ "claude",
+ serena_spec,
+ ownership_key=registrar.ownership_key("serena", scope="local"),
+ )
+ (tmp_path / ".claude.json").write_text(
+ json.dumps(
+ {
+ "projects": {
+ project.as_posix(): {
+ "mcpServers": {
+ "serena": {
+ "command": serena_spec.command,
+ "args": list(serena_spec.args),
+ }
+ }
+ }
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ with (
+ patch("headroom.mcp_registry.ClaudeRegistrar", return_value=registrar),
+ patch("headroom.cli.wrap._remove_claude_managed_hooks", return_value=False),
+ patch("headroom.cli.wrap._stop_local_proxy_for_unwrap"),
+ ):
+ result = runner.invoke(main, ["unwrap", "claude"])
+
+ assert result.exit_code == 0, result.output
+ assert "Removed Headroom-installed Serena MCP server" in result.output
+ config = json.loads((tmp_path / ".claude.json").read_text(encoding="utf-8"))
+ assert config["projects"][project.as_posix()]["mcpServers"] == {}
+
+
def test_unwrap_claude_keep_flags_skip_cleanup(
runner: CliRunner,
) -> None:
diff --git a/tests/test_mcp_registry/test_claude_registrar.py b/tests/test_mcp_registry/test_claude_registrar.py
index 5f79c43d4..5caa1e28c 100644
--- a/tests/test_mcp_registry/test_claude_registrar.py
+++ b/tests/test_mcp_registry/test_claude_registrar.py
@@ -10,7 +10,7 @@ from unittest.mock import patch
import pytest
from headroom.mcp_registry.base import RegisterStatus, ServerSpec
-from headroom.mcp_registry.claude import ClaudeRegistrar
+from headroom.mcp_registry.claude import SCOPE_LOCAL, SCOPE_USER, ClaudeRegistrar
from headroom.mcp_registry.install import build_headroom_spec
_RESOLVED_COMMAND = ("/usr/bin/python", "-m", "headroom.cli")
@@ -512,6 +512,258 @@ def test_register_via_file_merges_into_existing_valid_config(tmp_path: Path) ->
# ----------------------------------------------------------------------
+# Project ("local") scope — issue #2787
+#
+# A server registered at user scope loads in every Claude Code session on the
+# machine, so one that fails to start breaks unrelated projects. Project scope
+# confines it to the directory that was wrapped.
+# ----------------------------------------------------------------------
+
+_SERENA_ARGS = ["serena", "start-mcp-server"]
+
+
+def _local_registrar(
+ tmp_path: Path,
+ *,
+ cli: str | None = None,
+ project_dir: Path | None = None,
+) -> ClaudeRegistrar:
+ """Registrar writing project scope, pointed at ``tmp_path`` as $HOME."""
+ return ClaudeRegistrar(
+ claude_cli=cli,
+ home_dir=tmp_path,
+ scope=SCOPE_LOCAL,
+ project_dir=project_dir if project_dir is not None else tmp_path / "proj",
+ )
+
+
+def _serena_spec(command: str = "uvx") -> ServerSpec:
+ return ServerSpec(name="serena", command=command, args=tuple(_SERENA_ARGS))
+
+
+def test_rejects_unknown_scope(tmp_path: Path) -> None:
+ with pytest.raises(ValueError):
+ ClaudeRegistrar(claude_cli=None, home_dir=tmp_path, scope="global")
+
+
+def test_register_local_scope_writes_project_map_not_user_map(tmp_path: Path) -> None:
+ project = tmp_path / "proj"
+ reg = _local_registrar(tmp_path, project_dir=project)
+
+ result = reg.register_server(_serena_spec())
+
+ assert result.status == RegisterStatus.REGISTERED
+ data = json.loads((tmp_path / ".claude.json").read_text(encoding="utf-8"))
+ assert "serena" in data["projects"][project.as_posix()]["mcpServers"]
+ # The machine-wide map is what breaks unrelated sessions — stay out of it.
+ assert "mcpServers" not in data
+
+
+def test_register_local_scope_reuses_existing_project_key(tmp_path: Path) -> None:
+ """Claude Code keys ``projects`` by the session's cwd string (forward slashes
+ even on Windows). A second key naming the same directory would leave an entry
+ Claude Code never reads."""
+ project = tmp_path / "proj"
+ cfg = tmp_path / ".claude.json"
+ existing_key = project.as_posix() + "/" # same directory, different spelling
+ cfg.write_text(
+ json.dumps({"projects": {existing_key: {"hasTrustDialogAccepted": True}}}),
+ encoding="utf-8",
+ )
+ reg = _local_registrar(tmp_path, project_dir=project)
+
+ assert reg.register_server(_serena_spec()).status == RegisterStatus.REGISTERED
+
+ data = json.loads(cfg.read_text(encoding="utf-8"))
+ assert list(data["projects"]) == [existing_key]
+ assert "serena" in data["projects"][existing_key]["mcpServers"]
+ assert data["projects"][existing_key]["hasTrustDialogAccepted"] is True
+
+
+def test_register_local_scope_writes_even_when_user_entry_matches(tmp_path: Path) -> None:
+ """A leftover user-scope copy must not make the project-scope registration
+ look like a no-op — that would leave the machine-wide entry as the only one."""
+ project = tmp_path / "proj"
+ cfg = tmp_path / ".claude.json"
+ cfg.write_text(
+ json.dumps({"mcpServers": {"serena": {"command": "uvx", "args": _SERENA_ARGS}}}),
+ encoding="utf-8",
+ )
+ reg = _local_registrar(tmp_path, project_dir=project)
+
+ result = reg.register_server(_serena_spec())
+
+ assert result.status == RegisterStatus.REGISTERED
+ data = json.loads(cfg.read_text(encoding="utf-8"))
+ assert "serena" in data["projects"][project.as_posix()]["mcpServers"]
+ # Retiring the global copy is wrap's job (ledger-gated), not the registrar's.
+ assert "serena" in data["mcpServers"]
+
+
+def test_register_local_scope_never_writes_legacy_config(tmp_path: Path) -> None:
+ """``~/.claude/mcp.json`` has no projects map, so project scope always goes to
+ the modern config even when only the legacy file exists."""
+ legacy = tmp_path / ".claude" / "mcp.json"
+ legacy.parent.mkdir()
+ legacy.write_text(json.dumps({"mcpServers": {}}), encoding="utf-8")
+ project = tmp_path / "proj"
+ reg = _local_registrar(tmp_path, project_dir=project)
+
+ assert reg.register_server(_serena_spec()).status == RegisterStatus.REGISTERED
+
+ assert json.loads(legacy.read_text(encoding="utf-8"))["mcpServers"] == {}
+ data = json.loads((tmp_path / ".claude.json").read_text(encoding="utf-8"))
+ assert "serena" in data["projects"][project.as_posix()]["mcpServers"]
+
+
+def test_register_via_cli_passes_local_scope_and_project_cwd(tmp_path: Path) -> None:
+ project = tmp_path / "proj"
+ reg = _local_registrar(tmp_path, cli="/usr/local/bin/claude", project_dir=project)
+ ok = subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr="")
+
+ with patch("subprocess.run", return_value=ok) as run_mock:
+ result = reg.register_server(_serena_spec())
+
+ assert result.status == RegisterStatus.REGISTERED
+ add_call = run_mock.call_args
+ assert add_call is not None
+ assert add_call.args[0][:6] == [
+ "/usr/local/bin/claude",
+ "mcp",
+ "add",
+ "serena",
+ "-s",
+ "local",
+ ]
+ # `claude mcp add -s local` keys the entry by the CLI process's own cwd.
+ assert add_call.kwargs["cwd"] == str(project)
+
+
+def test_get_server_prefers_project_entry_over_user_entry(tmp_path: Path) -> None:
+ """Claude Code resolves project scope first, so our reads must too."""
+ project = tmp_path / "proj"
+ cfg = tmp_path / ".claude.json"
+ cfg.write_text(
+ json.dumps(
+ {
+ "mcpServers": {"serena": {"command": "global-uvx"}},
+ "projects": {project.as_posix(): {"mcpServers": {"serena": {"command": "uvx"}}}},
+ }
+ ),
+ encoding="utf-8",
+ )
+ reg = _local_registrar(tmp_path, project_dir=project)
+
+ unscoped = reg.get_server("serena")
+ assert unscoped is not None and unscoped.command == "uvx"
+
+ scoped_user = reg.get_server("serena", scope=SCOPE_USER)
+ assert scoped_user is not None and scoped_user.command == "global-uvx"
+
+ scoped_local = reg.get_server("serena", scope=SCOPE_LOCAL)
+ assert scoped_local is not None and scoped_local.command == "uvx"
+
+
+def test_get_server_scoped_read_ignores_other_projects(tmp_path: Path) -> None:
+ cfg = tmp_path / ".claude.json"
+ cfg.write_text(
+ json.dumps(
+ {"projects": {(tmp_path / "elsewhere").as_posix(): {"mcpServers": {"serena": {}}}}}
+ ),
+ encoding="utf-8",
+ )
+ reg = _local_registrar(tmp_path, project_dir=tmp_path / "proj")
+
+ assert reg.get_server("serena", scope=SCOPE_LOCAL) is None
+
+
+def test_force_register_local_scope_leaves_user_entry(tmp_path: Path) -> None:
+ """force=True replaces the entry in the target scope only.
+
+ Overwriting this project's Serena must not delete a machine-wide one the
+ user registered themselves.
+ """
+ project = tmp_path / "proj"
+ cfg = tmp_path / ".claude.json"
+ cfg.write_text(
+ json.dumps(
+ {
+ "mcpServers": {"serena": {"command": "user-managed-serena"}},
+ "projects": {project.as_posix(): {"mcpServers": {"serena": {"command": "old"}}}},
+ }
+ ),
+ encoding="utf-8",
+ )
+ reg = _local_registrar(tmp_path, project_dir=project)
+
+ result = reg.register_server(_serena_spec(), force=True)
+
+ assert result.status == RegisterStatus.REGISTERED
+ data = json.loads(cfg.read_text(encoding="utf-8"))
+ assert data["projects"][project.as_posix()]["mcpServers"]["serena"]["command"] == "uvx"
+ assert data["mcpServers"]["serena"]["command"] == "user-managed-serena"
+
+
+def test_unregister_removes_both_scopes_by_default(tmp_path: Path) -> None:
+ """unwrap must clean up regardless of which scope installed the entry."""
+ project = tmp_path / "proj"
+ other = tmp_path / "other"
+ cfg = tmp_path / ".claude.json"
+ cfg.write_text(
+ json.dumps(
+ {
+ "mcpServers": {"serena": {"command": "uvx"}},
+ "projects": {
+ project.as_posix(): {"mcpServers": {"serena": {"command": "uvx"}}},
+ other.as_posix(): {"mcpServers": {"serena": {"command": "uvx"}}},
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ reg = _local_registrar(tmp_path, project_dir=project)
+
+ assert reg.unregister_server("serena") is True
+
+ data = json.loads(cfg.read_text(encoding="utf-8"))
+ assert data["mcpServers"] == {}
+ assert data["projects"][project.as_posix()]["mcpServers"] == {}
+ # Other projects were wrapped separately; unwrapping here must not touch them.
+ assert "serena" in data["projects"][other.as_posix()]["mcpServers"]
+
+
+def test_unregister_user_scope_leaves_project_entry(tmp_path: Path) -> None:
+ project = tmp_path / "proj"
+ cfg = tmp_path / ".claude.json"
+ cfg.write_text(
+ json.dumps(
+ {
+ "mcpServers": {"serena": {"command": "uvx"}},
+ "projects": {project.as_posix(): {"mcpServers": {"serena": {"command": "uvx"}}}},
+ }
+ ),
+ encoding="utf-8",
+ )
+ reg = _local_registrar(tmp_path, project_dir=project)
+
+ assert reg.unregister_server("serena", scope=SCOPE_USER) is True
+
+ data = json.loads(cfg.read_text(encoding="utf-8"))
+ assert data["mcpServers"] == {}
+ assert "serena" in data["projects"][project.as_posix()]["mcpServers"]
+
+
+def test_default_scope_is_user_so_existing_callers_are_unchanged(tmp_path: Path) -> None:
+ reg = _make_registrar(tmp_path, cli=None)
+ assert reg.scope == SCOPE_USER
+
+ assert reg.register_server(_spec()).status == RegisterStatus.REGISTERED
+
+ data = json.loads((tmp_path / ".claude.json").read_text(encoding="utf-8"))
+ assert "headroom" in data["mcpServers"]
+ assert "projects" not in data
+
+
# get_plugin_servers() — servers bundled by Claude Code plugins (#3570)
# ----------------------------------------------------------------------