Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- Self-defined MCP servers whose names contain a slash, such as `com.example/server`, now keep their declared name as the config key in every target instead of colliding on the final segment; registry, `@scope/name` and plain names are unchanged. An older truncated entry is replaced only when APM's ownership records prove it wrote it; otherwise it is left in place. -- by @bodapatisaikrishna (#3493)
- Registry-only mode (`PROXY_REGISTRY_ONLY`) no longer contacts the upstream host to enumerate refs or versions: semver ranges and `apm view <pkg> versions` fail with an actionable error, `apm outdated` reports git dependencies as unknown and names the remedy, ref-to-SHA lookup skips the GitHub commits API, and exact tags and locked resolutions keep installing through the proxy. -- by @pearlatvg (#3471)
- `apm install` and `apm compile` create a new `apm.lock.yaml` and compiled outputs such as `AGENTS.md` with umask-derived permissions (`-rw-r--r--` under umask 022) instead of owner-only `0600`; existing files keep their mode and secret-bearing configs stay `0600`. (#3547)
- `apm marketplace check` accepts a `ref` that is a full 40-character commit SHA when the remote serves that commit, matching `apm pack`, instead of failing with `Ref '<sha>' not found`; unreachable commits and abbreviated SHAs fail with an actionable message, and tag and branch refs are unchanged. (#3543)
Expand Down
10 changes: 10 additions & 0 deletions docs/src/content/docs/consumer/install-mcp-servers.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,16 @@ For every selected target that passes its scope and adapter prerequisites,
`apm install` writes a runtime-specific MCP config file. The schemas differ;
the `apm.yml` source of truth does not.

Self-defined servers (`registry: false`) are written under their exact
declared `name`, including names with a slash such as `com.example/server`.
Registry servers such as `io.github.github/github-mcp-server` keep the short
`github-mcp-server` key in every target except VS Code. If an older APM release
wrote a self-defined server under its final segment, `apm install` removes that
entry only when APM's recorded ownership proves it wrote it (and, for Claude
Code and Codex, that it is unchanged); otherwise it leaves the entry and prints
its name and config path so you can remove it yourself. OpenCode entries are
not checked.

Registry-declared environment variables honor the registry's
`required` flag. Servers with optional auth install without token
prompts until you choose to configure one. See the
Expand Down
18 changes: 14 additions & 4 deletions src/apm_cli/adapters/client/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1539,23 +1539,33 @@ def _fetch_server_info(self, server_url: str, server_info_cache: dict | None) ->
return server_info

@staticmethod
def _determine_config_key(server_url: str, server_name: str | None) -> str:
def _determine_config_key(
server_url: str,
server_name: str | None,
server_info: dict | None = None,
) -> str:
"""Return the configuration key to use for *server_url*/*server_name*.

The caller-supplied *server_name* takes precedence. If it is absent,
preserve npm-style scoped names such as ``@scope/name`` (one slash by
npm convention) while keeping the historical ``owner/repo -> repo``
fallback for registry paths.
preserve self-defined names and npm-style scoped names such as
``@scope/name`` (one slash by npm convention) while keeping the historical
``owner/repo -> repo`` fallback for registry paths.

Args:
server_url: Registry reference used as fallback source.
server_name: Explicit caller-supplied name, if any.
server_info: Optional resolved or synthetic server info dict.

Returns:
Non-empty configuration key string.
"""
if server_name:
return server_name
# ``is_self_defined`` / ``_raw_stdio`` are APM-synthetic markers. Return
# the caller's reference, never ``server_info["name"]``, so a registry
# response carrying these keys cannot choose an arbitrary config key.
if server_info and (server_info.get("is_self_defined") or "_raw_stdio" in server_info):
return server_url
if server_url.startswith("@") and server_url.count("/") == 1:
return server_url
if "/" in server_url:
Expand Down
2 changes: 1 addition & 1 deletion src/apm_cli/adapters/client/claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ def configure_mcp_server(
_rich_error(f"MCP server '{server_url}' not found in registry")
return False

config_key = self._determine_config_key(server_url, server_name)
config_key = self._determine_config_key(server_url, server_name, server_info)

server_config = self._format_server_config(server_info, env_overrides, runtime_vars)
from apm_cli.install.mcp.ownership import mcp_native_hash
Expand Down
2 changes: 1 addition & 1 deletion src/apm_cli/adapters/client/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ def configure_mcp_server(
if server_info is None:
return False

config_key = self._determine_config_key(server_url, server_name)
config_key = self._determine_config_key(server_url, server_name, server_info)

# Generate server configuration with environment variable resolution
server_config = self._format_server_config(server_info, env_overrides, runtime_vars)
Expand Down
2 changes: 1 addition & 1 deletion src/apm_cli/adapters/client/copilot.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def configure_mcp_server(
# Generate server configuration with environment and runtime variable resolution
server_config = self._format_server_config(server_info, env_overrides, runtime_vars)

config_key = self._determine_config_key(server_url, server_name)
config_key = self._determine_config_key(server_url, server_name, server_info)

# Update configuration using the chosen key
self.update_config({config_key: server_config})
Expand Down
2 changes: 1 addition & 1 deletion src/apm_cli/adapters/client/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ def configure_mcp_server(
if server_info is None:
return False

config_key = self._determine_config_key(server_url, server_name)
config_key = self._determine_config_key(server_url, server_name, server_info)

server_config = self._format_server_config(server_info, env_overrides, runtime_vars)
if self.update_config({config_key: server_config}) is False:
Expand Down
7 changes: 1 addition & 6 deletions src/apm_cli/adapters/client/gemini.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,12 +297,7 @@ def configure_mcp_server(
_rich_error(f"MCP server '{server_url}' not found in registry", symbol="error")
return False

if server_name:
config_key = server_name
elif "/" in server_url:
config_key = server_url.split("/")[-1]
else:
config_key = server_url
config_key = self._determine_config_key(server_url, server_name, server_info)

server_config = self._format_server_config(server_info, env_overrides, runtime_vars)
self.update_config({config_key: server_config})
Expand Down
2 changes: 1 addition & 1 deletion src/apm_cli/adapters/client/hermes.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def configure_mcp_server(
if server_info is None:
return False

config_key = self._determine_config_key(server_url, server_name)
config_key = self._determine_config_key(server_url, server_name, server_info)
server_config = self._format_server_config(server_info, env_overrides, runtime_vars)
ok = self.update_config({config_key: server_config}, enabled=enabled)
if not ok:
Expand Down
3 changes: 3 additions & 0 deletions src/apm_cli/adapters/client/kiro.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,13 +208,16 @@ def configure_mcp_server(
)
return True

# Fallback key for the error message when the registry lookup raises.
config_key = self._determine_config_key(server_url, server_name)

try:
server_info = self._fetch_server_info(server_url, server_info_cache)
if server_info is None:
return False

config_key = self._determine_config_key(server_url, server_name, server_info)

self._last_env_placeholder_keys = set()
self._last_legacy_angle_vars = set()

Expand Down
2 changes: 1 addition & 1 deletion src/apm_cli/adapters/client/opencode.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def configure_mcp_server(
if server_info is None:
return False

config_key = self._determine_config_key(server_url, server_name)
config_key = self._determine_config_key(server_url, server_name, server_info)

server_config = self._format_server_config(server_info, env_overrides, runtime_vars)
written = self.update_config(
Expand Down
22 changes: 20 additions & 2 deletions src/apm_cli/install/mcp/ownership.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,20 @@ def mcp_native_hash(native: dict) -> str:
return "sha256:" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()


def _native_config_key(
client: Any,
name: str,
*,
requested_info: dict | None = None,
stored_config: dict | None = None,
) -> str:
"""Return the native key for *name*; self-defined servers keep their declared name."""
info = requested_info
if info is None and isinstance(stored_config, dict) and stored_config.get("registry") is False:
info = {"name": name, "is_self_defined": True}
return client._determine_config_key(name, None, info)


def compare_native_mcp_connection(
client: Any,
name: str,
Expand All @@ -53,7 +67,9 @@ def compare_native_mcp_connection(
if existing_configs is None
else existing_configs
)
key = client._determine_config_key(name, None)
key = _native_config_key(
client, name, requested_info=requested_info, stored_config=stored_config
)
if key not in existing:
return NativeMcpConnectionState.ABSENT
native = existing[key]
Expand Down Expand Up @@ -144,7 +160,9 @@ def require_removable_mcp_connections(
"only the entries you intend to retire), then retry the same command. "
"--force does not take ownership of user connections."
)
return {client._determine_config_key(name, None) for name in names}
return {
_native_config_key(client, name, stored_config=stored_configs.get(name)) for name in names
}


def retain_deferred_mcp_claims(
Expand Down
5 changes: 4 additions & 1 deletion src/apm_cli/integration/mcp_integrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,10 @@ def _build_self_defined_info(dep) -> dict:
Mimics the structure returned by the MCP registry so that existing
adapter code can consume self-defined deps without changes.
"""
info: dict = {"name": dep.name}
info: dict = {
"name": dep.name,
"is_self_defined": True,
}

# For stdio self-defined deps, store raw command/args so adapters
# can bypass registry-specific formatting (npm, docker, etc.).
Expand Down
103 changes: 103 additions & 0 deletions src/apm_cli/integration/mcp_integrator_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,86 @@ def _record_managed_server(
written_connections.add((runtime, server_name))


# Runtimes that always keyed self-defined servers by their full declared name,
# so a short-name entry there can never be a truncated write by older APM.
_DECLARED_KEY_RUNTIMES = frozenset({"vscode"})


def _reconcile_legacy_truncated_key(
dep_name: str,
runtimes: list[str],
*,
previously_owned: dict[str, set[str]],
previous_native_hashes: dict[str, dict[str, str]],
stored_config: dict | None,
claimed_keys: builtins.set,
project_root,
user_scope: bool,
logger,
fail_on_write_error: bool = False,
) -> None:
"""Replace or flag the pre-fix truncated config key of a self-defined server.

Older releases wrote ``com.example/srv`` under its final segment (``srv``).
Now that the declared name is the key, the short entry is removed only when
the ownership ledger proves APM wrote *dep_name* to that runtime (and, on
runtimes with native baselines, that its content is unchanged); otherwise
it is left in place and named (never its contents) so the user can decide.
"""
from apm_cli.adapters.client.base import MCPClientAdapter
from apm_cli.core.conflict_detector import MCPConflictDetector
from apm_cli.core.scope import InstallScope
from apm_cli.factory import ClientFactory
from apm_cli.integration.mcp_integrator import MCPIntegrator

legacy_key = MCPClientAdapter._determine_config_key(dep_name, None)
if legacy_key == dep_name or legacy_key in claimed_keys:
return
scope = InstallScope.USER if user_scope else InstallScope.PROJECT
for rt in runtimes:
if rt in _DECLARED_KEY_RUNTIMES:
continue
try:
client = ClientFactory.create_client(
rt, project_root=project_root, user_scope=user_scope
)
existing = MCPConflictDetector(client).get_existing_server_configs()
except Exception as exc:
logger.verbose_detail(f"Skipped legacy MCP entry check for {rt}: {exc}")
continue
if legacy_key not in existing:
continue
config_path = client.get_config_path()
if dep_name in previously_owned.get(rt, builtins.set()):
legacy_hash = previous_native_hashes.get(rt, {}).get(dep_name)
try:
MCPIntegrator.remove_stale(
{legacy_key},
runtime=rt,
project_root=project_root,
user_scope=user_scope,
logger=logger,
scope=scope,
fail_on_write_error=fail_on_write_error,
stored_configs={legacy_key: stored_config} if stored_config else {},
native_hashes={rt: {legacy_key: legacy_hash}} if legacy_hash else None,
)
except RequiredIntegrationError:
logger.warning(
f"Left existing MCP server '{legacy_key}' in {config_path}: it changed "
f"since APM wrote it for '{dep_name}'. Remove it manually if it is "
f"an outdated copy of '{dep_name}'."
)
continue
logger.progress(f"Renamed MCP server '{legacy_key}' to '{dep_name}' in {config_path}")
else:
logger.warning(
f"Left existing MCP server '{legacy_key}' in {config_path}: APM has no "
f"record of writing it for '{dep_name}'. Remove it manually if it is "
f"an outdated copy of '{dep_name}'."
)


def _raise_strict_config_failures(
failed_installations: list[str],
*,
Expand Down Expand Up @@ -1061,12 +1141,14 @@ def _install_self_defined_deps(
fail_on_write_error: bool = False,
native_hashes: dict[str, dict[str, str]] | None = None,
written_connections: set[tuple[str, str]] | None = None,
registry_dep_names: list[str] | None = None,
) -> int:
"""Install self-defined (``registry: false``) MCP deps for all target runtimes.

Mutates ``servers_to_update`` and ``successful_updates`` in-place.
Returns the number of servers newly configured or updated.
"""
from apm_cli.adapters.client.base import MCPClientAdapter
from apm_cli.install.mcp.ownership import (
NativeMcpConnectionState,
compare_native_mcp_connection,
Expand All @@ -1079,6 +1161,13 @@ def _install_self_defined_deps(
if written_connections is None:
written_connections = set()
self_defined_names = [dep.name for dep in self_defined_deps]
previously_owned = {
rt: builtins.set(names) for rt, names in (managed_target_servers or {}).items()
}
previous_native_hashes = {rt: dict(hashes) for rt, hashes in (native_hashes or {}).items()}
claimed_keys = builtins.set(self_defined_names) | {
MCPClientAdapter._determine_config_key(name, None) for name in registry_dep_names or ()
}
self_defined_to_install = MCPIntegrator._check_self_defined_servers_needing_installation(
self_defined_names,
target_runtimes,
Expand Down Expand Up @@ -1221,6 +1310,19 @@ def _install_self_defined_deps(
else:
failed_runtimes.append(rt)

_reconcile_legacy_truncated_key(
dep.name,
successful_runtimes,
previously_owned=previously_owned,
previous_native_hashes=previous_native_hashes,
stored_config=stored_mcp_configs.get(dep.name),
claimed_keys=claimed_keys,
project_root=project_root,
user_scope=user_scope,
logger=logger,
fail_on_write_error=fail_on_write_error,
)

if successful_runtimes:
if console:
label = "updated" if is_update else "configured"
Expand Down Expand Up @@ -1570,6 +1672,7 @@ def run_mcp_install( # noqa: PLR0913
fail_on_write_error=fail_on_write_error,
native_hashes=native_hashes,
written_connections=written_connections,
registry_dep_names=registry_dep_names,
)
except MCPNativeConflictError as exc:
native_conflicts.append(str(exc))
Expand Down
18 changes: 18 additions & 0 deletions tests/integration/test_wave2_adapters_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,15 @@ def test_determine_config_key_plain_name(self) -> None:
key = MCPClientAdapter._determine_config_key("my-server", None)
assert key == "my-server"

def test_determine_config_key_self_defined(self) -> None:
"""Self-defined servers with slashes keep their declared name."""
key = MCPClientAdapter._determine_config_key(
"com.azure.dev/mcp-remote",
None,
{"name": "com.azure.dev/mcp-remote", "is_self_defined": True},
)
assert key == "com.azure.dev/mcp-remote"

def test_infer_registry_name_npm_scoped(self) -> None:
"""Scoped npm package name infers npm."""
pkg = {"name": "@azure/mcp"}
Expand Down Expand Up @@ -2283,6 +2292,15 @@ def test_format_server_config_unsupported_transport_raises(self, tmp_path: Path)
with pytest.raises(ValueError, match="Unsupported remote transport"):
adapter._format_server_config(server_info)

def test_configure_mcp_server_fetch_raises_returns_false(self, tmp_path: Path) -> None:
"""configure_mcp_server returns False without UnboundLocalError when fetch raises."""
kiro_dir = tmp_path / ".kiro"
kiro_dir.mkdir()
adapter = KiroClientAdapter(project_root=tmp_path)
with patch.object(adapter, "_fetch_server_info", side_effect=RuntimeError("network error")):
result = adapter.configure_mcp_server("test/server")
assert result is False


# ===========================================================================
# 22. More adapters/client/gemini.py -- configure_mcp_server
Expand Down
Loading