aminghadersohi commented on code in PR #40959:
URL: https://github.com/apache/superset/pull/40959#discussion_r3493283358


##########
superset/mcp_service/dashboard/tool/duplicate_dashboard.py:
##########
@@ -0,0 +1,393 @@
+# 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]:
+    """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 and a flag indicating whether the layout maps any
+    chart, so the caller can refuse to produce a silently empty copy.
+    """
+    try:
+        metadata = json.loads(source.json_metadata or "{}")
+    except (json.JSONDecodeError, TypeError):
+        metadata = {}
+    if not isinstance(metadata, dict):
+        metadata = {}

Review Comment:
   Fixed in 9d07579476. Rather than failing hard (which would block duplication 
of an otherwise valid dashboard just because of aesthetic metadata), the tool 
now surfaces a non-fatal warning in the response when json_metadata cannot be 
decoded or is not a JSON object. The warning tells the caller that colors, 
native filters, and other settings were reset to defaults while chart content 
was preserved from position_json. A regression test 
(test_malformed_json_metadata_warns_not_fails) asserts the copy proceeds, the 
dashboard is returned, and the warnings list contains the metadata-loss notice.



##########
superset/mcp_service/dashboard/tool/duplicate_dashboard.py:
##########
@@ -0,0 +1,393 @@
+# 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()
+    )

Review Comment:
   Declining to add cross-validation of position chart IDs against 
source.slices. The stale-IDs scenario (position_json references chart IDs that 
don't match the source's actual slices) is a pre-existing data consistency 
problem with the source dashboard — not a failure mode introduced by this tool. 
The existing guard already covers the primary case: if position_json maps no 
chart IDs at all while the source has charts, the tool fails fast with a clear 
error. Extending that guard to compare the two ID sets would add an O(n) set 
intersection check and extra code complexity for a rare edge case, and could 
generate confusing errors in partial-overlap scenarios. An empty copy is 
immediately visible and actionable. If this scenario surfaces in production it 
can be addressed as a follow-up.



-- 
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]

Reply via email to