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


##########
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:
   **Suggestion:** This line documents ownership as a prerequisite, but chart 
deletion is authorized via editorship checks in the command layer, so the 
instruction can cause false permission assumptions and skipped valid actions. 
Align the text with actual editorship-based authorization. [comment mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ MCP delete_chart tool docs misstate required permission level.
   - ⚠️ Agents may skip valid chart deletions for editors.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. In `superset/mcp_service/app.py:76-87`, the `get_default_instructions()` 
string
   documents the “Chart Management” tools; line 86 describes `delete_chart` as 
“Delete a
   chart by ID/UUID (requires ownership; destructive; …)”.
   
   2. The `create_mcp_app()` function in `superset/mcp_service/app.py:713-728` 
imports
   `delete_chart` from `superset.mcp_service.chart.tool` and registers it as an 
MCP tool, so
   this description is what MCP agents see for `delete_chart`.
   
   3. The actual delete enforcement is implemented by `DeleteChartCommand` in
   `superset/commands/chart/delete.py:1-31`; its `validate()` method checks for 
reports
   (lines 17-25) and then, at lines 26-30, enforces
   `security_manager.raise_for_editorship(model)` for each chart, i.e., 
editorship, not
   ownership.
   
   4. When an MCP agent runs under a user account that is an editor but not 
owner of a chart,
   the instructions in `get_default_instructions()` say the tool “requires 
ownership”, even
   though `DeleteChartCommand` would allow the operation, so the agent may 
incorrectly avoid
   calling `delete_chart` or misreport it as invalid for that user.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=6cd542418dc44b148a00409bd8cf6941&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=6cd542418dc44b148a00409bd8cf6941&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/app.py
   **Line:** 186:186
   **Comment:**
        *Comment Mismatch: This line documents ownership as a prerequisite, but 
chart deletion is authorized via editorship checks in the command layer, so the 
instruction can cause false permission assumptions and skipped valid actions. 
Align the text with actual editorship-based authorization.
   
   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%2F41472&comment_hash=87a1afccf1dacf093abdfa9d643d480001c6c6542e07596981d3684f0e6c75c2&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41472&comment_hash=87a1afccf1dacf093abdfa9d643d480001c6c6542e07596981d3684f0e6c75c2&reaction=dislike'>👎</a>



##########
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:
   **Suggestion:** This instruction says deletion requires ownership, but the 
command layer actually enforces editorship (`raise_for_editorship`), so agents 
may incorrectly avoid valid delete operations for non-owner editors. Update the 
wording to match the real permission contract. [comment mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ MCP delete_dashboard tool docs misstate required permission level.
   - ⚠️ LLM agents may avoid allowed dashboard deletions by editors.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. In `superset/mcp_service/app.py:64-86`, the `get_default_instructions()` 
function
   builds the system prompt string returned to MCP agents, including the 
“Dashboard
   Management” tool list where line 137 documents `delete_dashboard` as 
“requires ownership”.
   
   2. The `create_mcp_app()` factory in `superset/mcp_service/app.py:705-739` 
imports
   `delete_dashboard` from `superset.mcp_service.dashboard.tool` and registers 
it as an MCP
   tool, so agents will both see this instruction text and have access to the
   `delete_dashboard` tool.
   
   3. The actual deletion behavior is implemented by `DeleteDashboardCommand` in
   `superset/commands/dashboard/delete.py:18-48`, whose `validate()` method 
first loads
   dashboards and then, at lines 43-47, enforces
   `security_manager.raise_for_editorship(model)`, i.e., editorship, not strict 
ownership.
   
   4. When an MCP agent is acting for a user who is an editor but not owner of 
a dashboard,
   the instructions in `get_default_instructions()` say deletion “requires 
ownership”, while
   the command layer would allow an editor (via `raise_for_editorship`), so the 
agent may
   unnecessarily avoid calling `delete_dashboard` or incorrectly report that 
the operation is
   not allowed even though it would succeed.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ff76e1d42a084b60be8bb1daaee51d3c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ff76e1d42a084b60be8bb1daaee51d3c&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/app.py
   **Line:** 137:137
   **Comment:**
        *Comment Mismatch: This instruction says deletion requires ownership, 
but the command layer actually enforces editorship (`raise_for_editorship`), so 
agents may incorrectly avoid valid delete operations for non-owner editors. 
Update the wording to match the real permission contract.
   
   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%2F41472&comment_hash=37540954161ced6b4680f913de668a3751ddd699109ac79a2850cd17e0e88c6a&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41472&comment_hash=37540954161ced6b4680f913de668a3751ddd699109ac79a2850cd17e0e88c6a&reaction=dislike'>👎</a>



##########
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:
   **Suggestion:** The tool returns LLM-facing messages that interpolate 
untrusted database text (`chart_name` and `ex`) without sanitization. A 
malicious chart title or report name can inject prompt-control delimiters into 
MCP responses. Sanitize or escape all dynamic text before building 
`message`/`error` fields. [security]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ LLM-facing delete_chart errors embed unsanitized database text.
   - ❌ Prompt-injection possible via malicious chart or report names.
   - ⚠️ Agent reasoning degraded by contaminated MCP tool responses.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. The MCP tool `delete_chart` is defined in
   `superset/mcp_service/chart/tool/delete_chart.py:75-95` and returns a
   `DeleteChartResponse` Pydantic model from 
`superset/mcp_service/chart/schemas.py:11-27`,
   whose `message` and `error` fields are plain `str | None` with no sanitizing 
validators.
   
   2. When deletion is blocked by attached alerts/reports, 
`DeleteChartCommand.validate()` in
   `superset/commands/chart/delete.py:12-25` calls 
`ReportScheduleDAO.find_by_chart_ids`,
   builds `report_names = [report.name for report in reports]` (line 19), and 
raises
   `ChartDeleteFailedReportsExistError` with a message containing the 
comma-joined,
   user-controlled report names (lines 20-24).
   
   3. In the MCP tool implementation, `delete_chart` catches this at
   `superset/mcp_service/chart/tool/delete_chart.py:155-162` and constructs an 
error string:
   `f"Chart '{chart_name}' (id={chart_id}) cannot be deleted: {ex}. Remove the 
associated
   alerts/reports first."`, where `chart_name` comes directly from 
`chart.slice_name` (line
   117) and `ex` is the exception message containing report names; neither 
value is passed
   through `escape_llm_context_delimiters` or `sanitize_for_llm_context`.
   
   4. Because `DeleteChartResponse` does not wrap or escape its 
`error`/`message` fields (no
   model validators on those fields in `schemas.py:11-27`), any chart title or 
report name
   containing LLM control tokens (for example, the MCP’s `<UNTRUSTED-CONTENT>` 
delimiters
   referenced in `superset/mcp_service/utils/sanitization.py:38-41`) will be 
returned
   verbatim in the MCP tool response, allowing a maliciously-named chart or 
report to inject
   unescaped content into the agent’s prompt context when `delete_chart` fails 
with
   `ChartDeleteFailedReportsExistError`.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e73c7d72a62342a29679e585008015d9&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=e73c7d72a62342a29679e585008015d9&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/chart/tool/delete_chart.py
   **Line:** 159:162
   **Comment:**
        *Security: The tool returns LLM-facing messages that interpolate 
untrusted database text (`chart_name` and `ex`) without sanitization. A 
malicious chart title or report name can inject prompt-control delimiters into 
MCP responses. Sanitize or escape all dynamic text before building 
`message`/`error` fields.
   
   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%2F41472&comment_hash=eb5e344e5aa8655a7aa6549dd13c19ab79bd68406a4008c999ff42c544d066ff&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41472&comment_hash=eb5e344e5aa8655a7aa6549dd13c19ab79bd68406a4008c999ff42c544d066ff&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]

Reply via email to