codeant-ai-for-open-source[bot] commented on code in PR #41842: URL: https://github.com/apache/superset/pull/41842#discussion_r3540879992
########## superset/mcp_service/dashboard/tool/restore_dashboard.py: ########## @@ -0,0 +1,162 @@ +# 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: restore_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 ( + DashboardForbiddenError, + DashboardNotFoundError, +) +from superset.commands.exceptions import CommandException +from superset.extensions import event_logger +from superset.mcp_service.dashboard.schemas import ( + RestoreDashboardRequest, + RestoreDashboardResponse, +) +from superset.mcp_service.utils import ( + escape_llm_context_delimiters, + sanitize_for_llm_context, +) + +logger = logging.getLogger(__name__) + + +def _find_dashboard_for_restore(identifier: int | str) -> Any | None: + """Resolve a dashboard by numeric ID or UUID, including soft-deleted rows. + + ``skip_visibility_filter`` is the only bypass — the DAO ``base_filter`` + stays in effect, so rows the user cannot see in the live UI stay hidden. + Ownership is then enforced by ``RestoreDashboardCommand``. + """ + from superset.daos.dashboard import DashboardDAO + + return DashboardDAO.find_by_id_or_uuid(str(identifier), skip_visibility_filter=True) + + +def _rollback() -> None: + from superset import db + + try: + db.session.rollback() # pylint: disable=consider-using-transaction + except SQLAlchemyError: + logger.warning( + "Database rollback failed during restore_dashboard error handling" + ) + + +@tool( + tags=["mutate"], + class_permission_name="Dashboard", + annotations=ToolAnnotations( + title="Restore dashboard", + readOnlyHint=False, + destructiveHint=False, + ), +) +async def restore_dashboard( + request: RestoreDashboardRequest, ctx: Context +) -> RestoreDashboardResponse: + """Restore a soft-deleted dashboard from trash. + + Identify the dashboard by numeric ID or UUID string (slug lookup does not + cover trashed dashboards). Only dashboards that were soft-deleted (moved + to trash while the ``SOFT_DELETE`` feature flag was enabled) can be + restored; permanently deleted dashboards are unrecoverable. The caller + must own the dashboard (or be an Admin). + + Example: + ```json + {"identifier": 42} + ``` + + Returns success with the restored 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("Restoring dashboard: identifier=%s" % (request.identifier,)) + + dashboard = _find_dashboard_for_restore(request.identifier) + if not dashboard: Review Comment: **Suggestion:** The dashboard pre-lookup is performed before entering the guarded command-execution try/except, so SQLAlchemy errors from `find_by_id_or_uuid` can bubble up as uncaught exceptions and bypass the tool’s error envelope. Wrap this lookup in SQLAlchemy-aware error handling to keep restore failures deterministic and MCP-friendly. [possible bug] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ restore_dashboard tool fails generically on DB lookup errors. - ⚠️ MCP clients receive unstructured failures for dashboard restore. - ⚠️ Error-handling inconsistent with guarded command execution path. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Start the MCP server, which creates the default FastMCP instance `mcp` in `superset/mcp_service/app.py:104` and registers dashboard tools including `restore_dashboard` imported in `superset/mcp_service/dashboard/tool/__init__.py:18-28`. 2. From an MCP client, invoke the `restore_dashboard` tool with any identifier (e.g., `{"identifier": 42}`), causing the coroutine `restore_dashboard()` in `superset/mcp_service/dashboard/tool/restore_dashboard.py:79-98` to run. 3. Inside `restore_dashboard`, after logging at `restore_dashboard.py:99`, the code performs the pre-lookup `dashboard = _find_dashboard_for_restore(request.identifier)` at `restore_dashboard.py:101`; `_find_dashboard_for_restore` is defined at `restore_dashboard.py:47-56` and calls `DashboardDAO.find_by_id_or_uuid(str(identifier), skip_visibility_filter=True)`, which issues a SQLAlchemy query via `db.session.query(...)` in `superset/daos/base.py:20-31`. 4. If a transient database outage or similar SQLAlchemy-level failure occurs during that query (raising a `SQLAlchemyError` from the session in `base.py:30-48`), the exception propagates back to `restore_dashboard` at line 101, before the guarded `try:` block at `restore_dashboard.py:124-155`; because no `try/except` encompasses the lookup, the error is not converted into a `RestoreDashboardResponse` with `success=False` and `error_type=...`, and instead escapes as an unhandled tool exception, yielding a generic MCP tool failure instead of the expected structured error response. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=15b07ccf0e3d437bb617a85383013ec9&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=15b07ccf0e3d437bb617a85383013ec9&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/restore_dashboard.py **Line:** 101:102 **Comment:** *Possible Bug: The dashboard pre-lookup is performed before entering the guarded command-execution try/except, so SQLAlchemy errors from `find_by_id_or_uuid` can bubble up as uncaught exceptions and bypass the tool’s error envelope. Wrap this lookup in SQLAlchemy-aware error handling to keep restore failures deterministic and MCP-friendly. 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%2F41842&comment_hash=59ab04239d1a89434663c6c096a2fd2d42817e1738e129224f5904a9993be5a7&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=59ab04239d1a89434663c6c096a2fd2d42817e1738e129224f5904a9993be5a7&reaction=dislike'>👎</a> ########## superset/mcp_service/chart/tool/restore_chart.py: ########## @@ -0,0 +1,155 @@ +# 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: restore_chart +""" + +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.chart.exceptions import ( + ChartForbiddenError, + ChartNotFoundError, +) +from superset.commands.exceptions import CommandException +from superset.extensions import event_logger +from superset.mcp_service.chart.schemas import ( + RestoreChartRequest, + RestoreChartResponse, +) +from superset.mcp_service.utils import ( + escape_llm_context_delimiters, + sanitize_for_llm_context, +) + +logger = logging.getLogger(__name__) + + +def _find_chart_for_restore(identifier: int | str) -> Any | None: + """Resolve a chart by numeric ID or UUID, including soft-deleted rows. + + ``skip_visibility_filter`` is the only bypass — the DAO ``base_filter`` + stays in effect, so rows the user cannot see in the live UI stay hidden. + Ownership is then enforced by ``RestoreChartCommand``. + """ + from superset.daos.chart import ChartDAO + + return ChartDAO.find_by_id_or_uuid(str(identifier), skip_visibility_filter=True) + + +def _rollback() -> None: + from superset import db + + try: + db.session.rollback() # pylint: disable=consider-using-transaction + except SQLAlchemyError: + logger.warning("Database rollback failed during restore_chart error handling") + + +@tool( + tags=["mutate"], + class_permission_name="Chart", + annotations=ToolAnnotations( + title="Restore chart", + readOnlyHint=False, + destructiveHint=False, + ), +) +async def restore_chart( + request: RestoreChartRequest, ctx: Context +) -> RestoreChartResponse: + """Restore a soft-deleted chart from trash. + + Identify the chart by numeric ID or UUID string (NOT chart name). Only + charts that were soft-deleted (moved to trash while the ``SOFT_DELETE`` + feature flag was enabled) can be restored; permanently deleted charts are + unrecoverable. The caller must own the chart (or be an Admin). + + Example: + ```json + {"identifier": 123} + ``` + + Returns success with the restored 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("Restoring chart: identifier=%s" % (request.identifier,)) + + chart = _find_chart_for_restore(request.identifier) + if not chart: Review Comment: **Suggestion:** The initial chart lookup runs outside the try/except block, so database failures during `find_by_id_or_uuid` (for example, transient DB outages/OperationalError) will raise out of the tool and return an unhandled failure instead of a structured `RestoreChartResponse`. Move the lookup into protected error handling (or add a dedicated `except SQLAlchemyError` around lookup) so lookup-time DB errors are reported consistently. [possible bug] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ restore_chart MCP tool surfaces generic failures on DB outages. - ⚠️ LLM agents lose structured error_type for lookup failures. - ⚠️ Inconsistent error envelope vs post-lookup command failures. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Start the MCP server, which creates the default FastMCP instance `mcp` in `superset/mcp_service/app.py:104` and registers chart tools including `restore_chart` defined at `superset/mcp_service/chart/tool/restore_chart.py:77-79` via the chart tool package. 2. From an MCP client, invoke the `restore_chart` tool with any identifier (e.g., `{"identifier": 123}`), causing the coroutine `restore_chart()` in `superset/mcp_service/chart/tool/restore_chart.py:77-95` to execute. 3. Inside `restore_chart`, after logging at `restore_chart.py:96`, the code calls `_find_chart_for_restore(request.identifier)` at `restore_chart.py:98`; `_find_chart_for_restore` is defined at `restore_chart.py:47-56` and calls `ChartDAO.find_by_id_or_uuid(str(identifier), skip_visibility_filter=True)`, which uses `db.session.query(...)` in `superset/daos/base.py:20-31`. 4. If the database is unavailable or a SQLAlchemy-level database error occurs while executing the query (e.g., an `OperationalError` bubbling as `SQLAlchemyError` from the session in `base.py:30-48`), that exception is raised back into `restore_chart` at line 98, before the `try:` block at `restore_chart.py:121-148`; because no surrounding `try/except` covers the lookup, the exception escapes the tool function instead of being translated into a structured `RestoreChartResponse` with `success=False` and `error_type=...`, so the MCP client receives a generic tool failure rather than the expected schema-shaped error. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=1da4179b9987481281672f1ccdba4cc0&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=1da4179b9987481281672f1ccdba4cc0&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/restore_chart.py **Line:** 98:99 **Comment:** *Possible Bug: The initial chart lookup runs outside the try/except block, so database failures during `find_by_id_or_uuid` (for example, transient DB outages/OperationalError) will raise out of the tool and return an unhandled failure instead of a structured `RestoreChartResponse`. Move the lookup into protected error handling (or add a dedicated `except SQLAlchemyError` around lookup) so lookup-time DB errors are reported consistently. 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%2F41842&comment_hash=e278e897d18b6a31ef126a6a1aea382e27a22b4c33cad4acf691588b06050a1f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=e278e897d18b6a31ef126a6a1aea382e27a22b4c33cad4acf691588b06050a1f&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]
