codeant-ai-for-open-source[bot] commented on code in PR #40959: URL: https://github.com/apache/superset/pull/40959#discussion_r3493542140
########## superset/mcp_service/dashboard/tool/duplicate_dashboard.py: ########## @@ -0,0 +1,414 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +MCP tool: duplicate_dashboard + +Duplicates an existing dashboard, optionally deep-copying its charts. +Canonical workflow: clone a template dashboard, then edit the copy +(e.g. to create a regional or staging variant). +""" + +import logging +from typing import Any + +from fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.extensions import event_logger +from superset.mcp_service.dashboard.schemas import ( + _sanitize_dashboard_info_for_llm_context, + DashboardInfo, + DuplicateDashboardRequest, + DuplicateDashboardResponse, + serialize_chart_summary, +) +from superset.mcp_service.privacy import user_can_view_data_model_metadata +from superset.mcp_service.utils.url_utils import get_superset_base_url +from superset.utils import json + +logger = logging.getLogger(__name__) Review Comment: ✅ **Customized review instruction saved!** **Instruction:** > Do not flag module-level Python logger declarations like `logger = logging.getLogger(__name__)` for missing type annotations; Superset intentionally leaves these unannotated and relies on mypy's inference. **Applied to:** - `**/*.py` --- 💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)* ########## superset/mcp_service/dashboard/schemas.py: ########## @@ -914,6 +914,138 @@ class GenerateDashboardResponse(BaseModel): ) +class DuplicateDashboardRequest(BaseModel): + """Request schema for duplicating an existing dashboard.""" + + model_config = ConfigDict(populate_by_name=True) Review Comment: ✅ **Customized review instruction saved!** **Instruction:** > Do not flag unannotated `model_config = ConfigDict(...)` class-level configuration in Pydantic v2 models; it is a recognized sentinel and should remain unannotated unless there is a real type-safety issue. **Applied to:** - `**/*.py` --- 💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)* ########## tests/unit_tests/mcp_service/dashboard/tool/test_duplicate_dashboard.py: ########## @@ -0,0 +1,580 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Unit tests for the duplicate_dashboard MCP tool. + +Follows the same pattern used in test_add_chart_to_existing_dashboard.py: +- Tests run through the async MCP Client (not direct function calls) +- Patches applied at source locations (superset.daos.dashboard.*, + superset.commands.dashboard.copy.*) +- auth is mocked via the autouse mock_auth fixture + +Covers: +- Duplicate referencing the same charts (duplicate_slices=False, default) +- Duplicate with deep-copied charts (duplicate_slices=True) +- Source dashboard not found +- Source dashboard access denied / copy forbidden +- Title sanitization (XSS stripped, XSS-only title rejected) +""" + +import logging +from collections.abc import Iterator +from unittest.mock import MagicMock, Mock, patch + +import pytest +from fastmcp import Client + +from superset.mcp_service.app import mcp +from superset.mcp_service.utils.sanitization import ( + LLM_CONTEXT_CLOSE_DELIMITER, + LLM_CONTEXT_OPEN_DELIMITER, +) +from superset.utils import json + + +def _wrapped(value: str) -> str: + """Return the LLM-context-wrapped form a sanitized field should have.""" + return f"{LLM_CONTEXT_OPEN_DELIMITER}\n{value}\n{LLM_CONTEXT_CLOSE_DELIMITER}" + + +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# Fixtures +# --------------------------------------------------------------------------- + + [email protected] +def mcp_server() -> object: + """Return the FastMCP app instance for use in MCP client tests.""" + return mcp + + [email protected](autouse=True) +def mock_auth() -> Iterator[MagicMock]: + """Mock authentication for all tests.""" + with patch("superset.mcp_service.auth.get_user_from_request") as mock_get_user: + mock_user = Mock() + mock_user.id = 1 + mock_user.username = "admin" + mock_get_user.return_value = mock_user + yield mock_get_user + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +SOURCE_POSITIONS = { Review Comment: ✅ **Customized review instruction saved!** **Instruction:** > Do not require explicit type annotations for module-level constants in test files; clear literals in tests are fine without annotations. **Applied to:** - `**/test/**` - `**/tests/**` - `**/*test*.py` --- 💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)* ########## superset/mcp_service/dashboard/tool/duplicate_dashboard.py: ########## @@ -0,0 +1,414 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +MCP tool: duplicate_dashboard + +Duplicates an existing dashboard, optionally deep-copying its charts. +Canonical workflow: clone a template dashboard, then edit the copy +(e.g. to create a regional or staging variant). +""" + +import logging +from typing import Any + +from fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.extensions import event_logger +from superset.mcp_service.dashboard.schemas import ( + _sanitize_dashboard_info_for_llm_context, + DashboardInfo, + DuplicateDashboardRequest, + DuplicateDashboardResponse, + serialize_chart_summary, +) +from superset.mcp_service.privacy import user_can_view_data_model_metadata +from superset.mcp_service.utils.url_utils import get_superset_base_url +from superset.utils import json + +logger = logging.getLogger(__name__) + + +def _positions_reference_charts(positions: dict[str, Any]) -> bool: + """Return whether a layout maps any chart into the dashboard. + + ``DashboardDAO.set_dash_metadata`` rebuilds the new dashboard's slice + list solely from the chart IDs found in ``positions``, so a layout + with no ``CHART`` entries yields an empty dashboard regardless of the + source's ``slices`` relationship. + """ + return any( + isinstance(value, dict) + and value.get("type") == "CHART" + and value.get("meta", {}).get("chartId") + for value in positions.values() + ) + + +def _build_copy_payload( + source: Any, dashboard_title: str, duplicate_slices: bool +) -> tuple[dict[str, Any], bool, str | None]: + """Build the data payload expected by ``CopyDashboardCommand``. + + Mirrors what the frontend "Save as" flow sends to the + ``/api/v1/dashboard/<id>/copy/`` endpoint: the source dashboard's + current ``json_metadata`` with a ``positions`` key holding the current + layout (``position_json``). ``DashboardCopySchema`` requires + ``json_metadata``, and ``DashboardDAO.copy_dashboard`` reads + ``positions`` from it to remap chart IDs when ``duplicate_slices`` + is enabled. + + Returns the payload, a flag indicating whether the layout maps any + chart (so the caller can refuse to produce a silently empty copy), + and an optional warning string when ``json_metadata`` could not be + decoded. The caller surfaces the warning rather than hard-failing: + metadata loss degrades aesthetic settings (colors, native filters) + but does not corrupt the copy's chart content. + """ + metadata_warning: str | None = None + try: + metadata = json.loads(source.json_metadata or "{}") + except (json.JSONDecodeError, TypeError): + metadata = {} + metadata_warning = ( + "Source dashboard's stored settings (json_metadata) could not " + "be decoded and were not copied. The duplicate uses default " + "settings for colors, native filters, and other metadata. " + "Open and re-save the source dashboard to repair its settings." + ) + if not isinstance(metadata, dict): + metadata = {} + if metadata_warning is None: + metadata_warning = ( + "Source dashboard's stored settings (json_metadata) were not " + "a valid JSON object and were not copied. The duplicate uses " + "default settings for colors, native filters, and other metadata." + ) + + try: + positions = json.loads(source.position_json or "{}") + except (json.JSONDecodeError, TypeError): + positions = {} + if not isinstance(positions, dict): + positions = {} + + metadata["positions"] = positions + + payload = { + "dashboard_title": dashboard_title, + "css": source.css, + "duplicate_slices": duplicate_slices, + "json_metadata": json.dumps(metadata), + } Review Comment: ✅ **Customized review instruction saved!** **Instruction:** > Do not flag missing type annotations for short-lived local variables inside Python function bodies when the type is already obvious from context; reserve these comments for ambiguous cases or public interfaces. **Applied to:** - `**/*.py` --- 💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)* -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
