gkneighb commented on code in PR #41472:
URL: https://github.com/apache/superset/pull/41472#discussion_r3555981505


##########
superset/mcp_service/app.py:
##########
@@ -133,6 +133,7 @@ def get_default_instructions(
 - update_dashboard: Update an existing dashboard's 
title/description/slug/published/layout/theme/CSS (requires write access; 
editorship-checked per-instance)
 - duplicate_dashboard: Duplicate an existing dashboard, optionally 
deep-copying its charts (requires write access)
 - add_chart_to_existing_dashboard: Add a chart to an existing dashboard 
(requires write access)
+- delete_dashboard: Delete a dashboard by ID/UUID/slug (requires ownership; 
destructive; does not delete its charts; soft-deletes to trash when the 
SOFT_DELETE feature flag is on, permanent otherwise)
 - manage_native_filters: Add, update, remove, or reorder native filters on a 
dashboard (requires write access; supports filter_select and filter_time)

Review Comment:
   Confirmed and fixed in c075793baa — master moved the delete commands to 
raise_for_editorship; docstrings and server instructions now say editor rights 
(owners and Admins qualify).



##########
superset/mcp_service/app.py:
##########
@@ -181,6 +182,7 @@ def get_default_instructions(
 - generate_explore_link: Create an interactive explore URL (preferred for 
exploration)
 - update_chart: Update existing saved chart configuration (requires write 
access)
 - update_chart_preview: Update cached chart preview without saving (requires 
write access)
+- delete_chart: Delete a chart by ID/UUID (requires ownership; destructive; 
soft-deletes to trash when the SOFT_DELETE feature flag is on, permanent 
otherwise)
 

Review Comment:
   Confirmed and fixed in c075793baa — master moved the delete commands to 
raise_for_editorship; docstrings and server instructions now say editor rights 
(owners and Admins qualify).



##########
superset/mcp_service/chart/tool/delete_chart.py:
##########
@@ -0,0 +1,181 @@
+# 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: delete_chart
+"""
+
+import logging
+
+from fastmcp import Context
+from sqlalchemy.exc import SQLAlchemyError
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset import is_feature_enabled
+from superset.commands.chart.exceptions import (
+    ChartDeleteFailedReportsExistError,
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.exceptions import CommandException
+from superset.extensions import event_logger
+from superset.mcp_service.chart.chart_helpers import find_chart_by_identifier
+from superset.mcp_service.chart.schemas import (
+    DeleteChartRequest,
+    DeleteChartResponse,
+)
+from superset.mcp_service.utils import escape_llm_context_delimiters
+
+logger = logging.getLogger(__name__)
+
+
+def _rollback() -> None:
+    """Best-effort session rollback so a failed delete cannot poison the
+    request's transaction; rollback failures are logged, not raised."""
+    from superset import db
+
+    try:
+        db.session.rollback()  # pylint: disable=consider-using-transaction
+    except SQLAlchemyError:
+        logger.warning("Database rollback failed during delete_chart error 
handling")
+
+
+def _routes_to_soft_delete() -> bool:
+    """Mirror the ``BaseDAO.delete`` routing predicate so the response can
+    report whether the row was trashed (restorable) or permanently removed."""
+    from superset.models.helpers import SoftDeleteMixin
+    from superset.models.slice import Slice
+
+    return issubclass(Slice, SoftDeleteMixin) and 
is_feature_enabled("SOFT_DELETE")
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="Chart",
+    annotations=ToolAnnotations(
+        title="Delete chart",
+        readOnlyHint=False,
+        destructiveHint=True,
+    ),
+)
+async def delete_chart(
+    request: DeleteChartRequest, ctx: Context
+) -> DeleteChartResponse:
+    """Delete a saved chart.
+
+    Identify the chart by numeric ID or UUID string (NOT chart name). When the
+    ``SOFT_DELETE`` feature flag is enabled the chart is moved to trash and can
+    be restored by an owner or Admin; otherwise the delete is permanent and
+    cannot be undone. The ``soft_deleted`` response field reports which
+    happened. The caller must own the chart (or be an Admin); charts with
+    attached alerts/reports cannot be deleted until those are removed.
+
+    Example:
+    ```json
+    {"identifier": 123}
+    ```
+
+    Returns success with the deleted chart's id/name, or an error. When the
+    caller lacks permission, ``permission_denied`` is true — do not retry; ask
+    the user.
+    """
+    await ctx.info("Deleting chart: identifier=%s" % (request.identifier,))
+
+    try:
+        chart = find_chart_by_identifier(request.identifier)
+    except SQLAlchemyError:
+        _rollback()
+        logger.exception("Chart lookup failed during delete_chart")
+        return DeleteChartResponse(
+            success=False,
+            error="Chart lookup failed due to a database error.",
+            error_type="LookupFailed",
+        )
+    if not chart:
+        safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+        msg = (
+            f"No chart found with identifier: {safe_id}. "
+            "Use list_charts to get valid chart IDs."
+        )
+        return DeleteChartResponse(success=False, error=msg, 
error_type="NotFound")
+
+    chart_id = chart.id
+    chart_name = chart.slice_name
+
+    # The try/except sits inside log_context so failed attempts (forbidden,
+    # reports-exist, db errors) are recorded in the audit log too — the
+    # context manager does not log when an exception propagates through it.
+    with event_logger.log_context(action="mcp.delete_chart"):
+        try:
+            from superset.commands.chart.delete import DeleteChartCommand
+
+            DeleteChartCommand([chart_id]).run()
+
+            soft_deleted = _routes_to_soft_delete()
+            if soft_deleted:
+                message = (
+                    f"Moved chart '{chart_name}' (id={chart_id}) to trash. "
+                    "It can be restored by an owner or Admin."
+                )
+            else:
+                message = f"Permanently deleted chart '{chart_name}' 
(id={chart_id})."
+            return DeleteChartResponse(
+                success=True,
+                deleted_id=chart_id,
+                deleted_name=chart_name,
+                soft_deleted=soft_deleted,
+                message=message,
+            )
+        except ChartForbiddenError:
+            await ctx.warning("Permission denied deleting chart id=%s" % 
(chart_id,))
+            return DeleteChartResponse(
+                success=False,
+                permission_denied=True,
+                error=(
+                    f"You do not have permission to delete chart 
'{chart_name}' "
+                    f"(id={chart_id}). Ask the user to delete it or grant "
+                    "access; do not retry."
+                ),
+                error_type="Forbidden",
+            )
+        except ChartDeleteFailedReportsExistError as ex:
+            _rollback()
+            return DeleteChartResponse(
+                success=False,
+                error=(
+                    f"Chart '{chart_name}' (id={chart_id}) cannot be deleted: "
+                    f"{ex}. Remove the associated alerts/reports first."
+                ),

Review Comment:
   Fixed in c075793baa — chart names (and dashboard titles in the sibling tool) 
are now wrapped via sanitize_for_llm_context before composing response text, 
matching the convention from #41842/#41497. The raw-exception half was already 
fixed in 0439d6b2b2 (SQLAlchemyError → generic message; CommandException text 
is user-facing by design).



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