Skip to content
Closed
2 changes: 1 addition & 1 deletion .apm/architecture/owners/hooks-integrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
},
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions docs/src/content/docs/consumer/install-mcp-servers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
3 changes: 2 additions & 1 deletion docs/src/content/docs/reference/manifest-schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>` | 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.
Expand Down
10 changes: 10 additions & 0 deletions packages/apm-guide/.apm/skills/apm-usage/dependencies.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
13 changes: 11 additions & 2 deletions src/apm_cli/core/target_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -873,13 +873,22 @@ 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."""

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."""
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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")
Expand Down
54 changes: 49 additions & 5 deletions src/apm_cli/install/mcp/integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand All @@ -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)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Comment thread
danielmeppiel marked this conversation as resolved.
Resolved
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(
Expand Down
31 changes: 31 additions & 0 deletions src/apm_cli/install/mcp/ownership.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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]],
Expand Down
10 changes: 8 additions & 2 deletions src/apm_cli/install/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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()
]
Expand Down
9 changes: 8 additions & 1 deletion src/apm_cli/install/service_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down
Loading