codeant-ai-for-open-source[bot] commented on code in PR #40399:
URL: https://github.com/apache/superset/pull/40399#discussion_r3293915409


##########
superset/mcp_service/dashboard/tool/update_dashboard.py:
##########
@@ -0,0 +1,205 @@
+# 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.
+
+"""
+Update dashboard FastMCP tool
+
+This module contains the FastMCP tool for updating an existing dashboard's
+layout, theme, and styling. Companion to ``generate_dashboard`` for
+incremental edits without re-creating the dashboard.
+"""
+
+import logging
+
+from fastmcp import Context
+from sqlalchemy.exc import SQLAlchemyError
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import db, event_logger
+from superset.mcp_service.dashboard.schemas import (
+    DashboardError,
+    GenerateDashboardResponse,
+    UpdateDashboardRequest,
+    dashboard_serializer,
+)
+from superset.mcp_service.utils.url_utils import get_superset_base_url
+from superset.utils import json
+
+logger = logging.getLogger(__name__)
+
+
+def _resolve_dashboard(identifier):
+    """Look up a dashboard by id, uuid, or slug. Returns the model or None."""
+    # Deferred import — DashboardDAO transitively pulls models whose
+    # Column definitions need the Flask app to be initialized first.
+    # Importing inside the function lets tool registration succeed at
+    # module-load time without triggering "App not initialized yet".
+    from superset.daos.dashboard import DashboardDAO
+
+    try:
+        return DashboardDAO.get_by_id_or_slug(identifier)
+    except Exception:  # pylint: disable=broad-except
+        # get_by_id_or_slug raises DashboardNotFoundError; treat all
+        # lookup-time errors as "not found" so the tool can return a
+        # structured DashboardError response instead of bubbling up.
+        return None
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="Dashboard",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Update dashboard layout/theme/CSS",
+        readOnlyHint=False,
+        destructiveHint=False,
+    ),
+)
+async def update_dashboard(
+    request: UpdateDashboardRequest, ctx: Context = None
+) -> GenerateDashboardResponse | DashboardError:
+    """Patch an existing dashboard's layout, theme, or styling.
+
+    Companion to ``generate_dashboard`` for incremental edits. Accepts
+    the same layout/theme/CSS fields that ``generate_dashboard`` does, so
+    an LLM can:
+
+      - Set or replace ``position_json`` after auto-generation
+      - Apply brand ``label_colors`` and ``color_scheme`` via
+        ``json_metadata_overrides``
+      - Toggle ``cross_filters_enabled`` via ``json_metadata_overrides``
+      - Inject ``css`` to hide chrome on print-ready dashboards
+      - Update ``dashboard_title``, ``description``, ``slug``, ``published``
+
+    Only the fields explicitly passed are applied; other fields are left
+    unchanged. ``json_metadata_overrides`` is merged shallowly with the
+    existing json_metadata — pass only the keys you want to change.
+
+    Example::
+
+        update_dashboard(request={
+            "identifier": 42,
+            "json_metadata_overrides": {
+                "label_colors": {"Electronics": "#4C78A8"},
+                "cross_filters_enabled": False,
+            },
+            "css": ".header-controls {display: none;}",
+        })
+    """
+    await ctx.info(
+        "Updating dashboard: identifier=%s" % (request.identifier,)
+    )
+
+    dashboard = _resolve_dashboard(request.identifier)
+    if dashboard is None:
+        return DashboardError(
+            error=f"Dashboard not found: {request.identifier!r}",
+            error_type="DashboardNotFound",
+        )
+
+    changed_fields: list[str] = []
+
+    try:
+        with event_logger.log_context(action="mcp.update_dashboard.apply"):
+            if request.dashboard_title is not None:
+                dashboard.dashboard_title = request.dashboard_title
+                changed_fields.append("dashboard_title")
+
+            if request.description is not None:
+                dashboard.description = request.description
+                changed_fields.append("description")
+
+            if request.slug is not None:
+                # Empty string clears the slug; non-empty sets it.
+                dashboard.slug = request.slug or None
+                changed_fields.append("slug")
+
+            if request.published is not None:
+                dashboard.published = request.published
+                changed_fields.append("published")

Review Comment:
   **🟠 Architect Review — HIGH**
   
   update_dashboard mutates dashboards after only a visibility/access check 
(DashboardDAO.get_by_id_or_slug + RBAC) and never enforces object-level 
ownership, so any user with Dashboard write permission can edit dashboards they 
can view but do not own, unlike the REST update path and other MCP dashboard 
mutators.
   
   **Suggestion:** Before applying updates, enforce object-level ownership 
using the same pattern as other dashboard-mutating flows (for example, calling 
security_manager.raise_for_ownership on the resolved dashboard, as in 
add_chart_to_existing_dashboard and UpdateDashboardCommand.validate).
   
   
   [Fix in 
Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=22860e66bba844279c5273edc1596fd1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 | [Fix in VSCode 
Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=22860e66bba844279c5273edc1596fd1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is an **Architect / Logical Review** comment left during a code review. 
These reviews are first-class, important findings — not optional suggestions. 
Do NOT dismiss this as a 'big architectural change' just because the title says 
architect review; most of these can be resolved with a small, localized fix 
once the intent is understood.
   
   **Path:** superset/mcp_service/dashboard/tool/update_dashboard.py
   **Line:** 107:133
   **Comment:**
        *HIGH: update_dashboard mutates dashboards after only a 
visibility/access check (DashboardDAO.get_by_id_or_slug + RBAC) and never 
enforces object-level ownership, so any user with Dashboard write permission 
can edit dashboards they can view but do not own, unlike the REST update path 
and other MCP dashboard mutators.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve 
this? If you propose a fix, implement it and please make it concise.
   If a suggested approach is provided above, use it as the authoritative 
instruction. If no explicit code suggestion is given, you MUST still draft and 
apply your own minimal, localized fix — do not punt back with 'no suggestion 
provided, review manually'. Keep the change as small as possible: add a guard 
clause, gate on a loading state, reorder an await, wrap in a conditional, etc. 
Do not refactor surrounding code or expand scope beyond the finding.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>



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