codeant-ai-for-open-source[bot] commented on code in PR #40399: URL: https://github.com/apache/superset/pull/40399#discussion_r3467059799
########## superset/mcp_service/dashboard/tool/update_dashboard.py: ########## @@ -0,0 +1,253 @@ +# 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 typing import Any + +from fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.commands.dashboard.exceptions import DashboardNotFoundError +from superset.exceptions import SupersetSecurityException +from superset.extensions import db, event_logger +from superset.mcp_service.dashboard.schemas import ( + dashboard_serializer, + DashboardError, + UpdateDashboardRequest, + UpdateDashboardResponse, +) +from superset.mcp_service.utils.url_utils import get_superset_base_url +from superset.utils import json + +logger = logging.getLogger(__name__) + + +def _build_dashboard_url(dashboard: Any) -> str: + """Build the user-facing dashboard URL, preferring slug over id.""" + return ( + f"{get_superset_base_url()}/superset/dashboard/" + f"{dashboard.slug or dashboard.id}/" + ) + + +def _find_and_authorize_dashboard( + identifier: int | str, +) -> tuple[Any, UpdateDashboardResponse | DashboardError | None]: + """Return (dashboard, None) on success or (None, error_response) on failure. + + Mirrors the helper in ``add_chart_to_existing_dashboard``: combines + the not-found and forbidden cases so the main tool body has a single + pre-condition branch. Returns ``DashboardError`` on not-found and + ``UpdateDashboardResponse`` (with ``permission_denied=True``) on + ownership failure — the two shapes carry different information for + the caller. + """ + # avoids ImportError before Flask app initialisation: + # `Exception: App not initialized yet. Please call init_app first` + # raised from superset.utils.encrypt when DashboardDAO is imported + # (via Slice's encrypted Column types). `security_manager` is a + # LocalProxy that needs the same app context to resolve at call + # time, so it is co-located with the DAO it accompanies. + from superset import security_manager + from superset.daos.dashboard import DashboardDAO + + try: + dashboard = DashboardDAO.get_by_id_or_slug(identifier) + except (DashboardNotFoundError, SQLAlchemyError): + return None, DashboardError( + error=f"Dashboard not found: {identifier!r}", + error_type="DashboardNotFound", + ) + + if dashboard is None: + return None, DashboardError( + error=f"Dashboard not found: {identifier!r}", + error_type="DashboardNotFound", + ) + + try: + security_manager.raise_for_ownership(dashboard) + except SupersetSecurityException: + return None, UpdateDashboardResponse( + permission_denied=True, + error=( + f"You don't have permission to edit dashboard " + f"'{dashboard.dashboard_title}' (ID: {dashboard.id})." + ), + ) + + return dashboard, None + + +def _apply_field_updates(dashboard: Any, request: UpdateDashboardRequest) -> list[str]: + """Apply each explicitly-passed field to the dashboard. + + Returns the names of fields actually changed. Mutates ``dashboard`` + in place. ``json_metadata_overrides`` is merged shallowly with the + existing ``json_metadata``; an empty string in ``slug`` or ``css`` + clears the underlying value. + """ + changed: list[str] = [] + + if request.dashboard_title is not None: + dashboard.dashboard_title = request.dashboard_title + changed.append("dashboard_title") + + if request.description is not None: + dashboard.description = request.description + changed.append("description") + + if request.slug is not None: + dashboard.slug = request.slug or None + changed.append("slug") + + if request.published is not None: + dashboard.published = request.published + changed.append("published") + + if request.position_json is not None: + dashboard.position_json = json.dumps(request.position_json) + changed.append("position_json") + + if request.json_metadata_overrides is not None: + existing = ( + json.loads(dashboard.json_metadata or "{}") + if dashboard.json_metadata + else {} + ) + existing.update(request.json_metadata_overrides) + dashboard.json_metadata = json.dumps(existing) Review Comment: **Suggestion:** Merging `json_metadata_overrides` assumes `dashboard.json_metadata` is always valid JSON object text, but existing rows can contain malformed JSON or a non-object payload (for example `"[]"`). In those cases `json.loads(...)` or `existing.update(...)` will raise `ValueError`/`AttributeError`, which is not caught by the `SQLAlchemyError` handler, causing an unhandled tool failure instead of a structured response. Parse defensively (fallback to `{}` when parsing fails or result is not a dict) before applying overrides. [type error] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ MCP update_dashboard crashes on malformed dashboard json_metadata. - ⚠️ LLM workflows cannot retheme affected dashboards via MCP. - ⚠️ Operators see generic tool failure instead of clear metadata error. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Ensure there is a dashboard row with malformed or non-dict JSON metadata in the `dashboards` table defined at `superset/models/dashboard.py:131-144` (e.g. set `json_metadata` to the literal string `"[]"` or an invalid JSON string via SQL or an older migration). 2. Call the FastMCP `update_dashboard` tool implemented at `superset/mcp_service/dashboard/tool/update_dashboard.py:162-193` with a request matching `UpdateDashboardRequest` from `superset/mcp_service/dashboard/schemas.py:118-187`, including a non-null `json_metadata_overrides` dict (for example `{"label_colors": {"X": "#000000"}}`) and `identifier` pointing to the dashboard from step 1. 3. In `update_dashboard`, the tool logs the request and calls `_find_and_authorize_dashboard` at `superset/mcp_service/dashboard/tool/update_dashboard.py:56-102`, which returns the dashboard object whose `json_metadata` field contains the malformed / non-dict JSON string. 4. Inside the `event_logger.log_context` in `update_dashboard` at `superset/mcp_service/dashboard/tool/update_dashboard.py:203-205`, `_apply_field_updates` is invoked (`_apply_field_updates` is defined at lines 105-149). Because `request.json_metadata_overrides` is not `None`, the branch at lines 135-142 executes: `json.loads(dashboard.json_metadata or "{}")` attempts to parse the existing `json_metadata`. If the column contains invalid JSON, `json.loads(...)` raises a `JSONDecodeError`/`ValueError`; if it contains valid non-dict JSON such as `"[]"`, `json.loads(...)` returns a list and `existing.update(request.json_metadata_overrides)` at line 141 raises `AttributeError` (`'list' object has no attribute 'update'`). These exceptions are not subclasses of `SQLAlchemyError`, so they bypass the `except SQLAlchemyError` block at `update_dashboard.py:231-243` and propagate out of the tool, causing an unhandled FastMCP tool failure instead of returning an `UpdateDashboardResponse` or `DashboardError`. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=a47c9727e6164ee7b83e728e8f905955&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=a47c9727e6164ee7b83e728e8f905955&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 a comment left during a code review. **Path:** superset/mcp_service/dashboard/tool/update_dashboard.py **Line:** 136:142 **Comment:** *Type Error: Merging `json_metadata_overrides` assumes `dashboard.json_metadata` is always valid JSON object text, but existing rows can contain malformed JSON or a non-object payload (for example `"[]"`). In those cases `json.loads(...)` or `existing.update(...)` will raise `ValueError`/`AttributeError`, which is not caught by the `SQLAlchemyError` handler, causing an unhandled tool failure instead of a structured response. Parse defensively (fallback to `{}` when parsing fails or result is not a dict) before applying overrides. 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. 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> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40399&comment_hash=8725a77ce9d3a0c0d1d66914b2c33c6e946443e82dde22ece9b9f13a8ca0a8e1&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40399&comment_hash=8725a77ce9d3a0c0d1d66914b2c33c6e946443e82dde22ece9b9f13a8ca0a8e1&reaction=dislike'>👎</a> -- 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]
