diff --git a/CHANGELOG.md b/CHANGELOG.md index 37f7d0bd..26e5bd57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### Fixed +- `cloudsmith mcp start` now exposes only read-only tools by default. Tools that change data or return credentials need `--allow-destructive-tools` (`-D`). A tool changes data when it uses POST, PUT, PATCH or DELETE, or when its name contains `delete`, `destroy` or `remove`. `--all-tools` (`-a`) enables every tool group and ignores `mcp_allowed_tools` and `mcp_allowed_tool_groups`. It no longer enables these tools without `-D`. When your allowlist matches tools that need `-D`, `mcp start`, `mcp list_tools` and `mcp list_groups` show a warning. `mcp configure` now accepts `-a` and `-D` and keeps them in the client configuration. Tools that change data now have `destructiveHint` set to `true`. (#620) + - `repos create`/`update`, `upstream create`/`update` and `policy deny|license|vulnerability create`/`update` now report a usage error when the config file isn't valid JSON or doesn't hold a JSON object, for example a file with a trailing comma. Previously the command crashed with a `JSONDecodeError` or `AttributeError` traceback. + - Fixed `cloudsmith download` choosing a package that can't be downloaded. The command also found packages that failed to sync or haven't finished, such as a failed duplicate upload of the same version. With `--yes`, it then chose the failed package, because it was uploaded last, and the download failed with HTTP 404. The command now searches only packages that have finished syncing. ## [1.31.3] - 2026-11-17 diff --git a/cloudsmith_cli/cli/commands/mcp.py b/cloudsmith_cli/cli/commands/mcp.py index 8b16375a..710d91a3 100644 --- a/cloudsmith_cli/cli/commands/mcp.py +++ b/cloudsmith_cli/cli/commands/mcp.py @@ -61,7 +61,13 @@ def start( with handle_api_exceptions( ctx, opts=opts, context_msg=SPEC_LOAD_ERROR_MESSAGE, err=True ): - mcp_server.run() + mcp_server.run( + on_tools_loaded=lambda: warn_hidden_tools( + mcp_server, + "run `cloudsmith mcp configure --allow-destructive-tools`, " + "then restart the MCP client", + ) + ) @mcp_.command(name="list_tools") @@ -88,6 +94,10 @@ def list_tools( ): tools = mcp_server.list_tools() + warn_hidden_tools( + mcp_server, "run `cloudsmith mcp list_tools --allow-destructive-tools`" + ) + if not use_stderr: click.secho("OK", fg="green", err=use_stderr) @@ -125,6 +135,10 @@ def list_groups( ): groups = mcp_server.list_groups() + warn_hidden_tools( + mcp_server, "run `cloudsmith mcp list_groups --allow-destructive-tools`" + ) + if not use_stderr: click.secho("OK", fg="green", err=use_stderr) @@ -136,6 +150,21 @@ def list_groups( print_groups(groups) +def warn_hidden_tools(mcp_server: server.DynamicMCPServer, fix: str) -> None: + """Warn on stderr about allowlisted tools that need --allow-destructive-tools.""" + hidden = mcp_server.hidden_allowlisted_tools + if not hidden: + return + count = len(hidden) + click.secho( + f"Warning: {count} {'tools' if count != 1 else 'tool'} in your MCP allowlist " + f"{'are' if count != 1 else 'is'} hidden without --allow-destructive-tools: " + f"{', '.join(hidden)}\nFix: {fix}", + fg="yellow", + err=True, + ) + + def print_tools(tool_list: dict[str, OpenAPITool]): """Print tools as a table or output in another format.""" @@ -214,10 +243,17 @@ def print_groups(group_list: dict[str, list[str]]): default=True, help="Configure globally (default) or in current project directory (local)", ) +@decorators.MCP_ALL_TOOLS_OPTION +@decorators.MCP_ALLOW_DESTRUCTIVE_TOOLS_OPTION @decorators.initialise_api @click.pass_context def configure( # pylint: disable=unused-argument - ctx: click.Context, opts: Options, client: str | None, is_global: bool + ctx: click.Context, + opts: Options, + client: str | None, + is_global: bool, + all_tools: bool, + allow_destructive_tools: bool, ) -> None: """ Configure the Cloudsmith MCP server for supported clients. @@ -249,7 +285,7 @@ def configure( # pylint: disable=unused-argument profile = ctx.meta.get("profile") # Determine the best command to run the MCP server - server_config = _get_server_config(profile) + server_config = _get_server_config(profile, all_tools, allow_destructive_tools) clients_to_configure = [] if client: @@ -318,7 +354,9 @@ def configure( # pylint: disable=unused-argument click.echo(click.style("\nNo clients were configured successfully", fg="red")) -def _get_server_config(profile=None): +def _get_server_config( + profile=None, all_tools: bool = False, allow_destructive_tools: bool = False +): """Determine the first available command configuration to run the MCP server.""" is_frozen = getattr(sys, "frozen", False) in_venv = hasattr(sys, "real_prefix") or ( @@ -330,24 +368,30 @@ def _get_server_config(profile=None): if profile: base_args.extend(["-P", profile]) + start_args = ["mcp", "start"] + if all_tools: + start_args.append("--all-tools") + if allow_destructive_tools: + start_args.append("--allow-destructive-tools") + if is_frozen: - return {"command": sys.executable, "args": base_args + ["mcp", "start"]} + return {"command": sys.executable, "args": base_args + start_args} # In a venv, always use python -m to ensure we use the venv's packages if in_venv: return { "command": sys.executable, - "args": ["-m", "cloudsmith_cli"] + base_args + ["mcp", "start"], + "args": ["-m", "cloudsmith_cli"] + base_args + start_args, } # Otherwise, try to find cloudsmith in PATH, fall back to python -m cloudsmith_cmd = shutil.which("cloudsmith") if cloudsmith_cmd: - return {"command": cloudsmith_cmd, "args": base_args + ["mcp", "start"]} + return {"command": cloudsmith_cmd, "args": base_args + start_args} return { "command": sys.executable, - "args": ["-m", "cloudsmith_cli"] + base_args + ["mcp", "start"], + "args": ["-m", "cloudsmith_cli"] + base_args + start_args, } diff --git a/cloudsmith_cli/cli/decorators.py b/cloudsmith_cli/cli/decorators.py index b5e41eee..4efe4a44 100644 --- a/cloudsmith_cli/cli/decorators.py +++ b/cloudsmith_cli/cli/decorators.py @@ -930,21 +930,33 @@ def call_print_rate_limit_info_with_opts(rate_info): return resolve_credentials(wrapper) +MCP_ALL_TOOLS_OPTION = click.option( + "-a", + "--all-tools", + default=False, + is_flag=True, + help=( + "Enable every tool group and ignore mcp_allowed_tools and " + "mcp_allowed_tool_groups. Tools that change data or return credentials " + "also need --allow-destructive-tools" + ), +) + +MCP_ALLOW_DESTRUCTIVE_TOOLS_OPTION = click.option( + "-D", + "--allow-destructive-tools", + default=False, + is_flag=True, + help=( + "Allow tools that change data or return credentials in the enabled tool " + "groups. Add --all-tools to enable every tool group" + ), +) + + def initialise_mcp(f): - @click.option( - "-a", - "--all-tools", - default=False, - is_flag=True, - help="Show all tools", - ) - @click.option( - "-D", - "--allow-destructive-tools", - default=False, - is_flag=True, - help="Allow destructive tools to be used", - ) + @MCP_ALL_TOOLS_OPTION + @MCP_ALLOW_DESTRUCTIVE_TOOLS_OPTION @click.pass_context @functools.wraps(f) def wrapper(ctx, *args, **kwargs): diff --git a/cloudsmith_cli/cli/tests/commands/test_mcp.py b/cloudsmith_cli/cli/tests/commands/test_mcp.py index 14363a83..0e55d272 100644 --- a/cloudsmith_cli/cli/tests/commands/test_mcp.py +++ b/cloudsmith_cli/cli/tests/commands/test_mcp.py @@ -1,3 +1,4 @@ +import asyncio import json import os import stat @@ -25,7 +26,7 @@ ) from ....core.api.exceptions import ApiException from ....core.mcp.data import OpenAPITool -from ....core.mcp.server import DynamicMCPServer +from ....core.mcp.server import CustomFastMCP, DynamicMCPServer from ....core.version import get_version as get_cli_version @@ -42,8 +43,6 @@ def test_list_tools_command_basic(self, runner): parameters={"type": "object", "properties": {}, "required": []}, base_url="https://api.cloudsmith.io", query_filter=None, - is_destructive=False, - is_read_only=True, ), "packages_list": OpenAPITool( name="packages_list", @@ -53,8 +52,6 @@ def test_list_tools_command_basic(self, runner): parameters={"type": "object", "properties": {}, "required": []}, base_url="https://api.cloudsmith.io", query_filter=None, - is_destructive=False, - is_read_only=True, ), } @@ -69,6 +66,7 @@ def test_list_tools_command_basic(self, runner): assert "packages_list" in result.output assert "List repositories" in result.output assert "List packages" in result.output + assert "Warning" not in result.stderr list_tools_mock.assert_called_once() def test_list_tools_command_with_filtering(self, runner): @@ -83,8 +81,6 @@ def test_list_tools_command_with_filtering(self, runner): parameters={"type": "object", "properties": {}, "required": []}, base_url="https://api.cloudsmith.io", query_filter=None, - is_destructive=False, - is_read_only=True, ), } @@ -111,8 +107,6 @@ def test_list_tools_command_json_output(self, runner): parameters={"type": "object", "properties": {}, "required": []}, base_url="https://api.cloudsmith.io", query_filter=None, - is_destructive=False, - is_read_only=True, ), } @@ -313,6 +307,104 @@ def refuse(request): assert exc_info.value.detail == "ConnectError: Connection refused" +class TestMCPHiddenToolsWarning: + @pytest.mark.parametrize( + ("command", "fix"), + [ + ( + start, + "Fix: run `cloudsmith mcp configure --allow-destructive-tools`, " + "then restart the MCP client", + ), + ( + list_tools, + "Fix: run `cloudsmith mcp list_tools --allow-destructive-tools`", + ), + ( + list_groups, + "Fix: run `cloudsmith mcp list_groups --allow-destructive-tools`", + ), + ], + ) + def test_warns_on_stderr_about_hidden_allowlisted_tools(self, runner, command, fix): + def hide_tools(server): + server.hidden_allowlisted_tools.extend(["repos_create", "user_tokens_list"]) + + with ( + patch.object( + DynamicMCPServer, + "load_openapi_spec", + autospec=True, + side_effect=hide_tools, + ), + patch.object(CustomFastMCP, "run"), + ): + result = runner.invoke(command, catch_exceptions=False) + + warning = ( + "Warning: 2 tools in your MCP allowlist are hidden without " + "--allow-destructive-tools: repos_create, user_tokens_list" + ) + assert f"{warning}\n{fix}\n" in result.stderr + assert "allowlist" not in result.stdout + + +MUTATING_SPEC = { + "paths": { + "/repos/": { + "get": {"operationId": "repos_list"}, + "post": {"operationId": "repos_create"}, + }, + "/user/self/": {"get": {"operationId": "user_self"}}, + "/repos/{owner}/{identifier}/privileges": { + "put": {"operationId": "repos_privileges_update"}, + "patch": {"operationId": "repos_privileges_partial_update"}, + }, + "/packages/{owner}/{repo}/{identifier}/": { + "delete": {"operationId": "packages_delete"}, + }, + "/orgs/{org}/members/{member}/remove/": { + "get": {"operationId": "orgs_members_remove"}, + }, + "/webhooks/{owner}/{repo}/": { + "get": {"operationId": "webhooks_list"}, + "post": {"operationId": "webhooks_create"}, + }, + "/user/tokens/": {"get": {"operationId": "user_tokens_list"}}, + } +} +READ_ONLY_TOOLS = {"repos_list", "user_self"} +DISABLED_GROUP_TOOLS = {"webhooks_list", "webhooks_create", "user_tokens_list"} +WRITE_TOOLS = { + "repos_create", + "repos_privileges_update", + "repos_privileges_partial_update", + "packages_delete", + "orgs_members_remove", +} + + +def _server_from_spec(spec: dict, **server_kwargs) -> DynamicMCPServer: + api_config = cloudsmith_api.Configuration() + api_config.host = "https://api.cloudsmith.io" + api_config.headers = {} + server = DynamicMCPServer(api_config=api_config, **server_kwargs) + + def handler(request: httpx2.Request) -> httpx2.Response: + is_v2 = "/v2/" in str(request.url) + return httpx2.Response(200, json={"paths": {}} if is_v2 else spec) + + with ( + patch("cloudsmith_cli.core.mcp.server.create_ssl_context", return_value=True), + patch( + "cloudsmith_cli.core.mcp.server.create_http_client", + return_value=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)), + ), + ): + asyncio.run(server.load_openapi_spec()) + return server + + class TestMCPServerDynamicToolGeneration: def test_server_generates_tools_from_openapi_spec(self): """Test that MCP server dynamically creates tools from OpenAPI spec.""" @@ -352,41 +444,16 @@ def test_server_generates_tools_from_openapi_spec(self): "operationId": "repos_read", "summary": "Get a specific repository", }, - "delete": { - "operationId": "repos_delete", - "summary": "Delete a repository", - }, }, } } - import cloudsmith_api - - # Create API config - api_config = cloudsmith_api.Configuration() - api_config.host = "https://api.cloudsmith.io" - api_config.api_key = {"X-Api-Key": "test-key"} - - # Create MCP server instance - server = DynamicMCPServer(api_config=api_config, force_all_tools=True) - - # Mock the spec loading directly - server.spec = mock_openapi_spec - - # Call the synchronous tool generation method - import asyncio - - asyncio.run( - server._generate_tools_from_spec( # pylint: disable=protected-access - "https://api.cloudsmith.io/v1" - ) - ) + server = _server_from_spec(mock_openapi_spec, force_all_tools=True) # Verify tools were created - assert len(server.tools) == 3 + assert len(server.tools) == 2 assert "repos_list" in server.tools assert "repos_read" in server.tools - assert "repos_delete" in server.tools # Verify tool details repos_list_tool = server.tools["repos_list"] @@ -394,13 +461,6 @@ def test_server_generates_tools_from_openapi_spec(self): assert repos_list_tool.description == "List all repositories" assert repos_list_tool.method == "GET" assert repos_list_tool.path == "/repos/" - assert repos_list_tool.is_read_only is True - assert repos_list_tool.is_destructive is False - - # Verify delete tool is marked as destructive - repos_delete_tool = server.tools["repos_delete"] - assert repos_delete_tool.is_destructive is True - assert repos_delete_tool.is_read_only is False def test_server_respects_tool_filtering(self): """Test that MCP server filters tools based on configuration.""" @@ -422,32 +482,53 @@ def test_server_respects_tool_filtering(self): } } - import cloudsmith_api - - api_config = cloudsmith_api.Configuration() - api_config.host = "https://api.cloudsmith.io" - api_config.api_key = {"X-Api-Key": "test-key"} - # Create server with filtering - only allow repos group - server = DynamicMCPServer(api_config=api_config, allowed_tool_groups=["repos"]) - - # Mock the spec loading directly - server.spec = mock_openapi_spec - - # Call the tool generation method - import asyncio - - asyncio.run( - server._generate_tools_from_spec( # pylint: disable=protected-access - "https://api.cloudsmith.io/v1" - ) - ) + server = _server_from_spec(mock_openapi_spec, allowed_tool_groups=["repos"]) # Verify only repos tools were created assert len(server.tools) == 1 assert "repos_list" in server.tools assert "packages_list" not in server.tools + @pytest.mark.parametrize( + ("server_kwargs", "expected_tools", "expected_hidden"), + [ + ({}, READ_ONLY_TOOLS, set()), + ( + {"allowed_tool_groups": ["repos"]}, + {"repos_list"}, + { + "repos_create", + "repos_privileges_update", + "repos_privileges_partial_update", + }, + ), + ({"allowed_tools": ["user_tokens_list"]}, set(), {"user_tokens_list"}), + ({"force_all_tools": True}, READ_ONLY_TOOLS | {"webhooks_list"}, set()), + ( + {"force_all_tools": True, "allow_destructive_tools": True}, + READ_ONLY_TOOLS | WRITE_TOOLS | DISABLED_GROUP_TOOLS, + set(), + ), + ], + ) + def test_tool_flags_select_listed_and_hidden_tools( + self, server_kwargs, expected_tools, expected_hidden + ): + server = _server_from_spec(MUTATING_SPEC, **server_kwargs) + + assert set(server.tools) == expected_tools + assert set(server.hidden_allowlisted_tools) == expected_hidden + + def test_destructive_opt_in_marks_write_tools_destructive(self): + server = _server_from_spec(MUTATING_SPEC, allow_destructive_tools=True) + + tools = asyncio.run(server.mcp.list_tools()) + destructive = {tool.name for tool in tools if tool.annotations.destructive_hint} + read_only = {tool.name for tool in tools if tool.annotations.read_only_hint} + assert destructive == WRITE_TOOLS + assert read_only == READ_ONLY_TOOLS + def test_server_reports_cli_version(self): import cloudsmith_api @@ -462,11 +543,6 @@ def test_server_reports_cli_version(self): class TestMCPServerLoadOpenAPISpec: def test_tool_urls_include_api_version(self): - import asyncio - - import cloudsmith_api - import httpx2 - api_config = cloudsmith_api.Configuration() api_config.host = "https://api.cloudsmith.io" api_config.headers = {} @@ -556,6 +632,27 @@ def test_frozen_executable_runs_mcp_directly(self): "args": ["-P", "staging", "mcp", "start"], } + def test_configure_keeps_tool_flags_in_start_args(self, runner, tmp_path): + config_path = tmp_path / "mcp.json" + with patch( + "cloudsmith_cli.cli.commands.mcp.get_config_path", + return_value=config_path, + ): + result = runner.invoke( + configure, ["--client", "cursor", "-k", "x", "-a", "-D"] + ) + + assert result.exit_code == 0, result.output + server_args = json.loads(config_path.read_text())["mcpServers"]["cloudsmith"][ + "args" + ] + assert server_args[-4:] == [ + "mcp", + "start", + "--all-tools", + "--allow-destructive-tools", + ] + class TestMCPConfigureClaudeCode: def test_user_scope_merges_into_existing_claude_json(self, tmp_path): diff --git a/cloudsmith_cli/core/mcp/data.py b/cloudsmith_cli/core/mcp/data.py index 99e1c43c..70c41eaf 100644 --- a/cloudsmith_cli/core/mcp/data.py +++ b/cloudsmith_cli/core/mcp/data.py @@ -1,6 +1,8 @@ from dataclasses import dataclass from typing import Any +TOOL_DELETE_SUFFIXES = ["delete", "destroy", "remove"] + @dataclass class OpenAPITool: @@ -13,5 +15,13 @@ class OpenAPITool: parameters: dict[str, Any] base_url: str query_filter: str | None - is_destructive: bool = False - is_read_only: bool = False + + @property + def is_destructive(self) -> bool: + return self.method != "GET" or any( + suffix in self.name for suffix in TOOL_DELETE_SUFFIXES + ) + + @property + def is_read_only(self) -> bool: + return not self.is_destructive diff --git a/cloudsmith_cli/core/mcp/server.py b/cloudsmith_cli/core/mcp/server.py index 8fd8afca..0a9cfcd4 100644 --- a/cloudsmith_cli/core/mcp/server.py +++ b/cloudsmith_cli/core/mcp/server.py @@ -4,6 +4,7 @@ import json import os import ssl +from collections.abc import Callable from typing import Any from urllib import parse @@ -26,10 +27,6 @@ "v1": "swagger/?format=openapi", "v2": "openapi/?format=json", } -TOOL_DELETE_SUFFIXES = ["delete", "destroy", "remove"] - -TOOL_READ_ONLY_SUFFIXES = ["read", "list", "retrieve"] - # Common action suffixes in OpenAPI operation IDs # These should not be considered as part of the resource group hierarchy TOOL_ACTION_SUFFIXES = [ @@ -75,6 +72,15 @@ "repo_retention", ] +# Read tools in these groups return API keys, entitlement tokens or upstream secrets. +CREDENTIAL_GROUPS = { + "entitlements", + "orgs_services", + "repos_upstream", + "user_token", + "user_tokens", +} + SERVER_NAME = "Cloudsmith MCP Server" # Environment variables that point at a CA bundle (file) or hashed CA directory. @@ -326,6 +332,7 @@ def __init__( self.allowed_tools = set(allowed_tools or []) self.force_all_tools = force_all_tools self.tools: dict[str, OpenAPITool] = {} + self.hidden_allowlisted_tools: list[str] = [] self.spec = {} self._ssl_context: ssl.SSLContext | bool | None = None @@ -399,28 +406,25 @@ def _get_tool_groups(self, tool_name: str) -> list[str]: return groups - def _is_tool_destructive(self, tool_name: str) -> bool: - return any(suffix in tool_name for suffix in TOOL_DELETE_SUFFIXES) - - def _is_tool_read_only(self, tool_name: str) -> bool: - return any(suffix in tool_name for suffix in TOOL_READ_ONLY_SUFFIXES) - - def _is_tool_allowed(self, tool_name: str) -> bool: + def _is_tool_allowed(self, tool: OpenAPITool) -> bool: """Check if a tool is allowed based on user configuration""" - if self.force_all_tools: - return True + tool_groups = self._get_tool_groups(tool.name) + allowed_tool_group = bool(set(tool_groups) & set(self.allowed_tool_groups)) + allowed_tool = tool.name in self.allowed_tools - # Check if tool is destructive and destructive tools are disabled - if not self.allow_destructive_tools and self._is_tool_destructive(tool_name): + if not self.allow_destructive_tools and ( + tool.is_destructive or CREDENTIAL_GROUPS.intersection(tool_groups) + ): + if allowed_tool or allowed_tool_group: + self.hidden_allowlisted_tools.append(tool.name) return False - tool_groups = self._get_tool_groups(tool_name) + if self.force_all_tools: + return True # If user provided their own list of allowed tools or tool groups if len(self.allowed_tools) > 0 or len(self.allowed_tool_groups) > 0: - allowed_tool_group = bool(set(tool_groups) & set(self.allowed_tool_groups)) - allowed_tool = tool_name in self.allowed_tools return allowed_tool or allowed_tool_group # Otherwise disable all categories in the default list @@ -445,7 +449,7 @@ async def _generate_tools_from_spec(self, base_url: str): path_parameters, base_url, ) - if tool and self._is_tool_allowed(tool.name): + if tool and self._is_tool_allowed(tool): self.tools[tool.name] = tool self._register_dynamic_tool(tool) @@ -819,8 +823,6 @@ def _create_tool_from_operation( parameters=parameter_schema, base_url=base_url, query_filter=simplified_query, - is_destructive=self._is_tool_destructive(tool_name), - is_read_only=self._is_tool_read_only(tool_name), ) def _format_enum_description( @@ -902,9 +904,11 @@ def _resolve_schema(self, schema: dict[str, Any]) -> dict[str, Any]: return resolved_schema - def run(self): + def run(self, on_tools_loaded: Callable[[], None] | None = None): """Initialize and run the server""" asyncio.run(self.load_openapi_spec()) + if on_tools_loaded: + on_tools_loaded() try: try: self.mcp.run(transport="stdio")