codeant-ai-for-open-source[bot] commented on code in PR #41472: URL: https://github.com/apache/superset/pull/41472#discussion_r3532853880
########## superset/mcp_service/chart/tool/delete_chart.py: ########## @@ -0,0 +1,140 @@ +# 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.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: + 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") + + +@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: + """Permanently delete a saved chart. + + Identify the chart by numeric ID or UUID string (NOT chart name). This is + destructive and cannot be undone. 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,)) + + chart = find_chart_by_identifier(request.identifier) + 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") Review Comment: **Suggestion:** The chart lookup runs before the guarded `try` block, so database lookup failures from `find_chart_by_identifier` are not caught by the tool’s error handling and will bubble up as hard failures. Move the lookup into the handled section (or add a dedicated `SQLAlchemyError` wrapper around lookup) so transient DB issues return a structured `DeleteChartResponse` instead of crashing the tool call. [possible bug] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx ⚠️ delete_chart tool crashes on database lookup failures. ⚠️ MCP client sees unstructured exception instead of DeleteChartResponse. ⚠️ Shared DB session not rolled back on lookup errors. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Start the Superset MCP server, which registers the chart tools via `create_mcp_app` and imports `delete_chart` in `superset/mcp_service/app.py:681-703` and `superset/mcp_service/chart/tool/__init__.py:18-32`. 2. From an MCP client, call the `"delete_chart"` tool on the global `mcp` instance with a payload like `{"request": {"identifier": 10}}`, following the pattern in `tests/unit_tests/mcp_service/chart/tool/test_delete_chart.py:79-81`. 3. The handler `delete_chart()` in `superset/mcp_service/chart/tool/delete_chart.py:63-81` logs the request and then performs a pre-delete lookup: `chart = find_chart_by_identifier(request.identifier)` at line 84. That helper calls `ChartDAO.find_by_id(...)` in `superset/daos/chart.py:45-74`, issuing a database query via `db.session`. 4. If the database layer raises `SQLAlchemyError` during this lookup (e.g., due to a lost DB connection or broken transaction), the exception is thrown before entering the `try` block at `delete_chart.py:96-133` which is the only place that catches `CommandException`, `SQLAlchemyError`, and `ValueError`. Because the lookup is outside that guarded section, no `_rollback()` is executed and no `DeleteChartResponse` is returned; instead the MCP call fails with an unhandled server error. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e6ad0329a4244f5e8f1078b1cd679b5b&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=e6ad0329a4244f5e8f1078b1cd679b5b&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:** 84:91 **Comment:** *Possible Bug: The chart lookup runs before the guarded `try` block, so database lookup failures from `find_chart_by_identifier` are not caught by the tool’s error handling and will bubble up as hard failures. Move the lookup into the handled section (or add a dedicated `SQLAlchemyError` wrapper around lookup) so transient DB issues return a structured `DeleteChartResponse` instead of crashing the tool call. 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=b62d044c44e5d6712148eae91064baa84eec1490724b7b3ed7c03053b7b887ec&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41472&comment_hash=b62d044c44e5d6712148eae91064baa84eec1490724b7b3ed7c03053b7b887ec&reaction=dislike'>👎</a> ########## superset/mcp_service/dashboard/tool/delete_dashboard.py: ########## @@ -0,0 +1,166 @@ +# 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_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 ( + DashboardDeleteFailedReportsExistError, + DashboardForbiddenError, + DashboardNotFoundError, +) +from superset.commands.exceptions import CommandException +from superset.extensions import event_logger +from superset.mcp_service.dashboard.schemas import ( + DeleteDashboardRequest, + DeleteDashboardResponse, +) +from superset.mcp_service.utils import escape_llm_context_delimiters + +logger = logging.getLogger(__name__) + + +def _find_dashboard_by_identifier(identifier: int | str) -> Any | None: + """Resolve a dashboard by numeric ID, UUID string, or slug. Returns None.""" + from superset.daos.dashboard import DashboardDAO + + if isinstance(identifier, int) or ( + isinstance(identifier, str) and identifier.isdigit() + ): + return DashboardDAO.find_by_id(int(identifier)) + # Try UUID, then fall back to slug. + dashboard = DashboardDAO.find_by_id(identifier, id_column="uuid") + if dashboard: + return dashboard + try: + return DashboardDAO.get_by_id_or_slug(identifier) + except DashboardNotFoundError: + return None + + +def _rollback() -> None: + from superset import db + + try: + db.session.rollback() # pylint: disable=consider-using-transaction + except SQLAlchemyError: + logger.warning( + "Database rollback failed during delete_dashboard error handling" + ) + + +@tool( + tags=["mutate"], + class_permission_name="Dashboard", + annotations=ToolAnnotations( + title="Delete dashboard", + readOnlyHint=False, + destructiveHint=True, + ), +) +async def delete_dashboard( + request: DeleteDashboardRequest, ctx: Context +) -> DeleteDashboardResponse: + """Permanently delete a dashboard. + + Identify the dashboard by numeric ID, UUID string, or slug. This is + destructive and cannot be undone. It removes the dashboard container only — + the charts on it are NOT deleted. The caller must own the dashboard (or be + an Admin); dashboards with attached alerts/reports cannot be deleted until + those are removed. + + Example: + ```json + {"identifier": 42} + ``` + + Returns success with the deleted dashboard's id/title, or an error. When the + caller lacks permission, ``permission_denied`` is true — do not retry; ask + the user. + """ + await ctx.info("Deleting dashboard: identifier=%s" % (request.identifier,)) + + dashboard = _find_dashboard_by_identifier(request.identifier) + if not dashboard: + safe_id = escape_llm_context_delimiters(str(request.identifier)[:200]) + msg = ( + f"No dashboard found with identifier: {safe_id}. " + "Use list_dashboards to get valid dashboard IDs." + ) + return DeleteDashboardResponse(success=False, error=msg, error_type="NotFound") Review Comment: **Suggestion:** The dashboard lookup is executed before the command `try`/`except`, so SQLAlchemy failures during identifier resolution are not converted into a structured `DeleteDashboardResponse`. This creates inconsistent behavior where lookup-time DB failures crash the tool call while delete-time failures are handled. Wrap lookup in the same error handling path. [possible bug] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx ⚠️ delete_dashboard tool crashes under database connectivity issues. ⚠️ MCP client receives generic error instead of structured response. ⚠️ Broken transaction state leaks into subsequent ORM operations. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. The Superset MCP server initializes and registers the `delete_dashboard` tool at startup via `create_mcp_app` and the imports in `superset/mcp_service/app.py:704-716`, and tests exercise this tool through FastMCP in `tests/unit_tests/mcp_service/dashboard/tool/test_delete_dashboard.py:84-87`. 2. A client calls `"delete_dashboard"` with `{"request": {"identifier": 1}}` (or any valid identifier), invoking the `delete_dashboard()` handler in `superset/mcp_service/dashboard/tool/delete_dashboard.py:83-102`. 3. Before entering the guarded `try` block at lines 117-159, `delete_dashboard()` performs a lookup `dashboard = _find_dashboard_by_identifier(request.identifier)` at line 105. `_find_dashboard_by_identifier()` issues database queries via `DashboardDAO.find_by_id(int(identifier))` or `DashboardDAO.get_by_id_or_slug(identifier)` in `superset/daos/dashboard.py:137-162`, all using the shared SQLAlchemy session `db.session`. 4. If a `SQLAlchemyError` is raised during these lookup queries (for example, due to a transient database connectivity problem or a broken transaction), the exception occurs inside `_find_dashboard_by_identifier()` before the `try`/`except` block that catches `(CommandException, SQLAlchemyError, ValueError)` and calls `_rollback()` at delete_dashboard.py:63-71. As a result, the exception is not converted into a structured `DeleteDashboardResponse`, `_rollback()` is not invoked, and the MCP tool call fails with an unhandled server error while the underlying session remains in an invalid transaction state. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=3adb10c18f6b4a1bac198aaa08d401b7&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=3adb10c18f6b4a1bac198aaa08d401b7&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/delete_dashboard.py **Line:** 105:112 **Comment:** *Possible Bug: The dashboard lookup is executed before the command `try`/`except`, so SQLAlchemy failures during identifier resolution are not converted into a structured `DeleteDashboardResponse`. This creates inconsistent behavior where lookup-time DB failures crash the tool call while delete-time failures are handled. Wrap lookup in the same error handling path. 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=9062abee81db737c0a6ae7e67a953e563492c477ba22ac1dfb1a92890fe282a0&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41472&comment_hash=9062abee81db737c0a6ae7e67a953e563492c477ba22ac1dfb1a92890fe282a0&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]
