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 025552fcf7..f1ced98d51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- `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) - Global `apm audit --ci` passes after `apm install -g` when `APM_HOME` is outside `HOME` or a local native Agent Plugin is installed. (closes #3901, #3946) - Kiro agents using current tool IDs or `@server` selectors now deploy; an unsupported tool skips only that agent with a warning (exit 0) instead of failing the install. (closes #2671, #3947) - `apm install` removes hooks a package deployed earlier once `apm deny` or a removed approval gates them, and names a denied package as denied. (#3944) 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 f8b21a83c2..9a6dcbd7e9 100644 --- a/docs/src/content/docs/reference/manifest-schema.md +++ b/docs/src/content/docs/reference/manifest-schema.md @@ -778,12 +778,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. 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. 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 1d8db2a631..69fa0c5d4f 100644 --- a/packages/apm-guide/.apm/skills/apm-usage/dependencies.md +++ b/packages/apm-guide/.apm/skills/apm-usage/dependencies.md @@ -715,6 +715,16 @@ dependencies: env: API_KEY: ${{ secrets.KEY }} + # 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 + 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 92c60013a9..89f5a5d424 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,78 @@ 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)", + "selected = {target: mcp_servers_for_runtime(mcp_deps, target) for target in", + "managed_target_servers[target] &= selected[target]", + "transfer_deselected_shared_claims(", + ), + ), + ( + _MCP_INTEGRATION, + "run_mcp_integration", + ( + "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)", "deselected_mcp_claims("), + ), + ( + "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/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 0cc439aa8e..ca317106d4 100644 --- a/src/apm_cli/install/mcp/integration.py +++ b/src/apm_cli/install/mcp/integration.py @@ -133,6 +133,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, ) @@ -143,6 +144,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) @@ -205,6 +207,13 @@ 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 |= 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. @@ -585,12 +594,47 @@ 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 - - for removed_target in sorted( - builtins.set(old_mcp_target_servers) - builtins.set(managed_target_servers) + 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; + # 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. + admitted = mcp_servers_for_runtime(mcp_deps, owned_target) + 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( + mcp_deps, owned_target, named_only=True + ) + 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, ): - retired_names = builtins.set(old_mcp_target_servers[removed_target]) + 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. retired_names -= names_owned_by_active_peers( diff --git a/src/apm_cli/install/mcp/ownership.py b/src/apm_cli/install/mcp/ownership.py index 2cd5982c57..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], @@ -727,6 +753,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/install/service.py b/src/apm_cli/install/service.py index f06075e75a..d660b8060d 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..19852083b3 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,17 @@ 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") - } + 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].intersection_update(current_names) + managed_target_servers[target] &= selected[target] for target in target_runtimes: managed_target_servers.setdefault(target, set()) @@ -1944,6 +1973,19 @@ def run_mcp_install( # noqa: PLR0913 symbol="check", ) + 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: + 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"{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 configured_count = 0 written_connections: set[tuple[str, str]] = set() @@ -1958,14 +2000,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 id(dep) not in scoped_out: + 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 +2034,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 +2058,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 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: 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 b5e3a91079..6093f42c38 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -4140,3 +4140,72 @@ 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] &= 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)", + "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", + ), + 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( + 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..8d566d7af5 --- /dev/null +++ b/tests/integration/test_mcp_dependency_targets_lifecycle.py @@ -0,0 +1,167 @@ +"""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 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 = [ + 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") + + # 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")], + 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 +) -> 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"), stdio_server("srv-c", "c")]) + chain.ok("install", "-g", "--no-policy", "--only", "mcp", "--target", "claude") + 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"] + + # 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"} + + 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", "srv-c"} + assert not re.search(r"^targets\s*=", codex_text, re.M) + 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"), 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"] 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",)), + ] diff --git a/tests/unit/test_mcp_overlays.py b/tests/unit/test_mcp_overlays.py index e2af06642a..7dc3a4ffe9 100644 --- a/tests/unit/test_mcp_overlays.py +++ b/tests/unit/test_mcp_overlays.py @@ -945,3 +945,26 @@ 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 {}) + + 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"]})