From 9c350949eba3bed66028759c0a947c7ce5189e0a Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 19 Nov 2026 17:39:10 +0100 Subject: [PATCH 1/6] fix(mcp): honor per-dependency targets for dependencies.mcp entries `targets:` on a dependencies.mcp entry was unknown to MCPDependency, so it was preserved in `extra`, rendered into every native MCP config, and every server reached every target. Stale pruning was also not per target, so `install -g --only mcp --target codex` retired servers still declared for claude. - `targets` is a modeled MCPDependency field parsed by parse_target_subset; it is never written into native config. - mcp_dependency_runtimes (the MCP target-selection owner) narrows the run's runtimes per dependency for writes, claim bookkeeping, pruning and --frozen claims. - Pruning removes a server only from targets it no longer selects; an unselected target keeps servers whose targets: still name it. - Extend the mutation_writes.mcp_target_selection guard and add mutation cases plus an installed-CLI regression for project and global scopes. Fixes #2606 apm-spec-waiver: implements accepted issue #2606 scope; OpenAPM manifest schema already admits additional MCP keys, no normative requirement changes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../owners/hooks-integrations.json | 2 +- CHANGELOG.md | 1 + .../content/docs/reference/manifest-schema.md | 3 +- .../.apm/skills/apm-usage/dependencies.md | 8 ++ .../checks/mutation_mcp_target_and_scope.py | 68 +++++++++++++ src/apm_cli/install/mcp/integration.py | 28 +++++- src/apm_cli/install/service.py | 10 +- src/apm_cli/install/service_integration.py | 9 +- .../integration/mcp_integrator_install.py | 66 ++++++++++--- src/apm_cli/models/dependency/mcp.py | 11 +++ .../test_architecture_owner_rule_mutations.py | 51 ++++++++++ .../test_mcp_dependency_targets_lifecycle.py | 98 +++++++++++++++++++ tests/unit/test_mcp_overlays.py | 16 +++ 13 files changed, 345 insertions(+), 26 deletions(-) create mode 100644 tests/integration/test_mcp_dependency_targets_lifecycle.py diff --git a/.apm/architecture/owners/hooks-integrations.json b/.apm/architecture/owners/hooks-integrations.json index 02c7978bcc..3e4bcfdfa7 100644 --- a/.apm/architecture/owners/hooks-integrations.json +++ b/.apm/architecture/owners/hooks-integrations.json @@ -33,7 +33,7 @@ { "id": "mcp-target-selection-precedence", "decision": "MCP target-selection precedence", - "owner": "integration/mcp_integrator_install.py (_resolve_target_runtimes)", + "owner": "integration/mcp_integrator_install.py (_resolve_target_runtimes; mcp_dependency_runtimes narrows each dependency by its targets: for writes, claim pruning and --frozen claims)", "selectors": ["src/apm_cli/integration/mcp_integrator_install.py"], "guards": ["hooks-integrations-mcp-target-selection"] }, diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a04a6b184..5d32659cde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- `targets:` on a `dependencies.mcp` entry now limits which targets get the server and is no longer written into native MCP config; `apm install -g --target codex` keeps servers declared for other targets. (closes #2606, #PR_NUMBER) - `apm uninstall plugin@marketplace` removes object-form `{name, marketplace}` entries from `apm.yml`, offline, with their lock row and files. (closes #3928, #3933) - Marketplace entries in `apm.yml`, transitive marketplace dependencies and `apm update` now refuse bare cross-repo `repo:` on `*.ghe.com` marketplaces, as CLI installs already did. (closes #3913, #3923) - `*.ghe.com` marketplaces now refuse bare cross-repo `git-subdir`, `gitlab` and `url` sources too, not only `type: github`. (closes #3937, #3942) diff --git a/docs/src/content/docs/reference/manifest-schema.md b/docs/src/content/docs/reference/manifest-schema.md index 30dc68ac75..b69304f0a9 100644 --- a/docs/src/content/docs/reference/manifest-schema.md +++ b/docs/src/content/docs/reference/manifest-schema.md @@ -776,12 +776,13 @@ A plain registry reference: `io.github.github/github-mcp-server`. | `url` | `string` | Conditional | | Endpoint URL. REQUIRED when `registry: false` and `transport` is `http`, `sse`, or `streamable-http`. | | `command` | `string` | Conditional | Single binary path; no embedded whitespace unless `args` is also present | Binary path. REQUIRED when `registry: false` and `transport` is `stdio`. | | `enabled` | any JSON value | OPTIONAL | OpenCode only | Passed unchanged to OpenCode's `opencode.json` entry. When omitted, APM keeps its existing `true` default. APM does not validate the value; OpenCode interprets it. In the OpenCode 2 `mcp.servers` layout, `false` becomes `disabled: true`, `true` writes no field, and other values warn and leave the file unchanged; see [OpenCode 2 configuration](../../consumer/install-mcp-servers/#opencode-2-configuration). Other targets ignore this field. | +| `targets` | `list` | OPTIONAL | Non-empty; known target names | Targets that receive this server: effective reach is the install targets intersected with this list. Omitted = every install target. Never written into a native MCP config. A target-scoped install (`--target`) keeps the server in the other targets it lists; reinstall prunes it only from targets it no longer lists. | Any additional keys not listed above are preserved as **extra passthrough fields** and round-tripped verbatim into the generated target manifests. This allows harness-specific configuration (e.g. Claude Code's `oauth` block for remote-MCP OAuth client config) to be declared in `apm.yml` and appear in the generated config without modification. A warning is emitted at parse time naming each non-standard key. Two guardrails apply: -- **Reserved keys are rejected.** A passthrough key whose name collides with a modeled field above -- `name`, `transport`/`type`, `command`, `url`, `headers`, `env`, `args`, `tools`, `version`, `registry`, `package`, `enabled` -- or with an adapter-owned field (`http_headers`, `env_http_headers`, `bearer_token_env_var`, `environment`, `id`, `httpUrl`, `serverUrl`) is dropped with a warning. This prevents a passthrough value from shadowing or redirecting a modeled field. Extra keys also never overwrite a value the target adapter set itself. The top-level `enabled` field is the OpenCode-only exception: it is forwarded only to OpenCode, and an `extra.enabled` value remains reserved. +- **Reserved keys are rejected.** A passthrough key whose name collides with a modeled field above -- `name`, `transport`/`type`, `command`, `url`, `headers`, `env`, `args`, `tools`, `version`, `registry`, `package`, `enabled`, `targets` -- or with an adapter-owned field (`http_headers`, `env_http_headers`, `bearer_token_env_var`, `environment`, `id`, `httpUrl`, `serverUrl`) is dropped with a warning. This prevents a passthrough value from shadowing or redirecting a modeled field. Extra keys also never overwrite a value the target adapter set itself. The top-level `enabled` field is the OpenCode-only exception: it is forwarded only to OpenCode, and an `extra.enabled` value remains reserved. - **Extra keys broadcast to every target.** Passthrough keys are written uniformly into the generated config for **all** installed harnesses, not just the one that understands them. A Claude Code `oauth` block (`clientId`/`callbackPort`), for example, is emitted into every target's server entry; harnesses that do not recognise the key ignore it. Per-harness scoping is tracked as a future enhancement (see issue #1806). > A future release may require passthrough keys to be nested under an explicit `extra:` block and stop auto-capturing bare top-level keys (fail-closed), via a deprecation path. See issue #1806. diff --git a/packages/apm-guide/.apm/skills/apm-usage/dependencies.md b/packages/apm-guide/.apm/skills/apm-usage/dependencies.md index 5c6fc2d51e..eb89fff51a 100644 --- a/packages/apm-guide/.apm/skills/apm-usage/dependencies.md +++ b/packages/apm-guide/.apm/skills/apm-usage/dependencies.md @@ -715,6 +715,14 @@ dependencies: env: API_KEY: ${{ secrets.KEY }} + # Per-server targets: install targets INTERSECT this list (omitted = all). + # Never written into native config; reinstall prunes only dropped targets. + - name: claude-only-tools + registry: false + transport: stdio + command: ./bin/claude-tools + targets: [claude] + # Self-defined HTTP server - name: internal-kb registry: false diff --git a/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py b/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py index 28f2b6d291..b60faaab7f 100644 --- a/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py +++ b/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py @@ -264,6 +264,74 @@ def _check_mcp_target_selection(provider: FactsProvider) -> Iterable[Violation]: "Selected MCP targets must delegate safe-config preflight before no-op detection", ) ) + findings.extend(_dependency_target_selection_findings(provider, rule_id, install_facts)) + return findings + + +# Per-dependency ``targets:`` narrowing (#2606): one owner decides which runtimes +# receive a server; install writes, claim pruning and --frozen claims route +# through it instead of re-reading ``dep.targets``. +_MCP_DEPENDENCY_TARGET_CONSUMERS: tuple[tuple[str, str, tuple[str, ...]], ...] = ( + ( + _MCP_INSTALL, + "run_mcp_install", + ( + "mcp_dependency_runtimes(dep, target_runtimes)", + "managed_target_servers[target] &= mcp_servers_for_runtime(mcp_deps, target)", + ), + ), + ( + _MCP_INTEGRATION, + "run_mcp_integration", + ( + "admitted = mcp_servers_for_runtime(mcp_deps, owned_target)", + "mcp_deps, owned_target, named_only=True", + ), + ), + ( + _MCP_INTEGRATION, + "run_owned_mcp_integration", + ("mcp_servers_for_runtime(dependencies, target)",), + ), + ( + "src/apm_cli/install/service_integration.py", + "run_service_integrations", + ("mcp_servers_for_runtime(prepared_mcp.dependencies, target)",), + ), +) + + +def _dependency_target_selection_findings( + provider: FactsProvider, rule_id: str, install_facts: FileFacts +) -> list[Violation]: + findings: list[Violation] = [] + owner_spans = _function_spans(install_facts, "mcp_dependency_runtimes") + if len(owner_spans) != 1 or not _span_has_fixed( + install_facts, owner_spans[0], "declared = _declared_mcp_targets(dep)" + ): + findings.append( + violation( + rule_id, + _MCP_INSTALL, + "mcp_dependency_runtimes must be the one per-dependency MCP target owner", + ) + ) + for path, function, fragments in _MCP_DEPENDENCY_TARGET_CONSUMERS: + facts, failures = checked_facts(provider, path, rule_id, require_python=True) + findings.extend(failures) + if failures: + continue + span = _function_span(facts, function) + for fragment in fragments: + if span is None or not _span_has_fixed(facts, span, fragment): + findings.append( + violation( + rule_id, + path, + f"{function} must route MCP dependency targets through " + f"mcp_dependency_runtimes (missing {fragment!r})", + ) + ) return findings diff --git a/src/apm_cli/install/mcp/integration.py b/src/apm_cli/install/mcp/integration.py index 15068f8937..436c7ffa05 100644 --- a/src/apm_cli/install/mcp/integration.py +++ b/src/apm_cli/install/mcp/integration.py @@ -121,6 +121,7 @@ def run_owned_mcp_integration( split_mcp_claims, ) from apm_cli.integration.mcp_integrator import MCPIntegrator as _OwnedMCPIntegrator + from apm_cli.integration.mcp_integrator_install import mcp_servers_for_runtime lockfile = LockFile.read(lock_path) or LockFile() native_hashes = DeploymentLedgerCodec.mcp_native_hashes(lockfile) @@ -183,6 +184,11 @@ def run_owned_mcp_integration( } for target, names in list(managed_targets.items()): stale_for_target = (stale if target in selected_targets else old_owned) & names + if target in selected_targets: + # Declared servers whose `targets:` no longer select this runtime. + stale_for_target |= ( + previous_targets.get(target, set()) & old_owned & new_names + ) - mcp_servers_for_runtime(dependencies, target) if stale_for_target and conflict is None: # An entry in a shared file (.mcp.json) stays while an active peer # owns it; only this runtime's claim retires. @@ -564,11 +570,23 @@ def _keep_unhealed(healed: dict[str, builtins.set]) -> None: managed_target_servers.get("copilot") if "copilot" in managed_target_servers else None, ) from apm_cli.install.mcp.ownership import names_owned_by_active_peers - - for removed_target in sorted( - builtins.set(old_mcp_target_servers) - builtins.set(managed_target_servers) - ): - retired_names = builtins.set(old_mcp_target_servers[removed_target]) + from apm_cli.integration.mcp_integrator_install import mcp_servers_for_runtime + + retired_by_target: builtins.dict[str, builtins.set] = {} + for owned_target, owned in sorted(old_mcp_target_servers.items()): + if owned_target in managed_target_servers: + # Declared servers whose `targets:` no longer select this runtime. + admitted = mcp_servers_for_runtime(mcp_deps, owned_target) + retired_by_target[owned_target] = (builtins.set(owned) & new_mcp_servers) - admitted + continue + # A runtime this run does not select keeps the servers that name it. + kept = builtins.set(owned) & mcp_servers_for_runtime( + mcp_deps, owned_target, named_only=True + ) + if kept: + managed_target_servers[owned_target] = kept + retired_by_target[owned_target] = builtins.set(owned) - kept + for removed_target, retired_names in retired_by_target.items(): # An entry in a file the removed runtime shares (.mcp.json) stays # while an active runtime still owns it. retired_names -= names_owned_by_active_peers( diff --git a/src/apm_cli/install/service.py b/src/apm_cli/install/service.py index cd1655db6a..784e4b81fe 100644 --- a/src/apm_cli/install/service.py +++ b/src/apm_cli/install/service.py @@ -111,10 +111,13 @@ def enforce_frozen_services( user_scope: bool, project_root: Path | None = None, mcp_declared_transports: dict[str, str | None] | None = None, + mcp_target_servers: dict[str, set[str]] | None = None, ) -> frozenset[tuple[str, str]]: """Refuse unrecorded service claims before either service mutates native state. - MCP claims every server on every target. LSP claims are per target + MCP claims every server on every target, narrowed by + *mcp_target_servers* when a dependency's ``targets:`` selects fewer. + LSP claims are per target (*lsp_target_servers* maps each selected runtime to the servers it can express), so a server a target skips is never required to be owned there. @@ -148,7 +151,10 @@ def enforce_frozen_services( "from the available source declarations" ) deferred: set[tuple[str, str]] = set() - claims = [("MCP", target, mcp_servers, mcp_ownership) for target in mcp_targets] + [ + claims = [ + ("MCP", target, (mcp_target_servers or {}).get(target, mcp_servers), mcp_ownership) + for target in mcp_targets + ] + [ ("LSP", target, names, lockfile.lsp_target_servers) for target, names in lsp_target_servers.items() ] diff --git a/src/apm_cli/install/service_integration.py b/src/apm_cli/install/service_integration.py index 11ee2f8ba4..0c412c3645 100644 --- a/src/apm_cli/install/service_integration.py +++ b/src/apm_cli/install/service_integration.py @@ -116,7 +116,10 @@ def run_service_integrations( from apm_cli.install.service import InstallService from apm_cli.integration.lsp_integrator import LSPIntegrator from apm_cli.integration.mcp_integrator import MCPIntegrator - from apm_cli.integration.mcp_integrator_install import _resolve_target_runtimes + from apm_cli.integration.mcp_integrator_install import ( + _resolve_target_runtimes, + mcp_servers_for_runtime, + ) prepared_mcp = prepare_mcp_integration( apm_package=apm_package, @@ -169,6 +172,10 @@ def run_service_integrations( for dep in prepared_mcp.dependencies if hasattr(dep, "name") }, + mcp_target_servers={ + target: mcp_servers_for_runtime(prepared_mcp.dependencies, target) + for target in mcp_targets or [] + }, ) from apm_cli.install.mcp.ownership import frozen_unrecorded_mcp_pairs diff --git a/src/apm_cli/integration/mcp_integrator_install.py b/src/apm_cli/integration/mcp_integrator_install.py index cba3f9b6e4..a52020aecf 100644 --- a/src/apm_cli/integration/mcp_integrator_install.py +++ b/src/apm_cli/integration/mcp_integrator_install.py @@ -1415,6 +1415,34 @@ def _resolve_target_runtimes( return target_runtimes +def _declared_mcp_targets(dep: Any) -> list[str] | None: + declared = getattr(dep, "targets", None) + return list(declared) if isinstance(declared, (list, tuple)) and declared else None + + +def mcp_dependency_runtimes(dep: Any, target_runtimes: list[str]) -> list[str]: + """Narrow the run's runtimes to a dependency's ``targets:``; never widen them.""" + from apm_cli.core.target_detection import EffectiveTargetDecision + from apm_cli.models.dependency.subsets import canonical_target_name + + declared = _declared_mcp_targets(dep) + if declared is None: + return list(target_runtimes) + admitted = set(EffectiveTargetDecision(declared, "dependencies.mcp").runtime_equivalents) + return [rt for rt in target_runtimes if rt in admitted or canonical_target_name(rt) in declared] + + +def mcp_servers_for_runtime(mcp_deps: list, runtime: str, *, named_only: bool = False) -> set[str]: + """Declared servers *runtime* receives; ``named_only`` keeps those whose targets name it.""" + return { + dep.name if hasattr(dep, "name") else dep + for dep in mcp_deps + if (isinstance(dep, str) or hasattr(dep, "name")) + and (_declared_mcp_targets(dep) is not None or not named_only) + and mcp_dependency_runtimes(dep, [runtime]) + } + + def _install_self_defined_deps( self_defined_deps: list, target_runtimes: list[str], @@ -1899,16 +1927,11 @@ def run_mcp_install( # noqa: PLR0913 active_runtimes=active_targets, user_scope=user_scope, ) - current_names = { - dep.name if hasattr(dep, "name") else dep - for dep in mcp_deps - if isinstance(dep, str) or hasattr(dep, "name") - } for target in list(managed_target_servers): if target not in active_targets: del managed_target_servers[target] else: - managed_target_servers[target].intersection_update(current_names) + managed_target_servers[target] &= mcp_servers_for_runtime(mcp_deps, target) for target in target_runtimes: managed_target_servers.setdefault(target, set()) @@ -1944,6 +1967,14 @@ def run_mcp_install( # noqa: PLR0913 symbol="check", ) + dep_runtimes = {id(dep): mcp_dependency_runtimes(dep, target_runtimes) for dep in mcp_deps} + for dep in mcp_deps: + if not dep_runtimes[id(dep)]: + logger.warning( + f"MCP server '{dep.name}' targets [{', '.join(dep.targets)}] do not overlap " + f"active MCP targets [{', '.join(target_runtimes)}]; skipping" + ) + # Use the new registry operations module for better server detection configured_count = 0 written_connections: set[tuple[str, str]] = set() @@ -1958,14 +1989,13 @@ def run_mcp_install( # noqa: PLR0913 # resolved against the correct registry endpoint. # Plain strings (backward-compat) and deps with registry=None go to # the default group (key=None). Only str values trigger routing. - registry_groups: builtins.dict[str | None, list] = {} + registry_groups: builtins.dict[tuple, list] = {} for dep in registry_deps: - key = _registry_group_key(dep) - if key not in registry_groups: - registry_groups[key] = [] - registry_groups[key].append(dep) + key = (tuple(dep_runtimes[id(dep)]), _registry_group_key(dep)) + if key[0]: + registry_groups.setdefault(key, []).append(dep) - for group_registry_url, group_deps_list in registry_groups.items(): + for (group_runtimes, group_registry_url), group_deps_list in registry_groups.items(): group_dep_names = [ dep.name if hasattr(dep, "name") else dep for dep in group_deps_list ] @@ -1993,7 +2023,7 @@ def run_mcp_install( # noqa: PLR0913 group_dep_names=group_dep_names, group_dep_map=group_dep_map, group_deps=group_deps_list, - target_runtimes=target_runtimes, + target_runtimes=list(group_runtimes), stored_mcp_configs=stored_mcp_configs, servers_to_update=servers_to_update, successful_updates=successful_updates, @@ -2017,11 +2047,15 @@ def run_mcp_install( # noqa: PLR0913 raise RuntimeError("Registry operations module required for MCP installation") # noqa: B904 # --- Self-defined deps (registry: false) --- - if self_defined_deps: + self_defined_groups: builtins.dict[tuple, list] = {} + for dep in self_defined_deps: + if dep_runtimes[id(dep)]: + self_defined_groups.setdefault(tuple(dep_runtimes[id(dep)]), []).append(dep) + for group_runtimes, group_self_defined in self_defined_groups.items(): try: configured_count += _install_self_defined_deps( - self_defined_deps=self_defined_deps, - target_runtimes=target_runtimes, + self_defined_deps=group_self_defined, + target_runtimes=list(group_runtimes), stored_mcp_configs=stored_mcp_configs, servers_to_update=servers_to_update, successful_updates=successful_updates, diff --git a/src/apm_cli/models/dependency/mcp.py b/src/apm_cli/models/dependency/mcp.py index 3fc9ce7e20..556d80e9b2 100644 --- a/src/apm_cli/models/dependency/mcp.py +++ b/src/apm_cli/models/dependency/mcp.py @@ -11,6 +11,8 @@ from apm_cli.utils.github_host import has_parser_dependent_url_chars from apm_cli.utils.path_security import PathTraversalError, validate_path_segments +from .subsets import parse_target_subset + # Keys recognised by from_dict (including legacy alias 'type' -> 'transport'). _KNOWN_DICT_KEYS = frozenset( { @@ -37,6 +39,8 @@ # Keeps the "never leaks into mcp_configs" invariant airtight (#2081). "resolved_by", "approval_keys", + # Selects which install targets receive the server; never rendered (#2606). + "targets", } ) @@ -151,6 +155,8 @@ class MCPDependency: # OpenCode-only value forwarded unchanged; other target adapters ignore it. enabled: Any = _ENABLED_UNSET extra: dict[str, Any] | None = None # Harness-specific passthrough keys (e.g. oauth) + # Canonical install targets that receive this server; None = every active target. + targets: list[str] | None = None # Install-time provenance: the declaring package identity when this server # was contributed transitively (via a sub-package's apm.yml), else None for # servers declared directly in the root manifest. Set by @@ -222,6 +228,8 @@ def from_dict(cls, d: dict) -> "MCPDependency": ) transport = d.get("transport") or d.get("type") # legacy 'type' -> 'transport' + targets_raw = d.get("targets") # architecture-authority-exempt: dependency-target-subset + targets = parse_target_subset(targets_raw) if targets_raw is not None else None instance = cls( name=d["name"], @@ -238,6 +246,7 @@ def from_dict(cls, d: dict) -> "MCPDependency": cwd=d.get("cwd"), enabled=d.get("enabled", _ENABLED_UNSET), extra=extra, + targets=targets, ) if instance.registry is False: @@ -308,6 +317,8 @@ def to_dict(self) -> dict: result[field_name] = value if self.has_enabled: result["enabled"] = self.enabled + if self.targets is not None: + result["targets"] = list(self.targets) if self.extra: for k, v in self.extra.items(): if k not in result and k not in _EXTRA_DENYLIST: diff --git a/tests/integration/test_architecture_owner_rule_mutations.py b/tests/integration/test_architecture_owner_rule_mutations.py index d6b7ca0c1d..bc0ed0de02 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -4045,3 +4045,54 @@ def test_lock_target_canonicalisation_guard_rejects_mutations( assert any( violation.rule_id == rule_id and violation.path == path for violation in report.violations ) + + +@pytest.mark.parametrize( + ("path", "old", "new"), + [ + pytest.param( + "src/apm_cli/integration/mcp_integrator_install.py", + " dep_runtimes = {id(dep): mcp_dependency_runtimes(dep, target_runtimes) for dep", + " dep_runtimes = {id(dep): list(target_runtimes) for dep", + id="install-writes-every-server-to-every-target", + ), + pytest.param( + "src/apm_cli/integration/mcp_integrator_install.py", + "managed_target_servers[target] &= mcp_servers_for_runtime(mcp_deps, target)", + "managed_target_servers[target] &= set(managed_target_servers[target])", + id="claims-ignore-dependency-targets", + ), + pytest.param( + "src/apm_cli/install/mcp/integration.py", + "admitted = mcp_servers_for_runtime(mcp_deps, owned_target)", + "admitted = new_mcp_servers", + id="pruning-ignores-dependency-targets", + ), + pytest.param( + "src/apm_cli/install/mcp/integration.py", + " mcp_deps, owned_target, named_only=True\n", + " [], owned_target, named_only=True\n", + id="target-scoped-install-retires-other-targets", + ), + pytest.param( + "src/apm_cli/install/service_integration.py", + "mcp_servers_for_runtime(prepared_mcp.dependencies, target)", + "set(MCPIntegrator.get_server_names(prepared_mcp.dependencies))", + id="frozen-claims-every-server-on-every-target", + ), + ], +) +def test_mcp_dependency_target_selection_guard_rejects_mutations( + path: str, old: str, new: str +) -> None: + """#2606: per-dependency MCP targets route through the one selection owner.""" + rule_id = "mutation_writes.mcp_target_selection" + source = _source(path) + assert source.count(old) == 1 + mutated = source.replace(old, new, 1) + ast.parse(mutated, filename=path) + report = run_selected_rules(ROOT, (rule_id,), source_overrides={path: mutated}) + assert report.failures == () + assert any( + violation.rule_id == rule_id and violation.path == path for violation in report.violations + ) diff --git a/tests/integration/test_mcp_dependency_targets_lifecycle.py b/tests/integration/test_mcp_dependency_targets_lifecycle.py new file mode 100644 index 0000000000..91e94b2976 --- /dev/null +++ b/tests/integration/test_mcp_dependency_targets_lifecycle.py @@ -0,0 +1,98 @@ +"""Per-dependency ``targets:`` scopes MCP servers and per-target pruning (#2606). + +``targets`` on a ``dependencies.mcp`` entry selects which targets receive the +server. It is never written into a native MCP config, and a target-scoped +install keeps servers that are still declared for the targets it skips. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path + +import pytest +import yaml + +from tests.integration._mcp_chain_kit import Chain, stdio_server + +pytestmark = [ + pytest.mark.integration, + pytest.mark.requires_apm_binary, + pytest.mark.lifecycle_smoke, +] + + +def _scoped(name: str, *targets: str) -> dict: + return {**stdio_server(name, name), "targets": list(targets)} + + +def test_project_dependency_targets_scope_servers_per_target( + tmp_path: Path, apm_binary_path: Path +) -> None: + chain = Chain(tmp_path / "project", apm_binary_path, dirs=(".claude", ".cursor")) + chain.write_manifest( + [_scoped("srv-claude-only", "claude"), _scoped("srv-cursor-only", "cursor")], + targets=["claude", "cursor"], + ) + result = chain.ok("install", "--no-policy") + assert "preserved in extra" not in result.stdout + result.stderr + + assert set(chain.servers("claude")) == {"srv-claude-only"} + assert set(chain.servers("cursor")) == {"srv-cursor-only"} + for target in ("claude", "cursor"): + for entry in chain.servers(target).values(): + assert "targets" not in entry, target + assert chain.lock()["mcp_target_servers"] == { + "claude": ["srv-claude-only"], + "cursor": ["srv-cursor-only"], + } + + # Retargeting a server prunes it only from the target it no longer selects. + chain.write_manifest( + [_scoped("srv-claude-only", "cursor"), _scoped("srv-cursor-only", "cursor")], + targets=["claude", "cursor"], + ) + chain.ok("install", "--no-policy") + assert chain.servers("claude") == {} + assert set(chain.servers("cursor")) == {"srv-claude-only", "srv-cursor-only"} + chain.ok("install", "--no-policy", "--frozen") + + +def test_global_target_scoped_install_keeps_servers_declared_for_other_targets( + tmp_path: Path, apm_binary_path: Path +) -> None: + chain = Chain(tmp_path / "global", apm_binary_path) + home = chain.isolated.home + for directory in (".claude", ".codex"): + (home / directory).mkdir(parents=True, exist_ok=True) + apm_home = Path(chain.env["APM_HOME"]) + apm_home.mkdir(parents=True, exist_ok=True) + + def write_global(mcp: list[dict]) -> None: + manifest = {"name": "global", "version": "1.0.0", "dependencies": {"mcp": mcp}} + (apm_home / "apm.yml").write_text(yaml.safe_dump(manifest), encoding="utf-8") + + def claude_servers() -> dict: + path = home / ".claude.json" + return json.loads(path.read_text("utf-8")).get("mcpServers", {}) if path.exists() else {} + + write_global([stdio_server("srv-a", "a")]) + chain.ok("install", "-g", "--no-policy", "--only", "mcp", "--target", "claude") + assert set(claude_servers()) == {"srv-a"} + + write_global([_scoped("srv-a", "claude"), _scoped("srv-b", "codex")]) + result = chain.ok("install", "-g", "--no-policy", "--only", "mcp", "--target", "codex") + assert "Removed stale MCP server 'srv-a'" not in result.stdout + assert set(claude_servers()) == {"srv-a"} + + codex_text = (home / ".codex" / "config.toml").read_text("utf-8") + codex_names = { + name + for name in re.findall(r"^\[mcp_servers\.([^\].]+)\]$", codex_text, re.M) + if not name.endswith(".env") + } + assert codex_names == {"srv-b"} + assert not re.search(r"^targets\s*=", codex_text, re.M) + lock = yaml.safe_load((apm_home / "apm.lock.yaml").read_text("utf-8")) + assert lock["mcp_target_servers"] == {"claude": ["srv-a"], "codex": ["srv-b"]} diff --git a/tests/unit/test_mcp_overlays.py b/tests/unit/test_mcp_overlays.py index e2af06642a..e08717d290 100644 --- a/tests/unit/test_mcp_overlays.py +++ b/tests/unit/test_mcp_overlays.py @@ -945,3 +945,19 @@ def test_opencode_enabled_object_order_does_not_create_drift() -> None: ) == set() ) + + +class TestMCPDependencyTargetsScoping: + """Regression for #2606: ``targets`` scopes reach; it is not a harness passthrough key.""" + + def test_targets_key_does_not_leak_into_extra(self): + dep = MCPDependency.from_dict( + { + "name": "srv-claude-only", + "registry": False, + "transport": "stdio", + "command": "echo", + "targets": ["claude"], + } + ) + assert "targets" not in (dep.extra or {}) From 07bb501f27c45e96fdfa39fe623d5dfe5802dcae Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 19 Nov 2026 18:20:33 +0100 Subject: [PATCH 2/6] fix(mcp): retire claims on targets the manifest itself drops A target-scoped install keeps servers whose entry targets: still name a target outside the run. When the manifest's own targets: is what dropped that target, no entry reaches it, so its claims retire as before. Extend the lifecycle test with the manifest-drop and undeclare cases. apm-spec-waiver: implements accepted issue #2606 scope; no normative spec requirement changes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/install/mcp/integration.py | 6 ++++++ .../test_mcp_dependency_targets_lifecycle.py | 14 ++++++++++++++ tests/unit/test_mcp_overlays.py | 7 +++++++ 3 files changed, 27 insertions(+) diff --git a/src/apm_cli/install/mcp/integration.py b/src/apm_cli/install/mcp/integration.py index 436c7ffa05..4436c43c00 100644 --- a/src/apm_cli/install/mcp/integration.py +++ b/src/apm_cli/install/mcp/integration.py @@ -572,6 +572,10 @@ def _keep_unhealed(healed: dict[str, builtins.set]) -> None: from apm_cli.install.mcp.ownership import names_owned_by_active_peers from apm_cli.integration.mcp_integrator_install import mcp_servers_for_runtime + # Targets the manifest itself stopped selecting leave every entry's reach. + manifest_selected = ( + runtime is None and target_decision is not None and target_decision.source == "apm.yml" + ) retired_by_target: builtins.dict[str, builtins.set] = {} for owned_target, owned in sorted(old_mcp_target_servers.items()): if owned_target in managed_target_servers: @@ -583,6 +587,8 @@ def _keep_unhealed(healed: dict[str, builtins.set]) -> None: kept = builtins.set(owned) & mcp_servers_for_runtime( mcp_deps, owned_target, named_only=True ) + if manifest_selected: + kept = builtins.set() if kept: managed_target_servers[owned_target] = kept retired_by_target[owned_target] = builtins.set(owned) - kept diff --git a/tests/integration/test_mcp_dependency_targets_lifecycle.py b/tests/integration/test_mcp_dependency_targets_lifecycle.py index 91e94b2976..410488191d 100644 --- a/tests/integration/test_mcp_dependency_targets_lifecycle.py +++ b/tests/integration/test_mcp_dependency_targets_lifecycle.py @@ -58,6 +58,15 @@ def test_project_dependency_targets_scope_servers_per_target( assert set(chain.servers("cursor")) == {"srv-claude-only", "srv-cursor-only"} chain.ok("install", "--no-policy", "--frozen") + # A target the manifest itself drops leaves every entry's reach. + chain.write_manifest( + [_scoped("srv-claude-only", "cursor"), _scoped("srv-cursor-only", "cursor")], + targets=["claude"], + ) + chain.ok("install", "--no-policy") + assert chain.servers("cursor") == {} + assert chain.lock().get("mcp_target_servers", {}) == {} + def test_global_target_scoped_install_keeps_servers_declared_for_other_targets( tmp_path: Path, apm_binary_path: Path @@ -96,3 +105,8 @@ def claude_servers() -> dict: assert not re.search(r"^targets\s*=", codex_text, re.M) lock = yaml.safe_load((apm_home / "apm.lock.yaml").read_text("utf-8")) assert lock["mcp_target_servers"] == {"claude": ["srv-a"], "codex": ["srv-b"]} + + # Undeclaring the server still retires it from the target outside this run. + write_global([_scoped("srv-b", "codex")]) + chain.ok("install", "-g", "--no-policy", "--only", "mcp", "--target", "codex") + assert claude_servers() == {} diff --git a/tests/unit/test_mcp_overlays.py b/tests/unit/test_mcp_overlays.py index e08717d290..7dc3a4ffe9 100644 --- a/tests/unit/test_mcp_overlays.py +++ b/tests/unit/test_mcp_overlays.py @@ -961,3 +961,10 @@ def test_targets_key_does_not_leak_into_extra(self): } ) assert "targets" not in (dep.extra or {}) + + def test_targets_is_modeled_and_rejects_unknown_target_names(self): + base = {"name": "srv", "registry": False, "transport": "stdio", "command": "echo"} + scoped = MCPDependency.from_dict({**base, "targets": ["claude"]}) + assert scoped.targets == ["claude"] + with pytest.raises(ValueError, match="Unknown target 'claud'"): + MCPDependency.from_dict({**base, "targets": ["claud"]}) From 9942b6736b68d7734b25493cd0e06f30cd60af7f Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 19 Nov 2026 18:26:16 +0100 Subject: [PATCH 3/6] docs(changelog): reference #3951 for #2606 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d32659cde..5fd82f2035 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,7 +37,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- `targets:` on a `dependencies.mcp` entry now limits which targets get the server and is no longer written into native MCP config; `apm install -g --target codex` keeps servers declared for other targets. (closes #2606, #PR_NUMBER) +- `targets:` on `dependencies.mcp` entries now limits which targets get each server, is never written into native config, and target-scoped installs keep servers declared elsewhere. (closes #2606, #3951) - `apm uninstall plugin@marketplace` removes object-form `{name, marketplace}` entries from `apm.yml`, offline, with their lock row and files. (closes #3928, #3933) - Marketplace entries in `apm.yml`, transitive marketplace dependencies and `apm update` now refuse bare cross-repo `repo:` on `*.ghe.com` marketplaces, as CLI installs already did. (closes #3913, #3923) - `*.ghe.com` marketplaces now refuse bare cross-repo `git-subdir`, `gitlab` and `url` sources too, not only `type: github`. (closes #3937, #3942) From 1bd9ac3f7d07aab83593c7941ad8e5b0ca150f9c Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 19 Nov 2026 18:31:23 +0100 Subject: [PATCH 4/6] fix(mcp): skip only entries whose declared targets miss the run The skip path assumed every dependency had a targets list and dropped untargeted deps from registry and self-defined groups whenever the run's runtime list was empty, so registry operations were never built. Skip and warn only when the entry declares targets: with no overlap. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/integration/mcp_integrator_install.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/apm_cli/integration/mcp_integrator_install.py b/src/apm_cli/integration/mcp_integrator_install.py index a52020aecf..84a8134ac1 100644 --- a/src/apm_cli/integration/mcp_integrator_install.py +++ b/src/apm_cli/integration/mcp_integrator_install.py @@ -1968,10 +1968,13 @@ def run_mcp_install( # noqa: PLR0913 ) dep_runtimes = {id(dep): mcp_dependency_runtimes(dep, target_runtimes) for dep in mcp_deps} + scoped_out: set[int] = set() for dep in mcp_deps: - if not dep_runtimes[id(dep)]: + declared = _declared_mcp_targets(dep) + if declared is not None and not dep_runtimes[id(dep)]: + scoped_out.add(id(dep)) logger.warning( - f"MCP server '{dep.name}' targets [{', '.join(dep.targets)}] do not overlap " + f"MCP server '{dep.name}' targets [{', '.join(declared)}] do not overlap " f"active MCP targets [{', '.join(target_runtimes)}]; skipping" ) @@ -1992,7 +1995,7 @@ def run_mcp_install( # noqa: PLR0913 registry_groups: builtins.dict[tuple, list] = {} for dep in registry_deps: key = (tuple(dep_runtimes[id(dep)]), _registry_group_key(dep)) - if key[0]: + if id(dep) not in scoped_out: registry_groups.setdefault(key, []).append(dep) for (group_runtimes, group_registry_url), group_deps_list in registry_groups.items(): @@ -2049,7 +2052,7 @@ def run_mcp_install( # noqa: PLR0913 # --- Self-defined deps (registry: false) --- self_defined_groups: builtins.dict[tuple, list] = {} for dep in self_defined_deps: - if dep_runtimes[id(dep)]: + if id(dep) not in scoped_out: self_defined_groups.setdefault(tuple(dep_runtimes[id(dep)]), []).append(dep) for group_runtimes, group_self_defined in self_defined_groups.items(): try: From 1c4ba2e63252e4ba59daca370770888481cbf461 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 19 Nov 2026 19:07:34 +0100 Subject: [PATCH 5/6] fix(mcp): fold panel follow-ups for per-target MCP pruning Addresses the #3951 panel (CEO follow-ups 1-4): - typed EffectiveTargetDecision.from_manifest replaces the free-form source == "apm.yml" check that decided manifest-drop retirement; - deselected_mcp_claims in ownership.py is the one retire algebra for the install and owned (bundle) paths; the guard pins both plus the typed predicate, with two new mutation cases; - tests for the no-overlap skip warning, untargeted servers following --target, the retained claim's native-hash receipt, registry grouping by narrowed runtimes, and owned-path deselection; - docs: skip warning, manifest-drop rule, untargeted rule and the shared claude/copilot .mcp.json reach. apm-spec-waiver: implements accepted issue #2606 scope; no normative spec requirement changes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../docs/consumer/install-mcp-servers.md | 4 ++ .../content/docs/reference/manifest-schema.md | 2 +- .../.apm/skills/apm-usage/dependencies.md | 6 ++- .../checks/mutation_mcp_target_and_scope.py | 4 +- src/apm_cli/core/target_detection.py | 13 ++++++- src/apm_cli/install/mcp/integration.py | 20 +++++++--- src/apm_cli/install/mcp/ownership.py | 5 +++ .../integration/mcp_integrator_install.py | 6 ++- .../test_architecture_owner_rule_mutations.py | 12 ++++++ .../test_mcp_dependency_targets_lifecycle.py | 35 +++++++++++++---- .../install/test_owned_mcp_integration.py | 38 +++++++++++++++++++ .../integration/test_mcp_per_dep_registry.py | 35 +++++++++++++++++ 12 files changed, 159 insertions(+), 21 deletions(-) diff --git a/docs/src/content/docs/consumer/install-mcp-servers.md b/docs/src/content/docs/consumer/install-mcp-servers.md index 61b7e8306f..bfbbdbf366 100644 --- a/docs/src/content/docs/consumer/install-mcp-servers.md +++ b/docs/src/content/docs/consumer/install-mcp-servers.md @@ -352,6 +352,10 @@ MCP install resolves targets in this order: post-exclusion selection; project, scope, and adapter gates can still skip a write. +A `targets:` list on one `dependencies.mcp` entry narrows that set further +for that server; see [Manifest Schema](../../reference/manifest-schema/). +`apm install --target codex` does not remove a server scoped to `[claude]`. + The same effective decision drives package, MCP, and LSP phases; APM does not re-resolve each phase independently. diff --git a/docs/src/content/docs/reference/manifest-schema.md b/docs/src/content/docs/reference/manifest-schema.md index b69304f0a9..9b682e560b 100644 --- a/docs/src/content/docs/reference/manifest-schema.md +++ b/docs/src/content/docs/reference/manifest-schema.md @@ -776,7 +776,7 @@ A plain registry reference: `io.github.github/github-mcp-server`. | `url` | `string` | Conditional | | Endpoint URL. REQUIRED when `registry: false` and `transport` is `http`, `sse`, or `streamable-http`. | | `command` | `string` | Conditional | Single binary path; no embedded whitespace unless `args` is also present | Binary path. REQUIRED when `registry: false` and `transport` is `stdio`. | | `enabled` | any JSON value | OPTIONAL | OpenCode only | Passed unchanged to OpenCode's `opencode.json` entry. When omitted, APM keeps its existing `true` default. APM does not validate the value; OpenCode interprets it. In the OpenCode 2 `mcp.servers` layout, `false` becomes `disabled: true`, `true` writes no field, and other values warn and leave the file unchanged; see [OpenCode 2 configuration](../../consumer/install-mcp-servers/#opencode-2-configuration). Other targets ignore this field. | -| `targets` | `list` | OPTIONAL | Non-empty; known target names | Targets that receive this server: effective reach is the install targets intersected with this list. Omitted = every install target. Never written into a native MCP config. A target-scoped install (`--target`) keeps the server in the other targets it lists; reinstall prunes it only from targets it no longer lists. | +| `targets` | `list` | OPTIONAL | Non-empty; known target names | Targets that receive this server: effective reach is the install targets intersected with this list. Omitted = every install target. No overlap = skipped with a warning. Never written to native config. A `--target` install keeps the server in other targets it lists; an untargeted server follows `--target`. Dropping a target from this list, or from the manifest `targets:`, removes the server there on the next install. In project scope `claude` and `copilot` share `.mcp.json`, so naming either one makes the server visible to both. | Any additional keys not listed above are preserved as **extra passthrough fields** and round-tripped verbatim into the generated target manifests. This allows harness-specific configuration (e.g. Claude Code's `oauth` block for remote-MCP OAuth client config) to be declared in `apm.yml` and appear in the generated config without modification. A warning is emitted at parse time naming each non-standard key. diff --git a/packages/apm-guide/.apm/skills/apm-usage/dependencies.md b/packages/apm-guide/.apm/skills/apm-usage/dependencies.md index eb89fff51a..b690bff3d5 100644 --- a/packages/apm-guide/.apm/skills/apm-usage/dependencies.md +++ b/packages/apm-guide/.apm/skills/apm-usage/dependencies.md @@ -715,8 +715,10 @@ dependencies: env: API_KEY: ${{ secrets.KEY }} - # Per-server targets: install targets INTERSECT this list (omitted = all). - # Never written into native config; reinstall prunes only dropped targets. + # Per-server targets: install targets INTERSECT this list (omitted = all; + # no overlap = skipped with a warning). Never written into native config. + # Dropping a target here or from manifest targets: prunes it on reinstall. + # Project-scope claude and copilot share .mcp.json: either name reaches both. - name: claude-only-tools registry: false transport: stdio diff --git a/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py b/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py index b60faaab7f..20681793bc 100644 --- a/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py +++ b/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py @@ -286,12 +286,14 @@ def _check_mcp_target_selection(provider: FactsProvider) -> Iterable[Violation]: ( "admitted = mcp_servers_for_runtime(mcp_deps, owned_target)", "mcp_deps, owned_target, named_only=True", + "deselected_mcp_claims(", + "target_decision.from_manifest", ), ), ( _MCP_INTEGRATION, "run_owned_mcp_integration", - ("mcp_servers_for_runtime(dependencies, target)",), + ("mcp_servers_for_runtime(dependencies, target)", "deselected_mcp_claims("), ), ( "src/apm_cli/install/service_integration.py", diff --git a/src/apm_cli/core/target_detection.py b/src/apm_cli/core/target_detection.py index 6a50e4db7d..3c7ef54c9e 100644 --- a/src/apm_cli/core/target_detection.py +++ b/src/apm_cli/core/target_detection.py @@ -873,6 +873,10 @@ def canonical_policy_target_name(value: str | None) -> str | None: return names[0] if names else None +# Provenance label of a decision taken from the manifest's ``targets:``. +MANIFEST_TARGET_SOURCE = "apm.yml" + + @dataclass(frozen=True) class EffectiveTargetDecision: """One install-time target decision shared by package, MCP, and LSP phases.""" @@ -880,6 +884,11 @@ class EffectiveTargetDecision: value: str | list[str] | None source: str + @property + def from_manifest(self) -> bool: + """True when the manifest's own ``targets:`` made this decision.""" + return self.source == MANIFEST_TARGET_SOURCE + @cached_property def canonical_targets(self) -> tuple[str, ...] | None: """Return the selected native target profiles, or None when unrestricted.""" @@ -984,7 +993,7 @@ def resolve_effective_target_decision( return EffectiveTargetDecision(explicit_target, "--target flag") if manifest_target: - return EffectiveTargetDecision(manifest_target, "apm.yml") + return EffectiveTargetDecision(manifest_target, MANIFEST_TARGET_SOURCE) from apm_cli.config import get_install_target @@ -1032,7 +1041,7 @@ def resolve_audit_target_decision( Without declared or recorded intent, preserve audit's discovery fallback. """ if manifest_target: - return EffectiveTargetDecision(manifest_target, "apm.yml") + return EffectiveTargetDecision(manifest_target, MANIFEST_TARGET_SOURCE) if recorded_targets: return EffectiveTargetDecision(list(recorded_targets), "deployment ledger") return EffectiveTargetDecision(None, "auto-detect") diff --git a/src/apm_cli/install/mcp/integration.py b/src/apm_cli/install/mcp/integration.py index 4436c43c00..7a6482fc4e 100644 --- a/src/apm_cli/install/mcp/integration.py +++ b/src/apm_cli/install/mcp/integration.py @@ -111,6 +111,7 @@ def run_owned_mcp_integration( from apm_cli.deps.lockfile import LockFile from apm_cli.install.errors import MCPNativeConflictError from apm_cli.install.mcp.ownership import ( + deselected_mcp_claims, names_owned_by_active_peers, retain_deferred_mcp_claims, ) @@ -186,9 +187,11 @@ def run_owned_mcp_integration( stale_for_target = (stale if target in selected_targets else old_owned) & names if target in selected_targets: # Declared servers whose `targets:` no longer select this runtime. - stale_for_target |= ( - previous_targets.get(target, set()) & old_owned & new_names - ) - mcp_servers_for_runtime(dependencies, target) + stale_for_target |= deselected_mcp_claims( + previous_targets.get(target, set()) & old_owned, + new_names, + mcp_servers_for_runtime(dependencies, target), + ) if stale_for_target and conflict is None: # An entry in a shared file (.mcp.json) stays while an active peer # owns it; only this runtime's claim retires. @@ -569,19 +572,24 @@ def _keep_unhealed(healed: dict[str, builtins.set]) -> None: builtins.set(new_mcp_servers), managed_target_servers.get("copilot") if "copilot" in managed_target_servers else None, ) - from apm_cli.install.mcp.ownership import names_owned_by_active_peers + from apm_cli.install.mcp.ownership import ( + deselected_mcp_claims, + names_owned_by_active_peers, + ) from apm_cli.integration.mcp_integrator_install import mcp_servers_for_runtime # Targets the manifest itself stopped selecting leave every entry's reach. manifest_selected = ( - runtime is None and target_decision is not None and target_decision.source == "apm.yml" + runtime is None and target_decision is not None and target_decision.from_manifest ) retired_by_target: builtins.dict[str, builtins.set] = {} for owned_target, owned in sorted(old_mcp_target_servers.items()): if owned_target in managed_target_servers: # Declared servers whose `targets:` no longer select this runtime. admitted = mcp_servers_for_runtime(mcp_deps, owned_target) - retired_by_target[owned_target] = (builtins.set(owned) & new_mcp_servers) - admitted + retired_by_target[owned_target] = deselected_mcp_claims( + owned, new_mcp_servers, admitted + ) continue # A runtime this run does not select keeps the servers that name it. kept = builtins.set(owned) & mcp_servers_for_runtime( diff --git a/src/apm_cli/install/mcp/ownership.py b/src/apm_cli/install/mcp/ownership.py index 2cd5982c57..ec92a300ad 100644 --- a/src/apm_cli/install/mcp/ownership.py +++ b/src/apm_cli/install/mcp/ownership.py @@ -727,6 +727,11 @@ def names_owned_by_active_peers( return kept +def deselected_mcp_claims(owned: set[str], declared: set[str], selected: set[str]) -> set[str]: + """Owned, still-declared servers a target's ``targets:`` selection no longer includes.""" + return (set(owned) & set(declared)) - set(selected) + + def retain_deferred_mcp_claims( current: dict[str, set[str]], previous: dict[str, set[str]], diff --git a/src/apm_cli/integration/mcp_integrator_install.py b/src/apm_cli/integration/mcp_integrator_install.py index 84a8134ac1..76b738715e 100644 --- a/src/apm_cli/integration/mcp_integrator_install.py +++ b/src/apm_cli/integration/mcp_integrator_install.py @@ -1973,9 +1973,11 @@ def run_mcp_install( # noqa: PLR0913 declared = _declared_mcp_targets(dep) if declared is not None and not dep_runtimes[id(dep)]: scoped_out.add(id(dep)) + # Logged inline: an MCP-only run that changes nothing never + # renders the diagnostics summary, which would hide the skip. logger.warning( - f"MCP server '{dep.name}' targets [{', '.join(declared)}] do not overlap " - f"active MCP targets [{', '.join(target_runtimes)}]; skipping" + f"{dep.name}: MCP server targets [{', '.join(declared)}] do not overlap " + f"active install targets [{', '.join(target_runtimes)}]; skipping" ) # Use the new registry operations module for better server detection diff --git a/tests/integration/test_architecture_owner_rule_mutations.py b/tests/integration/test_architecture_owner_rule_mutations.py index bc0ed0de02..db8d57c768 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -4080,6 +4080,18 @@ def test_lock_target_canonicalisation_guard_rejects_mutations( "set(MCPIntegrator.get_server_names(prepared_mcp.dependencies))", id="frozen-claims-every-server-on-every-target", ), + pytest.param( + "src/apm_cli/install/mcp/integration.py", + "target_decision is not None and target_decision.from_manifest", + 'target_decision is not None and target_decision.source == "apm.yml"', + id="manifest-drop-keyed-on-display-label", + ), + pytest.param( + "src/apm_cli/install/mcp/integration.py", + " stale_for_target |= deselected_mcp_claims(\n", + " stale_for_target |= set().union(\n", + id="owned-path-forks-deselection-algebra", + ), ], ) def test_mcp_dependency_target_selection_guard_rejects_mutations( diff --git a/tests/integration/test_mcp_dependency_targets_lifecycle.py b/tests/integration/test_mcp_dependency_targets_lifecycle.py index 410488191d..680aa5802d 100644 --- a/tests/integration/test_mcp_dependency_targets_lifecycle.py +++ b/tests/integration/test_mcp_dependency_targets_lifecycle.py @@ -14,6 +14,8 @@ import pytest import yaml +from apm_cli.core.deployment_ledger import DeploymentLedgerCodec +from apm_cli.deps.lockfile import LockFile from tests.integration._mcp_chain_kit import Chain, stdio_server pytestmark = [ @@ -58,6 +60,18 @@ def test_project_dependency_targets_scope_servers_per_target( assert set(chain.servers("cursor")) == {"srv-claude-only", "srv-cursor-only"} chain.ok("install", "--no-policy", "--frozen") + # An entry whose targets miss every active target is skipped, with a warning. + chain.write_manifest( + [_scoped("srv-claude-only", "cursor"), _scoped("srv-codex-only", "codex")], + targets=["claude", "cursor"], + ) + result = chain.ok("install", "--no-policy") + output = " ".join((result.stdout + result.stderr).split()) + assert "srv-codex-only: MCP server targets [codex] do not overlap" in output + assert "srv-codex-only" not in chain.servers("claude") + assert "srv-codex-only" not in chain.servers("cursor") + assert chain.lock()["mcp_target_servers"] == {"cursor": ["srv-claude-only"]} + # A target the manifest itself drops leaves every entry's reach. chain.write_manifest( [_scoped("srv-claude-only", "cursor"), _scoped("srv-cursor-only", "cursor")], @@ -86,11 +100,16 @@ def claude_servers() -> dict: path = home / ".claude.json" return json.loads(path.read_text("utf-8")).get("mcpServers", {}) if path.exists() else {} - write_global([stdio_server("srv-a", "a")]) + write_global([stdio_server("srv-a", "a"), stdio_server("srv-c", "c")]) chain.ok("install", "-g", "--no-policy", "--only", "mcp", "--target", "claude") - assert set(claude_servers()) == {"srv-a"} + assert set(claude_servers()) == {"srv-a", "srv-c"} + lock_path = apm_home / "apm.lock.yaml" + receipt = DeploymentLedgerCodec.mcp_native_hashes(LockFile.read(lock_path))["claude"]["srv-a"] - write_global([_scoped("srv-a", "claude"), _scoped("srv-b", "codex")]) + # An untargeted server follows the run's --target; a scoped one keeps its targets. + write_global( + [_scoped("srv-a", "claude"), _scoped("srv-b", "codex"), stdio_server("srv-c", "c")] + ) result = chain.ok("install", "-g", "--no-policy", "--only", "mcp", "--target", "codex") assert "Removed stale MCP server 'srv-a'" not in result.stdout assert set(claude_servers()) == {"srv-a"} @@ -101,12 +120,14 @@ def claude_servers() -> dict: for name in re.findall(r"^\[mcp_servers\.([^\].]+)\]$", codex_text, re.M) if not name.endswith(".env") } - assert codex_names == {"srv-b"} + assert codex_names == {"srv-b", "srv-c"} assert not re.search(r"^targets\s*=", codex_text, re.M) - lock = yaml.safe_load((apm_home / "apm.lock.yaml").read_text("utf-8")) - assert lock["mcp_target_servers"] == {"claude": ["srv-a"], "codex": ["srv-b"]} + lock = yaml.safe_load(lock_path.read_text("utf-8")) + assert lock["mcp_target_servers"] == {"claude": ["srv-a"], "codex": ["srv-b", "srv-c"]} + kept = DeploymentLedgerCodec.mcp_native_hashes(LockFile.read(lock_path))["claude"] + assert kept["srv-a"] == receipt # Undeclaring the server still retires it from the target outside this run. - write_global([_scoped("srv-b", "codex")]) + write_global([_scoped("srv-b", "codex"), stdio_server("srv-c", "c")]) chain.ok("install", "-g", "--no-policy", "--only", "mcp", "--target", "codex") assert claude_servers() == {} diff --git a/tests/unit/install/test_owned_mcp_integration.py b/tests/unit/install/test_owned_mcp_integration.py index 6e4355af5e..d9db72905b 100644 --- a/tests/unit/install/test_owned_mcp_integration.py +++ b/tests/unit/install/test_owned_mcp_integration.py @@ -170,3 +170,41 @@ def install(owner: str, names: list[str]) -> int: assert set(actual) == ({"new", "old", "other", "clash"} if conflict else {"new", "other"}) if conflict: assert actual["clash"] == native["mcpServers"]["clash"] + + +def test_owned_mcp_retires_only_servers_targets_no_longer_select(tmp_path) -> None: + """#2606: a still-declared server leaves a target its ``targets:`` dropped.""" + lock_path = tmp_path / "apm.lock.yaml" + lockfile = LockFile() + lockfile.mcp_config_provenance = {"a": "bundle:bundle-a", "b": "bundle:bundle-a"} + lockfile.mcp_configs = {"a": {"name": "a"}, "b": {"name": "b"}} + lockfile.mcp_target_servers = {"codex": {"a", "b"}} + lockfile.write(lock_path) + scoped = MCPDependency(name="a", transport="stdio", command="echo", targets=["claude"]) + + def fake_install(dependencies, **kwargs): + kwargs["managed_target_servers"].setdefault("codex", set()) + return len(dependencies) + + with ( + patch( + "apm_cli.integration.mcp_integrator.MCPIntegrator.install", + side_effect=fake_install, + ), + patch("apm_cli.integration.mcp_integrator.MCPIntegrator.remove_stale") as remove_stale, + ): + run_owned_mcp_integration( + dependencies=[scoped, _dependency("b")], + owner="bundle-a", + lock_path=lock_path, + project_root=tmp_path, + user_scope=False, + target_runtimes=["codex"], + ) + + remove_stale.assert_called_once() + assert remove_stale.call_args.args[0] == {"a"} + assert remove_stale.call_args.kwargs["runtime"] == "codex" + updated = LockFile.read(lock_path) + assert updated is not None + assert updated.mcp_target_servers == {"codex": ["b"]} diff --git a/tests/unit/integration/test_mcp_per_dep_registry.py b/tests/unit/integration/test_mcp_per_dep_registry.py index c64c7cd532..f241d1a986 100644 --- a/tests/unit/integration/test_mcp_per_dep_registry.py +++ b/tests/unit/integration/test_mcp_per_dep_registry.py @@ -367,3 +367,38 @@ def test_false_registry_deps_are_excluded_from_registry_groups(self): # The registry group only sees registry-server validate_call = ops_mock.validate_servers_exist.call_args assert validate_call[0][0] == ["registry-server"] + + +class TestRegistryDepsNarrowedByTargets: + """#2606: a registry group receives only the runtimes its deps' ``targets:`` select.""" + + def test_same_registry_deps_with_different_targets_split_by_runtimes(self): + dep_claude = _make_dep("srv-claude", targets=["claude"]) + dep_cursor = _make_dep("srv-cursor", targets=["cursor"]) + dep_all = _make_dep("srv-all") + dep_none = _make_dep("srv-none", targets=["codex"]) + module = "apm_cli.integration.mcp_integrator_install" + + with ( + patch(_OPS_PATH, return_value=_make_operations_mock([])), + patch(f"{module}._resolve_target_runtimes", return_value=["claude", "cursor"]), + patch(f"{module}._validate_target_configs"), + patch(f"{module}._resolve_frozen_deferred_pairs"), + patch(f"{module}._install_registry_group", return_value=0) as install_group, + ): + from apm_cli.integration.mcp_integrator_install import run_mcp_install + + run_mcp_install( + mcp_deps=[dep_claude, dep_cursor, dep_all, dep_none], + logger=MagicMock(), + ) + + groups = sorted( + (tuple(c.kwargs["target_runtimes"]), tuple(c.kwargs["group_dep_names"])) + for c in install_group.call_args_list + ) + assert groups == [ + (("claude",), ("srv-claude",)), + (("claude", "cursor"), ("srv-all",)), + (("cursor",), ("srv-cursor",)), + ] From 491110afb8ab1b3d7661bcd37f48075e61d5bc72 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 19 Nov 2026 20:16:04 +0100 Subject: [PATCH 6/6] fix(mcp): keep retained MCP claims correct across exclude and retarget Addresses Copilot inline review on #3951: - src/apm_cli/install/mcp/integration.py:621: --exclude no longer clears claims on a target the manifest still lists; only targets missing from the manifest's own runtimes retire. - integration.py:623: a skipped target keeps the old declaration baseline for its retained servers, so its next install sees the drift and applies the new declaration. - src/apm_cli/integration/mcp_integrator_install.py:1934: retargeting between claude and copilot hands the shared .mcp.json claim and receipt to the newly selected peer before narrowing, so the entry is not read as foreign or deleted. Lifecycle regression covers all three; guard and mutation case pin the shared-claim transfer. apm-spec-waiver: implements accepted issue #2606 scope; no normative spec requirement changes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../checks/mutation_mcp_target_and_scope.py | 4 ++- src/apm_cli/install/mcp/integration.py | 20 ++++++++--- src/apm_cli/install/mcp/ownership.py | 26 ++++++++++++++ .../integration/mcp_integrator_install.py | 8 ++++- .../test_architecture_owner_rule_mutations.py | 8 ++++- .../test_mcp_dependency_targets_lifecycle.py | 34 +++++++++++++++++++ 6 files changed, 93 insertions(+), 7 deletions(-) diff --git a/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py b/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py index 23de87d12e..89f5a5d424 100644 --- a/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py +++ b/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py @@ -277,7 +277,9 @@ def _check_mcp_target_selection(provider: FactsProvider) -> Iterable[Violation]: "run_mcp_install", ( "mcp_dependency_runtimes(dep, target_runtimes)", - "managed_target_servers[target] &= mcp_servers_for_runtime(mcp_deps, target)", + "selected = {target: mcp_servers_for_runtime(mcp_deps, target) for target in", + "managed_target_servers[target] &= selected[target]", + "transfer_deselected_shared_claims(", ), ), ( diff --git a/src/apm_cli/install/mcp/integration.py b/src/apm_cli/install/mcp/integration.py index ce196f8449..ca317106d4 100644 --- a/src/apm_cli/install/mcp/integration.py +++ b/src/apm_cli/install/mcp/integration.py @@ -600,11 +600,15 @@ def _keep_unhealed(healed: dict[str, builtins.set]) -> None: ) from apm_cli.integration.mcp_integrator_install import mcp_servers_for_runtime - # Targets the manifest itself stopped selecting leave every entry's reach. - manifest_selected = ( - runtime is None and target_decision is not None and target_decision.from_manifest + # Targets the manifest itself stopped selecting leave every entry's reach; + # a target only excluded from this run (--exclude) is still listed there. + manifest_runtimes = ( + builtins.set(target_decision.runtime_targets_for_scope(user_scope=user_scope) or ()) + if runtime is None and target_decision is not None and target_decision.from_manifest + else None ) retired_by_target: builtins.dict[str, builtins.set] = {} + retained_names: builtins.set = builtins.set() for owned_target, owned in sorted(old_mcp_target_servers.items()): if owned_target in managed_target_servers: # Declared servers whose `targets:` no longer select this runtime. @@ -617,11 +621,19 @@ def _keep_unhealed(healed: dict[str, builtins.set]) -> None: kept = builtins.set(owned) & mcp_servers_for_runtime( mcp_deps, owned_target, named_only=True ) - if manifest_selected: + if manifest_runtimes is not None and owned_target not in manifest_runtimes: kept = builtins.set() if kept: managed_target_servers[owned_target] = kept + retained_names |= kept retired_by_target[owned_target] = builtins.set(owned) - kept + # A skipped target still holds the old declaration: keep that baseline + # so its next install sees the drift and applies the new one. + for name in MCPIntegrator._detect_mcp_config_drift( + [dep for dep in mcp_deps if getattr(dep, "name", None) in retained_names], + old_mcp_configs, + ): + new_mcp_configs[name] = old_mcp_configs[name] for removed_target, retired_names in retired_by_target.items(): # An entry in a file the removed runtime shares (.mcp.json) stays # while an active runtime still owns it. diff --git a/src/apm_cli/install/mcp/ownership.py b/src/apm_cli/install/mcp/ownership.py index ec92a300ad..a065757fc0 100644 --- a/src/apm_cli/install/mcp/ownership.py +++ b/src/apm_cli/install/mcp/ownership.py @@ -713,6 +713,32 @@ def inherit_shared_destination_claims( native_hashes.setdefault(peer, {}).setdefault(name, peer_hash) +def transfer_deselected_shared_claims( + managed_target_servers: dict[str, set[str]], + native_hashes: dict[str, dict[str, str]] | None, + *, + selected: Mapping[str, set[str]], + user_scope: bool, +) -> None: + """Hand a shared-file claim to the active peer a server's ``targets:`` now selects. + + The entry in the shared file (.mcp.json) is the same one, so the peer + owns it with the deselected runtime's receipt instead of reading it as + foreign while that runtime's cleanup removes it. + """ + for runtime in sorted(set(managed_target_servers) & set(selected)): + dropped = managed_target_servers[runtime] - selected[runtime] + for peer in sorted(shared_destination_peers(runtime, user_scope=user_scope)): + if peer not in selected: + continue + owned = managed_target_servers.setdefault(peer, set()) + for name in sorted((dropped & selected[peer]) - owned): + owned.add(name) + receipt = (native_hashes or {}).get(runtime, {}).get(name) + if native_hashes is not None and receipt is not None: + native_hashes.setdefault(peer, {}).setdefault(name, receipt) + + def names_owned_by_active_peers( runtime: str, names: set[str], diff --git a/src/apm_cli/integration/mcp_integrator_install.py b/src/apm_cli/integration/mcp_integrator_install.py index 76b738715e..19852083b3 100644 --- a/src/apm_cli/integration/mcp_integrator_install.py +++ b/src/apm_cli/integration/mcp_integrator_install.py @@ -1927,11 +1927,17 @@ def run_mcp_install( # noqa: PLR0913 active_runtimes=active_targets, user_scope=user_scope, ) + from apm_cli.install.mcp.ownership import transfer_deselected_shared_claims + + selected = {target: mcp_servers_for_runtime(mcp_deps, target) for target in active_targets} + transfer_deselected_shared_claims( + managed_target_servers, native_hashes, selected=selected, user_scope=user_scope + ) for target in list(managed_target_servers): if target not in active_targets: del managed_target_servers[target] else: - managed_target_servers[target] &= mcp_servers_for_runtime(mcp_deps, target) + managed_target_servers[target] &= selected[target] for target in target_runtimes: managed_target_servers.setdefault(target, set()) diff --git a/tests/integration/test_architecture_owner_rule_mutations.py b/tests/integration/test_architecture_owner_rule_mutations.py index 7bfe63d866..216a832551 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -4141,10 +4141,16 @@ def test_lock_target_canonicalisation_guard_rejects_mutations( ), pytest.param( "src/apm_cli/integration/mcp_integrator_install.py", - "managed_target_servers[target] &= mcp_servers_for_runtime(mcp_deps, target)", + "managed_target_servers[target] &= selected[target]", "managed_target_servers[target] &= set(managed_target_servers[target])", id="claims-ignore-dependency-targets", ), + pytest.param( + "src/apm_cli/integration/mcp_integrator_install.py", + " transfer_deselected_shared_claims(\n", + " (lambda *args, **kwargs: None)(\n", + id="retarget-drops-shared-file-claim", + ), pytest.param( "src/apm_cli/install/mcp/integration.py", "admitted = mcp_servers_for_runtime(mcp_deps, owned_target)", diff --git a/tests/integration/test_mcp_dependency_targets_lifecycle.py b/tests/integration/test_mcp_dependency_targets_lifecycle.py index 680aa5802d..8d566d7af5 100644 --- a/tests/integration/test_mcp_dependency_targets_lifecycle.py +++ b/tests/integration/test_mcp_dependency_targets_lifecycle.py @@ -131,3 +131,37 @@ def claude_servers() -> dict: write_global([_scoped("srv-b", "codex"), stdio_server("srv-c", "c")]) chain.ok("install", "-g", "--no-policy", "--only", "mcp", "--target", "codex") assert claude_servers() == {} + + +def test_project_retained_claims_survive_exclude_retarget_and_pending_updates( + tmp_path: Path, apm_binary_path: Path +) -> None: + """Exclusion keeps claims, skipped targets get later updates, shared-file retarget keeps.""" + chain = Chain(tmp_path / "retained", apm_binary_path, dirs=(".claude", ".cursor")) + manifest_targets = ["claude", "cursor", "copilot"] + chain.write_manifest( + [_scoped("srv-cursor", "cursor"), _scoped("srv-shared", "claude")], + targets=manifest_targets, + ) + chain.ok("install", "--no-policy") + assert chain.servers("cursor")["srv-cursor"]["args"] == ["srv-cursor"] + + # --exclude skips a target the manifest still lists: its claims stay. + chain.ok("install", "--no-policy", "--exclude", "cursor") + assert "srv-cursor" in chain.servers("cursor") + assert chain.lock()["mcp_target_servers"]["cursor"] == ["srv-cursor"] + + # A declaration change made while cursor is skipped lands on its next install. + updated = {**_scoped("srv-cursor", "cursor"), "args": ["srv-cursor", "--v2"]} + chain.write_manifest([updated, _scoped("srv-shared", "claude")], targets=manifest_targets) + chain.ok("install", "--no-policy", "--exclude", "cursor") + assert chain.servers("cursor")["srv-cursor"]["args"] == ["srv-cursor"] + chain.ok("install", "--no-policy") + assert chain.servers("cursor")["srv-cursor"]["args"] == ["srv-cursor", "--v2"] + + # Retargeting between claude and copilot keeps the one shared .mcp.json entry. + chain.write_manifest([updated, _scoped("srv-shared", "copilot")], targets=manifest_targets) + chain.ok("install", "--no-policy") + assert "srv-shared" in chain.servers("copilot") + assert chain.lock()["mcp_target_servers"].get("claude", []) == [] + assert chain.lock()["mcp_target_servers"]["copilot"] == ["srv-shared"]