You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "gkneighb (via GitHub)" <gi...@apache.org> on 2026/07/07 02:21:45 UTC
[PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
gkneighb opened a new pull request, #41842:
URL: https://github.com/apache/superset/pull/41842
### SUMMARY
Adds `restore_chart` and `restore_dashboard` MCP tools, exposing the soft-delete restore capability introduced in #40129 / #40128 to MCP clients. With soft-delete rolling out behind the `SOFT_DELETE` feature flag, an LLM agent can trash a chart or dashboard via the REST-backed delete flows (and, pending #41472, via MCP delete tools) but has no way to undo it — these tools close that loop.
Design notes:
- **Delegates to `Restore{Chart,Dashboard}Command`** — ownership checks, the "is actually soft-deleted" guard, and transactional wrapping all live in the existing command layer; the tools add no new authorization logic.
- **Accepts numeric ID or UUID.** The restore commands are UUID-keyed, but MCP list/info/delete tools deal in numeric IDs, so the tools resolve the identifier via `find_by_id_or_uuid(..., skip_visibility_filter=True)`. Matching the command's own lookup semantics, the visibility filter is the *only* bypass — the DAO `base_filter` stays in effect, so rows the user can't see in the live UI stay hidden, and ownership is then enforced by the command.
- **Not gated on `SOFT_DELETE`** — mirroring the REST `POST /api/v1/chart/<uuid>/restore` endpoint, restore stays available even if the flag is later disabled, so rows trashed while it was on remain recoverable.
- **LLM-friendly errors** — distinct `NotFound` vs `NotDeleted` (`"is not in trash; nothing to restore"`) error types, and the established `permission_denied: true` / "do not retry; ask the user" convention for ownership failures.
Part of a series filling out MCP resource-lifecycle coverage (delete: #41472).
### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
N/A (MCP service tools; no UI changes)
### TESTING INSTRUCTIONS
Unit tests (12 new, run through the async FastMCP client like the other tool tests):
```bash
pytest tests/unit_tests/mcp_service/chart/tool/test_restore_chart.py \
tests/unit_tests/mcp_service/dashboard/tool/test_restore_dashboard.py
```
Manual: with `FEATURE_FLAGS = {"SOFT_DELETE": True}`, delete a chart you own (UI or API), then call the `restore_chart` MCP tool with its numeric ID or UUID — the chart reappears in list/detail endpoints. Calling it again returns `error_type: "NotDeleted"`. Calling it on someone else's trashed chart returns `permission_denied: true`.
### ADDITIONAL INFORMATION
- [ ] Has associated issue:
- [x] Required feature flags: `SOFT_DELETE` (to produce trashed rows; the restore tools themselves are not gated)
- [ ] Changes UI
- [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
- [ ] Migration is atomic, supports rollback & is backwards-compatible
- [ ] Confirm DB migration upgrade and downgrade tested
- [ ] Runtime estimates and downtime expectations provided
- [x] Introduces new feature or API
- [ ] Removes existing feature or API
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_014z1fQxTadTEvpCJLx9WnB8
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3575513358
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -2725,6 +2725,35 @@ class ChartFiltersInfo(BaseModel):
)
+class RestoreChartRequest(BaseModel):
+ """Request schema for restore_chart."""
+
+ identifier: int | str = Field(
+ ...,
+ description=(
+ "Chart identifier - numeric ID or UUID string (charts have no slug)."
+ ),
+ )
Review Comment:
Fixed in the latest push — boolean identifiers rejected on both restore request schemas with tests, mirroring the delete tools.
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,177 @@
+# 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.
+
+ Both bypasses mirror ``BaseRestoreCommand.validate``'s own lookup:
+ ``skip_visibility_filter`` unhides the soft-deleted row, and
+ ``skip_base_filter`` keeps an editor's own trash reachable even when the
+ entity's RBAC base_filter has no editorship leg (a lost grant must not
+ hide a row from the one audience that can restore it). The restore
+ audience is enforced by ``RestoreChartCommand`` via
+ ``raise_for_editorship``.
+ """
+ from superset.daos.chart import ChartDAO
+
+ return ChartDAO.find_by_id_or_uuid(
+ str(identifier),
+ skip_base_filter=True,
+ 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 be an editor of the chart (owners and
+ Admins qualify).
+
+ 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,))
+
+ try:
+ chart = _find_chart_for_restore(request.identifier)
+ except SQLAlchemyError:
+ _rollback()
+ logger.exception("Chart lookup failed during restore_chart")
+ return RestoreChartResponse(
+ 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}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ # Chart names are user-controlled; wrap before composing response text so
+ # a hostile name cannot inject prompt content into the tool output.
+ chart_name = sanitize_for_llm_context(chart.slice_name, field_path=("slice_name",))
+
+ if chart.deleted_at is None:
+ return RestoreChartResponse(
+ success=False,
+ error=(
+ f"Chart '{chart_name}' (id={chart_id}) is not in trash; "
+ "nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.chart.restore import RestoreChartCommand
+
+ with event_logger.log_context(action="mcp.restore_chart"):
+ RestoreChartCommand(str(chart.uuid)).run()
Review Comment:
Fixed in the latest push — try/except moved inside log_context so failed restore attempts are audited, mirroring the delete tools.
##########
superset/mcp_service/dashboard/tool/restore_dashboard.py:
##########
@@ -0,0 +1,185 @@
+# 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.
+
+ Both bypasses mirror ``BaseRestoreCommand.validate``'s own lookup:
+ ``skip_visibility_filter`` unhides the soft-deleted row, and
+ ``skip_base_filter`` keeps an editor's own trash reachable even when the
+ entity's RBAC base_filter has no editorship leg (a lost grant must not
+ hide a row from the one audience that can restore it). The restore
+ audience is enforced by ``RestoreDashboardCommand`` via
+ ``raise_for_editorship``.
+ """
+ from superset.daos.dashboard import DashboardDAO
+
+ return DashboardDAO.find_by_id_or_uuid(
+ str(identifier),
+ skip_base_filter=True,
+ 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 be an editor of the dashboard (owners and Admins qualify).
+
+ 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,))
+
+ try:
+ dashboard = _find_dashboard_for_restore(request.identifier)
+ except SQLAlchemyError:
+ _rollback()
+ logger.exception("Dashboard lookup failed during restore_dashboard")
+ return RestoreDashboardResponse(
+ success=False,
+ error="Dashboard lookup failed due to a database error.",
+ error_type="LookupFailed",
+ )
+ if not dashboard:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No dashboard found with identifier: {safe_id}."
+ return RestoreDashboardResponse(success=False, error=msg, error_type="NotFound")
+
+ dashboard_id = dashboard.id
+ # Dashboard titles are user-controlled; wrap before composing response
+ # text so a hostile title cannot inject prompt content into the output.
+ dashboard_name = sanitize_for_llm_context(
+ dashboard.dashboard_title, field_path=("dashboard_title",)
+ )
+
+ if dashboard.deleted_at is None:
+ return RestoreDashboardResponse(
+ success=False,
+ error=(
+ f"Dashboard '{dashboard_name}' (id={dashboard_id}) is not in "
+ "trash; nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.dashboard.restore import RestoreDashboardCommand
+
+ with event_logger.log_context(action="mcp.restore_dashboard"):
+ RestoreDashboardCommand(str(dashboard.uuid)).run()
Review Comment:
Fixed in the latest push — same restructure as restore_chart.
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,177 @@
+# 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.
+
+ Both bypasses mirror ``BaseRestoreCommand.validate``'s own lookup:
+ ``skip_visibility_filter`` unhides the soft-deleted row, and
+ ``skip_base_filter`` keeps an editor's own trash reachable even when the
+ entity's RBAC base_filter has no editorship leg (a lost grant must not
+ hide a row from the one audience that can restore it). The restore
+ audience is enforced by ``RestoreChartCommand`` via
+ ``raise_for_editorship``.
+ """
+ from superset.daos.chart import ChartDAO
+
+ return ChartDAO.find_by_id_or_uuid(
+ str(identifier),
+ skip_base_filter=True,
+ skip_visibility_filter=True,
+ )
Review Comment:
Declining: this bypass was explicitly requested in the maintainer's review (see the reopened thread above) and matches BaseRestoreCommand.validate at HEAD, which passes skip_base_filter=True by design — its docstring explains a lost base_filter grant must not hide a row from the one audience that can restore it. The restore audience is enforced by raise_for_editorship in the command; a non-editor holding a valid identifier gets permission_denied, same as the REST restore endpoint.
##########
superset/mcp_service/dashboard/tool/restore_dashboard.py:
##########
@@ -0,0 +1,185 @@
+# 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.
+
+ Both bypasses mirror ``BaseRestoreCommand.validate``'s own lookup:
+ ``skip_visibility_filter`` unhides the soft-deleted row, and
+ ``skip_base_filter`` keeps an editor's own trash reachable even when the
+ entity's RBAC base_filter has no editorship leg (a lost grant must not
+ hide a row from the one audience that can restore it). The restore
+ audience is enforced by ``RestoreDashboardCommand`` via
+ ``raise_for_editorship``.
+ """
+ from superset.daos.dashboard import DashboardDAO
+
+ return DashboardDAO.find_by_id_or_uuid(
+ str(identifier),
+ skip_base_filter=True,
+ skip_visibility_filter=True,
+ )
Review Comment:
Declining: this bypass was explicitly requested in the maintainer's review (see the reopened thread above) and matches BaseRestoreCommand.validate at HEAD, which passes skip_base_filter=True by design — its docstring explains a lost base_filter grant must not hide a row from the one audience that can restore it. The restore audience is enforced by raise_for_editorship in the command; a non-editor holding a valid identifier gets permission_denied, same as the REST restore endpoint.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3575310139
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,177 @@
+# 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.
+
+ Both bypasses mirror ``BaseRestoreCommand.validate``'s own lookup:
+ ``skip_visibility_filter`` unhides the soft-deleted row, and
+ ``skip_base_filter`` keeps an editor's own trash reachable even when the
+ entity's RBAC base_filter has no editorship leg (a lost grant must not
+ hide a row from the one audience that can restore it). The restore
+ audience is enforced by ``RestoreChartCommand`` via
+ ``raise_for_editorship``.
+ """
+ from superset.daos.chart import ChartDAO
+
+ return ChartDAO.find_by_id_or_uuid(
+ str(identifier),
+ skip_base_filter=True,
+ 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 be an editor of the chart (owners and
+ Admins qualify).
+
+ 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,))
+
+ try:
+ chart = _find_chart_for_restore(request.identifier)
+ except SQLAlchemyError:
+ _rollback()
+ logger.exception("Chart lookup failed during restore_chart")
+ return RestoreChartResponse(
+ 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}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ # Chart names are user-controlled; wrap before composing response text so
+ # a hostile name cannot inject prompt content into the tool output.
+ chart_name = sanitize_for_llm_context(chart.slice_name, field_path=("slice_name",))
+
+ if chart.deleted_at is None:
+ return RestoreChartResponse(
+ success=False,
+ error=(
+ f"Chart '{chart_name}' (id={chart_id}) is not in trash; "
+ "nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.chart.restore import RestoreChartCommand
+
+ with event_logger.log_context(action="mcp.restore_chart"):
+ RestoreChartCommand(str(chart.uuid)).run()
Review Comment:
**Suggestion:** The command execution is inside `event_logger.log_context`, but the `try/except` is outside it, so failed restore attempts exit the context by exception and are not reliably audited. Move exception handling inside the log context block so both success and failure paths are captured consistently. [incomplete implementation]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Failed chart restores missing action in central audit log.
- ⚠️ Weakens ability to investigate MCP restore misuse.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Note the established audit pattern in the delete tool: in `delete_chart()`
(superset/mcp_service/chart/tool/delete_chart.py:124-127) the `try/except` block is placed
inside `with event_logger.log_context(action="mcp.delete_chart")`, and the comment
explicitly states “the context manager does not log when an exception propagates through
it”, so failures are handled inside the context to ensure logging.
2. Start the Superset MCP service and call `restore_chart()`
(superset/mcp_service/chart/tool/restore_chart.py:85-104) as a user who is not an editor
of the target soft-deleted chart, so `RestoreChartCommand.run()` will raise
`ChartForbiddenError` after `security_manager.raise_for_editorship()` in
`BaseRestoreCommand.validate()` (superset/commands/restore.py:76-103).
3. Observe the restore implementation at
`superset/mcp_service/chart/tool/restore_chart.py:137-149`: the `try:` wraps the `with
event_logger.log_context(action="mcp.restore_chart")` block and the subsequent success
return, while the `except ChartForbiddenError` and other `except` clauses (lines 150-167)
live outside the `with` block.
4. When `RestoreChartCommand(str(chart.uuid)).run()` raises `ChartForbiddenError`, the
exception propagates out of `event_logger.log_context(...)` before being caught by the
outer `except`, matching the delete-tool comment that the context manager does not log on
exceptions; as a result, forbidden/failed restore attempts are handled and surfaced to the
client but the central `event_logger` audit trail does not record a `mcp.restore_chart`
failure event.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d8ba9b5b2539498db6b44c71d2e9a989&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=d8ba9b5b2539498db6b44c71d2e9a989&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:** 137:141
**Comment:**
*Incomplete Implementation: The command execution is inside `event_logger.log_context`, but the `try/except` is outside it, so failed restore attempts exit the context by exception and are not reliably audited. Move exception handling inside the log context block so both success and failure paths are captured 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=c22c3b06d78457afc33b1174dd8dcbc94b7853a69c494d2aaea93f38725a6280&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=c22c3b06d78457afc33b1174dd8dcbc94b7853a69c494d2aaea93f38725a6280&reaction=dislike'>👎</a>
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,177 @@
+# 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.
+
+ Both bypasses mirror ``BaseRestoreCommand.validate``'s own lookup:
+ ``skip_visibility_filter`` unhides the soft-deleted row, and
+ ``skip_base_filter`` keeps an editor's own trash reachable even when the
+ entity's RBAC base_filter has no editorship leg (a lost grant must not
+ hide a row from the one audience that can restore it). The restore
+ audience is enforced by ``RestoreChartCommand`` via
+ ``raise_for_editorship``.
+ """
+ from superset.daos.chart import ChartDAO
+
+ return ChartDAO.find_by_id_or_uuid(
+ str(identifier),
+ skip_base_filter=True,
+ skip_visibility_filter=True,
+ )
Review Comment:
**Suggestion:** The pre-lookup disables the DAO `base_filter`, which lets the tool resolve charts that should remain hidden by RBAC visibility rules and can leak their existence/title via `NotDeleted` or `Forbidden` responses before the command layer runs. Keep `base_filter` enabled in this pre-lookup and only bypass visibility filtering for soft-deleted rows. [security]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ MCP restore_chart leaks names of RBAC-hidden charts.
- ⚠️ Undermines dashboard/chart RBAC visibility guarantees for MCP clients.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Start the Superset MCP service so chart tools are available; tools are wired via
`create_mcp_app()` in `superset/mcp_service/app.py:602`, which includes `restore_chart()`
from `superset/mcp_service/chart/tool/restore_chart.py:85`.
2. Create a chart that is hidden from the caller by RBAC base filtering, e.g. via
`ChartDAO.base_filter = ChartFilter` in `superset/daos/chart.py:45-47` so
`ChartDAO.find_by_id_or_uuid()` normally scopes results to permitted datasources.
3. As an MCP client user who has Chart class permission but lacks editorship/datasource
access to that chart, call the `restore_chart()` tool
(superset/mcp_service/chart/tool/restore_chart.py:85-104) with `request.identifier` set to
the chart’s numeric ID or UUID.
4. Inside `restore_chart()`, helper `_find_chart_for_restore()`
(superset/mcp_service/chart/tool/restore_chart.py:47-64) calls
`ChartDAO.find_by_id_or_uuid(str(identifier), skip_base_filter=True,
skip_visibility_filter=True)` (BaseDAO implementation at `superset/daos/base.py:229-245`),
resolving the RBAC-hidden chart; subsequent checks at `restore_chart.py:128-135`
(“NotDeleted” path) and error handling at `restore_chart.py:150-159` (“Forbidden” path)
include `chart.slice_name` and `chart.id` in tool responses, disclosing the existence/name
of charts that base_filter would normally hide from this user.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=4673099de8d64724a9cf9aec5ec73ad9&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=4673099de8d64724a9cf9aec5ec73ad9&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:** 60:64
**Comment:**
*Security: The pre-lookup disables the DAO `base_filter`, which lets the tool resolve charts that should remain hidden by RBAC visibility rules and can leak their existence/title via `NotDeleted` or `Forbidden` responses before the command layer runs. Keep `base_filter` enabled in this pre-lookup and only bypass visibility filtering for soft-deleted rows.
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=4b52a08930ff3d3bc4d88b3d40af2f66d0db0ef33b650f00ca6d539806905168&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=4b52a08930ff3d3bc4d88b3d40af2f66d0db0ef33b650f00ca6d539806905168&reaction=dislike'>👎</a>
##########
superset/mcp_service/dashboard/tool/restore_dashboard.py:
##########
@@ -0,0 +1,185 @@
+# 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.
+
+ Both bypasses mirror ``BaseRestoreCommand.validate``'s own lookup:
+ ``skip_visibility_filter`` unhides the soft-deleted row, and
+ ``skip_base_filter`` keeps an editor's own trash reachable even when the
+ entity's RBAC base_filter has no editorship leg (a lost grant must not
+ hide a row from the one audience that can restore it). The restore
+ audience is enforced by ``RestoreDashboardCommand`` via
+ ``raise_for_editorship``.
+ """
+ from superset.daos.dashboard import DashboardDAO
+
+ return DashboardDAO.find_by_id_or_uuid(
+ str(identifier),
+ skip_base_filter=True,
+ 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 be an editor of the dashboard (owners and Admins qualify).
+
+ 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,))
+
+ try:
+ dashboard = _find_dashboard_for_restore(request.identifier)
+ except SQLAlchemyError:
+ _rollback()
+ logger.exception("Dashboard lookup failed during restore_dashboard")
+ return RestoreDashboardResponse(
+ success=False,
+ error="Dashboard lookup failed due to a database error.",
+ error_type="LookupFailed",
+ )
+ if not dashboard:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No dashboard found with identifier: {safe_id}."
+ return RestoreDashboardResponse(success=False, error=msg, error_type="NotFound")
+
+ dashboard_id = dashboard.id
+ # Dashboard titles are user-controlled; wrap before composing response
+ # text so a hostile title cannot inject prompt content into the output.
+ dashboard_name = sanitize_for_llm_context(
+ dashboard.dashboard_title, field_path=("dashboard_title",)
+ )
+
+ if dashboard.deleted_at is None:
+ return RestoreDashboardResponse(
+ success=False,
+ error=(
+ f"Dashboard '{dashboard_name}' (id={dashboard_id}) is not in "
+ "trash; nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.dashboard.restore import RestoreDashboardCommand
+
+ with event_logger.log_context(action="mcp.restore_dashboard"):
+ RestoreDashboardCommand(str(dashboard.uuid)).run()
Review Comment:
**Suggestion:** The `try/except` wraps the `with event_logger.log_context(...)` block, which means exceptions from restore can propagate through the context manager before being handled and may skip failure audit logging. Mirror the established delete-tool pattern by placing exception handling inside the logging context. [incomplete implementation]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Failed dashboard restores missing entries in audit trail.
- ⚠️ Hampers forensic analysis of MCP dashboard restore misuse.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Compare the established delete-tool pattern: in `delete_dashboard()`
(superset/mcp_service/dashboard/tool/delete_dashboard.py:165-169) the `try/except` block
is placed inside `with event_logger.log_context(action="mcp.delete_dashboard")`, with a
comment noting that the context manager does not log when an exception propagates through
it, so failures are handled inside the context to guarantee audit logging.
2. Start the Superset MCP service and call `restore_dashboard()`
(superset/mcp_service/dashboard/tool/restore_dashboard.py:87-106) as a user who is not an
editor of the soft-deleted dashboard, so `RestoreDashboardCommand.run()` ultimately raises
`DashboardForbiddenError` via `security_manager.raise_for_editorship()` in
`BaseRestoreCommand.validate()` (superset/commands/restore.py:76-103).
3. Inspect the restore implementation at
`superset/mcp_service/dashboard/tool/restore_dashboard.py:141-171`: the outer `try:` wraps
the `with event_logger.log_context(action="mcp.restore_dashboard")` block and the success
return, while the `except DashboardForbiddenError`, `except DashboardNotFoundError`, and
generic `except (CommandException, SQLAlchemyError, ValueError)` handlers (lines 155-172)
reside outside the `with` block.
4. When `RestoreDashboardCommand(str(dashboard.uuid)).run()` raises
`DashboardForbiddenError` or another error, the exception leaves
`event_logger.log_context(...)` before being caught by the outer `except`, matching the
delete-tool comment about missing logs on propagated exceptions; as a result, failed or
forbidden dashboard restore attempts are surfaced to the client but do not produce a
corresponding `mcp.restore_dashboard` event in the central audit log, reducing visibility
into restore failures compared to delete operations.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=19a1f4c3a5e247da9c1844fd372593cf&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=19a1f4c3a5e247da9c1844fd372593cf&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:** 141:145
**Comment:**
*Incomplete Implementation: The `try/except` wraps the `with event_logger.log_context(...)` block, which means exceptions from restore can propagate through the context manager before being handled and may skip failure audit logging. Mirror the established delete-tool pattern by placing exception handling inside the logging context.
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=ffd102e5339d94861ac667ee1b99d94566980f2f13d829040c01c89e69b425ff&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=ffd102e5339d94861ac667ee1b99d94566980f2f13d829040c01c89e69b425ff&reaction=dislike'>👎</a>
##########
superset/mcp_service/dashboard/tool/restore_dashboard.py:
##########
@@ -0,0 +1,185 @@
+# 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.
+
+ Both bypasses mirror ``BaseRestoreCommand.validate``'s own lookup:
+ ``skip_visibility_filter`` unhides the soft-deleted row, and
+ ``skip_base_filter`` keeps an editor's own trash reachable even when the
+ entity's RBAC base_filter has no editorship leg (a lost grant must not
+ hide a row from the one audience that can restore it). The restore
+ audience is enforced by ``RestoreDashboardCommand`` via
+ ``raise_for_editorship``.
+ """
+ from superset.daos.dashboard import DashboardDAO
+
+ return DashboardDAO.find_by_id_or_uuid(
+ str(identifier),
+ skip_base_filter=True,
+ skip_visibility_filter=True,
+ )
Review Comment:
**Suggestion:** The restore pre-lookup bypasses `base_filter`, so dashboards hidden by normal DAO scoping can still be resolved and partially disclosed in tool errors/messages. Keep `base_filter` active and only skip visibility filtering needed to see soft-deleted rows. [security]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ MCP restore_dashboard leaks titles of RBAC-hidden dashboards.
- ⚠️ Bypasses dashboard base_filter visibility gate for MCP callers.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Start the Superset MCP service so dashboard tools are available; tools are wired via
`create_mcp_app()` in `superset/mcp_service/app.py:602`, which includes
`restore_dashboard()` from `superset/mcp_service/dashboard/tool/restore_dashboard.py:87`.
2. Ensure a dashboard exists that is hidden from the caller by `DashboardDAO.base_filter =
DashboardAccessFilter` (superset/daos/dashboard.py:60-61), so standard DAO lookups respect
RBAC scoping and the user cannot see it via normal list/get APIs.
3. As an MCP client user with Dashboard class permission but without editorship or view
access to that dashboard, call the `restore_dashboard()` tool
(superset/mcp_service/dashboard/tool/restore_dashboard.py:87-106) with
`request.identifier` set to that dashboard’s numeric ID or UUID.
4. Inside `restore_dashboard()`, helper `_find_dashboard_for_restore()`
(superset/mcp_service/dashboard/tool/restore_dashboard.py:48-64) invokes
`DashboardDAO.find_by_id_or_uuid(str(identifier), skip_base_filter=True,
skip_visibility_filter=True)` (BaseDAO implementation at `superset/daos/base.py:229-245`),
bypassing the RBAC base_filter and resolving the hidden dashboard; subsequent logic at
`restore_dashboard.py:131-138` (“NotDeleted” error) and forbidden handling at
`restore_dashboard.py:156-166` includes the sanitized title and id in responses,
disclosing the existence/title of dashboards that the base_filter is designed to keep
invisible to this caller.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=a287a79e619c45259c8770ef695671f1&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=a287a79e619c45259c8770ef695671f1&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:** 60:64
**Comment:**
*Security: The restore pre-lookup bypasses `base_filter`, so dashboards hidden by normal DAO scoping can still be resolved and partially disclosed in tool errors/messages. Keep `base_filter` active and only skip visibility filtering needed to see soft-deleted rows.
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=7b5a0f9c00c37b848994b02662c2801bcac1729d5f491621ff0533ab0fb6cd71&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=7b5a0f9c00c37b848994b02662c2801bcac1729d5f491621ff0533ab0fb6cd71&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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #41842:
URL: https://github.com/apache/superset/pull/41842#issuecomment-4907867546
Lots of bot comments here to assess/address/refute/resolve, if you don't mind sorting them out.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas merged PR #41842:
URL: https://github.com/apache/superset/pull/41842
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3565449476
##########
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__)
Review Comment:
Declining, standing rationale: module-level logger/string constants and locals with inferable types are unannotated across this codebase's mcp_service modules and test suites; mypy passes. Identical future findings will be declined the same way.
##########
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__)
Review Comment:
Declining, standing rationale: module-level logger/string constants and locals with inferable types are unannotated across this codebase's mcp_service modules and test suites; mypy passes. Identical future findings will be declined the same way.
##########
tests/unit_tests/mcp_service/chart/tool/test_restore_chart.py:
##########
@@ -0,0 +1,183 @@
+# 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.
+
+"""Unit tests for the restore_chart MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other chart tool test files.
+"""
+
+from collections.abc import Iterator
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
Review Comment:
Declining, standing rationale: module-level logger/string constants and locals with inferable types are unannotated across this codebase's mcp_service modules and test suites; mypy passes. Identical future findings will be declined the same way.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3533161838
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,148 @@
+# 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
+
+logger = logging.getLogger(__name__)
Review Comment:
**Suggestion:** Add an explicit type annotation to the module logger variable to satisfy the type-hint requirement for relevant variables. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The new Python file defines a module-level logger without a type annotation. Since this is a relevant variable that can be annotated, it matches the type-hint requirement violation.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=351b4e787e424491a6a22031c861a9ac&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=351b4e787e424491a6a22031c861a9ac&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:** 41:41
**Comment:**
*Custom Rule: Add an explicit type annotation to the module logger variable to satisfy the type-hint requirement for relevant variables.
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=fb0b5ebbcf509ff48d8757b7539e17aba83acbc358a77e2a711a568b6b8a80cb&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=fb0b5ebbcf509ff48d8757b7539e17aba83acbc358a77e2a711a568b6b8a80cb&reaction=dislike'>👎</a>
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,148 @@
+# 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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No chart found with identifier: {safe_id}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ chart_name = chart.slice_name
Review Comment:
**Suggestion:** Add explicit type annotations for key local variables derived from dynamically typed objects so their types are not left implicit. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The new code introduces local variables derived from a dynamically typed object without annotations. These variables can be explicitly typed, so this is a real omission under the type-hint rule.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=40956635b0764396b5ed524d63a2b90e&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=40956635b0764396b5ed524d63a2b90e&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:** 95:102
**Comment:**
*Custom Rule: Add explicit type annotations for key local variables derived from dynamically typed objects so their types are not left implicit.
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=3dd49d9954d54ec9e45f16c64e40df9de7295a40931f05e8fc8a5c5e7a5c2868&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=3dd49d9954d54ec9e45f16c64e40df9de7295a40931f05e8fc8a5c5e7a5c2868&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/chart/tool/test_restore_chart.py:
##########
@@ -0,0 +1,182 @@
+# 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.
+
+"""Unit tests for the restore_chart MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other chart tool test files.
+"""
+
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.chart.ChartDAO.find_by_id_or_uuid"
+_COMMAND = "superset.commands.chart.restore.RestoreChartCommand"
+
+_UUID = UUID("11111111-2222-3333-4444-555555555555")
+
+
+@pytest.fixture
+def mcp_server() -> object:
+ return mcp
+
+
+@pytest.fixture(autouse=True)
+def mock_auth():
+ with patch("superset.mcp_service.auth.get_user_from_request") as mock_get_user:
+ mock_user = Mock()
+ mock_user.id = 1
+ mock_user.username = "admin"
+ mock_get_user.return_value = mock_user
+ yield mock_get_user
Review Comment:
**Suggestion:** Add an explicit return type hint to this fixture function (for example, an iterator/generator type) to comply with the required typing rule. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The fixture function `mock_auth` is newly added Python code and omits a return type hint, which violates the required typing rule for functions that can be annotated.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=af833d0719ed4571966cd05298e2b670&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=af833d0719ed4571966cd05298e2b670&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:** tests/unit_tests/mcp_service/chart/tool/test_restore_chart.py
**Line:** 44:51
**Comment:**
*Custom Rule: Add an explicit return type hint to this fixture function (for example, an iterator/generator type) to comply with the required typing rule.
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=66dc92a42060863f51cea782b0f81950a8198a21f04b86fd1a160f09894b507f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=66dc92a42060863f51cea782b0f81950a8198a21f04b86fd1a160f09894b507f&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/dashboard/tool/test_restore_dashboard.py:
##########
@@ -0,0 +1,184 @@
+# 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.
+
+"""Unit tests for the restore_dashboard MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other dashboard tool test files.
+"""
+
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.dashboard.DashboardDAO.find_by_id_or_uuid"
+_COMMAND = "superset.commands.dashboard.restore.RestoreDashboardCommand"
+
+_UUID = UUID("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")
+
+
+@pytest.fixture
+def mcp_server() -> object:
+ return mcp
+
+
+@pytest.fixture(autouse=True)
+def mock_auth():
+ with patch("superset.mcp_service.auth.get_user_from_request") as mock_get_user:
+ mock_user = Mock()
+ mock_user.id = 1
+ mock_user.username = "admin"
+ mock_get_user.return_value = mock_user
+ yield mock_get_user
Review Comment:
**Suggestion:** Add an explicit return type annotation to this fixture function (for example a generator/iterator type) to satisfy the project requirement for Python type hints on functions. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The rule requires type hints on newly added Python functions when they can be annotated. This fixture is defined without any return type annotation, so the suggestion correctly identifies a real violation.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=be68fb2d76ba474ab2a11f2d6f6fe7cc&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=be68fb2d76ba474ab2a11f2d6f6fe7cc&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:** tests/unit_tests/mcp_service/dashboard/tool/test_restore_dashboard.py
**Line:** 44:51
**Comment:**
*Custom Rule: Add an explicit return type annotation to this fixture function (for example a generator/iterator type) to satisfy the project requirement for Python type hints on functions.
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=3e0f769ac998147aa51fbf94675d2eaebec6409f821653f70dc93e97a404f9d9&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=3e0f769ac998147aa51fbf94675d2eaebec6409f821653f70dc93e97a404f9d9&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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #41842:
URL: https://github.com/apache/superset/pull/41842#issuecomment-4899498923
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3574252502
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,169 @@
+# 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)
Review Comment:
MEDIUM: this pre-lookup keeps `base_filter` enabled (only `skip_visibility_filter=True` is passed), but the canonical command it delegates to, `BaseRestoreCommand.validate()` (`superset/commands/restore.py:86-91`), passes `skip_base_filter=True` **and** `skip_visibility_filter=True` by explicit design — its own docstring says this keeps "an editor's own trash reachable even when the entity's RBAC base_filter has no editorship leg... a lost grant must not hide a row from the one audience that can restore it."
codeant raised a version of this; the author declined citing "base_filter intact" in the command's own lookup, but that's not what `superset/commands/restore.py` does at this HEAD. Net effect: an editor whose current `base_filter` access lapsed (e.g. lost datasource grant, but still owns/can-edit the chart) gets a false `NotFound` from this pre-check, even though `RestoreChartCommand` would let them restore it. Not a security escalation (over-restrictive, not under-restrictive) but worth aligning — suggest passing `skip_base_filter=True` here to match the command's own semantics.
##########
tests/unit_tests/mcp_service/chart/tool/test_restore_chart.py:
##########
@@ -0,0 +1,208 @@
+# 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.
+
+"""Unit tests for the restore_chart MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other chart tool test files.
+"""
+
+from collections.abc import Iterator
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.chart.ChartDAO.find_by_id_or_uuid"
Review Comment:
MEDIUM: no test exercises the `LookupFailed` branch (`restore_chart.py:99-108`) — the try/except wrapping `_find_chart_for_restore` that was added specifically to fix codeant's "DB failure during find_by_id_or_uuid bubbles out uncaught" thread. The fix landed at this HEAD but shipped without a regression test (mock `_FIND` to raise `SQLAlchemyError`/`OperationalError` and assert `error_type == "LookupFailed"`).
##########
tests/unit_tests/mcp_service/dashboard/tool/test_restore_dashboard.py:
##########
@@ -0,0 +1,185 @@
+# 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.
+
+"""Unit tests for the restore_dashboard MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other dashboard tool test files.
+"""
+
+from collections.abc import Iterator
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.dashboard.DashboardDAO.find_by_id_or_uuid"
Review Comment:
MEDIUM: two coverage gaps here — (a) no `SQLAlchemyError`-masking test, unlike the chart sibling's `test_restore_chart_sqlalchemy_error_is_generic` (same hardening was applied at `restore_dashboard.py:164-177`); (b) no test for `DashboardSlugConflictError` (`superset/commands/dashboard/restore.py:47-64`) — the one dashboard-specific restore rule beyond the shared base class (slug reclaimed by another active dashboard while this one was trashed), which falls through to the generic `except (CommandException, ...)` branch at `restore_dashboard.py:164` untested.
##########
superset/mcp_service/dashboard/tool/restore_dashboard.py:
##########
@@ -0,0 +1,177 @@
+# 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)
Review Comment:
MEDIUM: same issue as the chart tool's pre-lookup — `base_filter` stays enabled here, but `BaseRestoreCommand.validate()` (`superset/commands/restore.py:86-91`) bypasses it (`skip_base_filter=True`) by design so an editor's own trash stays reachable even if their base_filter access lapsed. This pre-lookup being stricter than the command it wraps can produce a false `NotFound` for a legitimate editor. Suggest passing `skip_base_filter=True` to match.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #41842:
URL: https://github.com/apache/superset/pull/41842#issuecomment-4911686572
**Bito Automatic Review Failed - Technical Failure** <br/><br/> Bito encountered technical difficulties while generating code feedback . To retry, type `/review` in a comment and save. If the issue persists, contact support@bito.ai and provide the following details: <br/><br/>Agent Run ID: b4325210-4978-4857-9db1-269d16d1b7ad
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3565416330
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,154 @@
+# 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)
Review Comment:
**Suggestion:** The pre-lookup keeps the DAO base filter enabled, which can hide a soft-deleted chart from users who are still valid editors; `RestoreChartCommand` intentionally bypasses the base filter to allow exactly that restore path. This causes false `NotFound` responses before authorization/restore logic runs. Align this lookup with command semantics by bypassing the base filter for restore resolution. [api mismatch]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
❌ MCP restore_chart wrongly reports NotFound for editable charts.
⚠️ Prevents soft-deleted chart recovery via MCP clients.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Start the MCP FastMCP server via `init_fastmcp_server()` in
`superset/mcp_service/app.py:940`, which registers the `restore_chart()` tool defined in
`superset/mcp_service/chart/tool/restore_chart.py:77-96`.
2. As a user who is an editor of a chart but whose dataset access has been revoked by
RBAC, soft-delete the chart using the `delete_chart()` MCP tool in
`superset/mcp_service/chart/tool/delete_chart.py:78-147`, which routes to `BaseDAO.delete`
and sets `deleted_at` on the chart row.
3. From a FastMCP client, call the `restore_chart` MCP tool with that chart’s numeric ID
or UUID; this invokes `_find_chart_for_restore()` in
`superset/mcp_service/chart/tool/restore_chart.py:47-56`, which calls
`ChartDAO.find_by_id_or_uuid(str(identifier), skip_visibility_filter=True)` while still
applying the `ChartDAO.base_filter = ChartFilter` declared at
`superset/daos/chart.py:45-47`.
4. In contrast, `BaseRestoreCommand.validate()` in `superset/commands/restore.py:76-91`
uses `self.dao.find_by_id(..., id_column="uuid", skip_base_filter=True,
skip_visibility_filter=True)` specifically to bypass the base filter for editors’ trash;
because `_find_chart_for_restore` does not set `skip_base_filter=True`, the chart row is
hidden by `ChartFilter` and `restore_chart()` returns a `RestoreChartResponse` with
`success=False` and `error_type="NotFound"` before `RestoreChartCommand` or ownership
checks run, incorrectly blocking a legitimate restore.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=18b9c221cc4344a6b308eb73df10f051&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=18b9c221cc4344a6b308eb73df10f051&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:** 56:56
**Comment:**
*Api Mismatch: The pre-lookup keeps the DAO base filter enabled, which can hide a soft-deleted chart from users who are still valid editors; `RestoreChartCommand` intentionally bypasses the base filter to allow exactly that restore path. This causes false `NotFound` responses before authorization/restore logic runs. Align this lookup with command semantics by bypassing the base filter for restore resolution.
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=66462f0f2b73d58275481d728ac9c2ee59d9162c8d17978506fe547080aa347f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=66462f0f2b73d58275481d728ac9c2ee59d9162c8d17978506fe547080aa347f&reaction=dislike'>👎</a>
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,154 @@
+# 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 be an editor of the chart (owners and
+ Admins qualify).
+
+ 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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No chart found with identifier: {safe_id}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ # Chart names are user-controlled; wrap before composing response text so
+ # a hostile name cannot inject prompt content into the tool output.
+ chart_name = sanitize_for_llm_context(chart.slice_name, field_path=("slice_name",))
+
+ if chart.deleted_at is None:
+ return RestoreChartResponse(
+ success=False,
+ error=(
+ f"Chart '{chart_name}' (id={chart_id}) is not in trash; "
+ "nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.chart.restore import RestoreChartCommand
+
+ with event_logger.log_context(action="mcp.restore_chart"):
+ RestoreChartCommand(str(chart.uuid)).run()
+
+ return RestoreChartResponse(
+ success=True,
+ restored_id=chart_id,
+ restored_name=chart_name,
+ message=f"Restored chart '{chart_name}' (id={chart_id}) from trash.",
+ )
+ except ChartForbiddenError:
+ await ctx.warning("Permission denied restoring chart id=%s" % (chart_id,))
+ return RestoreChartResponse(
+ success=False,
+ permission_denied=True,
+ error=(
+ f"You do not have permission to restore chart '{chart_name}' "
+ f"(id={chart_id}). Ask the user to restore it or grant access; "
+ "do not retry."
+ ),
+ error_type="Forbidden",
+ )
+ except ChartNotFoundError:
+ msg = f"Chart id={chart_id} is no longer restorable."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+ except (CommandException, SQLAlchemyError, ValueError) as ex:
+ _rollback()
+ await ctx.error("Chart restore failed: %s: %s" % (type(ex).__name__, ex))
+ return RestoreChartResponse(
+ success=False,
+ error=f"Chart restore failed: {ex}",
+ error_type=type(ex).__name__,
+ )
Review Comment:
**Suggestion:** This returns raw `SQLAlchemyError` text to clients, which can leak SQL/query/connection internals. Other mutate tools in this code path already mask DB exceptions with a generic message, and restore should do the same for consistency and security. [security]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
⚠️ MCP restore_chart leaks SQLAlchemyError details to clients.
⚠️ Exposes database internals in LLM tool responses.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Invoke the `restore_chart` MCP tool from a FastMCP client; this calls `restore_chart()`
in `superset/mcp_service/chart/tool/restore_chart.py:77-154` after the server is created
by `create_mcp_app()` in `superset/mcp_service/app.py:602`.
2. During the `try` block at `restore_chart.py:120-125`, where `with
event_logger.log_context(action="mcp.restore_chart"):` wraps
`RestoreChartCommand(str(chart.uuid)).run()`, induce a database failure so that the
command or transaction raises `SQLAlchemyError` (e.g., misconfigured DB, connection
issue).
3. The exception is caught by the `except (CommandException, SQLAlchemyError, ValueError)
as ex:` handler at `restore_chart.py:147-154`, which calls `_rollback()` at
`restore_chart.py:59-66` and logs `await ctx.error("Chart restore failed: %s: %s" %
(type(ex).__name__, ex))`.
4. The handler then returns `RestoreChartResponse(success=False, error=f"Chart restore
failed: {ex}", error_type=type(ex).__name__)`, exposing the raw `SQLAlchemyError` string
to the MCP client, whereas the delete path in
`superset/mcp_service/chart/tool/delete_chart.py:173-185` explicitly masks
`SQLAlchemyError` as `"Chart delete failed due to a database error."`, demonstrating that
restore currently leaks more internal DB detail than other mutate tools.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=c42bcc964d9445fca593358ef534dab0&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=c42bcc964d9445fca593358ef534dab0&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:** 147:154
**Comment:**
*Security: This returns raw `SQLAlchemyError` text to clients, which can leak SQL/query/connection internals. Other mutate tools in this code path already mask DB exceptions with a generic message, and restore should do the same for consistency and security.
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=fcbeb0c539e703d2a47677a51de91b70f1944f36161bfece3f69da793fee059c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=fcbeb0c539e703d2a47677a51de91b70f1944f36161bfece3f69da793fee059c&reaction=dislike'>👎</a>
##########
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)
Review Comment:
**Suggestion:** The pre-lookup keeps the DAO base filter enabled, but the restore command is designed to bypass that filter so editors can restore their own soft-deleted dashboards even when visibility filters would hide them. Returning `NotFound` from this pre-check can therefore reject legitimate restores. Use the same base-filter bypass semantics as the restore command. [api mismatch]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
❌ MCP restore_dashboard misreports NotFound for editable dashboards.
⚠️ Blocks soft-deleted dashboard recovery via MCP clients.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Run the MCP FastMCP server so that dashboard tools, including `restore_dashboard()` in
`superset/mcp_service/dashboard/tool/restore_dashboard.py:79-162`, are registered by
`create_mcp_app()` in `superset/mcp_service/app.py:602`.
2. Soft-delete a dashboard (e.g., via the `delete_dashboard()` MCP tool in
`superset/mcp_service/dashboard/tool/delete_dashboard.py:102-192`, which routes to
`BaseDAO.delete` and sets `deleted_at`) while the user remains an editor but later loses
dashboard visibility through `DashboardAccessFilter` (`DashboardDAO.base_filter =
DashboardAccessFilter` at `superset/daos/dashboard.py:60-62`).
3. From a FastMCP client, call the `restore_dashboard` tool with the dashboard’s
identifier; this invokes `_find_dashboard_for_restore()` at
`superset/mcp_service/dashboard/tool/restore_dashboard.py:47-56`, which calls
`DashboardDAO.find_by_id_or_uuid(str(identifier), skip_visibility_filter=True)` and still
applies the base filter.
4. Meanwhile, `BaseRestoreCommand.validate()` used by `RestoreDashboardCommand` in
`superset/commands/restore.py:76-91` deliberately performs a lookup with
`skip_base_filter=True, skip_visibility_filter=True` so editors can see their own trash;
because `_find_dashboard_for_restore` leaves `skip_base_filter` as False, the soft-deleted
dashboard can be hidden by `DashboardAccessFilter`, causing `restore_dashboard()` to
return `RestoreDashboardResponse(success=False, error_type="NotFound")` without ever
invoking `RestoreDashboardCommand` or ownership checks, denying legitimate restores for
editors.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ea01d32f597d490ba79e2340520bdb80&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=ea01d32f597d490ba79e2340520bdb80&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:** 56:56
**Comment:**
*Api Mismatch: The pre-lookup keeps the DAO base filter enabled, but the restore command is designed to bypass that filter so editors can restore their own soft-deleted dashboards even when visibility filters would hide them. Returning `NotFound` from this pre-check can therefore reject legitimate restores. Use the same base-filter bypass semantics as the restore command.
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=fea709783f0cbdc6c5b2a3ed1dbb80d55f4bbd2ae2cb00b027a42849b18b3ee4&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=fea709783f0cbdc6c5b2a3ed1dbb80d55f4bbd2ae2cb00b027a42849b18b3ee4&reaction=dislike'>👎</a>
##########
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 be an editor of the dashboard (owners and Admins qualify).
+
+ 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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No dashboard found with identifier: {safe_id}."
+ return RestoreDashboardResponse(success=False, error=msg, error_type="NotFound")
+
+ dashboard_id = dashboard.id
+ # Dashboard titles are user-controlled; wrap before composing response
+ # text so a hostile title cannot inject prompt content into the output.
+ dashboard_name = sanitize_for_llm_context(
+ dashboard.dashboard_title, field_path=("dashboard_title",)
+ )
+
+ if dashboard.deleted_at is None:
+ return RestoreDashboardResponse(
+ success=False,
+ error=(
+ f"Dashboard '{dashboard_name}' (id={dashboard_id}) is not in "
+ "trash; nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.dashboard.restore import RestoreDashboardCommand
+
+ with event_logger.log_context(action="mcp.restore_dashboard"):
+ RestoreDashboardCommand(str(dashboard.uuid)).run()
+
+ return RestoreDashboardResponse(
+ success=True,
+ restored_id=dashboard_id,
+ restored_name=dashboard_name,
+ message=(
+ f"Restored dashboard '{dashboard_name}' (id={dashboard_id}) from trash."
+ ),
+ )
+ except DashboardForbiddenError:
+ await ctx.warning(
+ "Permission denied restoring dashboard id=%s" % (dashboard_id,)
+ )
+ return RestoreDashboardResponse(
+ success=False,
+ permission_denied=True,
+ error=(
+ f"You do not have permission to restore dashboard "
+ f"'{dashboard_name}' (id={dashboard_id}). Ask the user to "
+ "restore it or grant access; do not retry."
+ ),
+ error_type="Forbidden",
+ )
+ except DashboardNotFoundError:
+ msg = f"Dashboard id={dashboard_id} is no longer restorable."
+ return RestoreDashboardResponse(success=False, error=msg, error_type="NotFound")
+ except (CommandException, SQLAlchemyError, ValueError) as ex:
+ _rollback()
+ await ctx.error("Dashboard restore failed: %s: %s" % (type(ex).__name__, ex))
+ return RestoreDashboardResponse(
+ success=False,
+ error=f"Dashboard restore failed: {ex}",
+ error_type=type(ex).__name__,
Review Comment:
**Suggestion:** This response includes raw database exception details, which can disclose internal SQL/DB information. Mirror the delete-tool pattern by returning a generic message for SQLAlchemy failures while keeping detailed logs server-side. [security]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
⚠️ MCP restore_dashboard returns raw SQLAlchemy errors to callers.
⚠️ Reveals database/internal state in tool error messages.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Call the `restore_dashboard` MCP tool from a FastMCP client; this executes
`restore_dashboard()` in `superset/mcp_service/dashboard/tool/restore_dashboard.py:79-162`
after tool registration in `superset/mcp_service/app.py:602`.
2. Cause a database error during `RestoreDashboardCommand(str(dashboard.uuid)).run()`
inside the `with event_logger.log_context(action="mcp.restore_dashboard"):` block at
`restore_dashboard.py:124-128` (for example, a failing transaction or invalid SQL that
surfaces as `SQLAlchemyError`).
3. The error is caught by the `except (CommandException, SQLAlchemyError, ValueError) as
ex:` handler at `restore_dashboard.py:155-161`, which calls `_rollback()`
(`restore_dashboard.py:59-67`) and logs `await ctx.error("Dashboard restore failed: %s:
%s" % (type(ex).__name__, ex))`.
4. The handler then returns `RestoreDashboardResponse(success=False, error=f"Dashboard
restore failed: {ex}", error_type=type(ex).__name__)`, exposing the raw `SQLAlchemyError`
text to the MCP client, unlike `delete_dashboard()` in
`superset/mcp_service/dashboard/tool/delete_dashboard.py:222-235`, where SQLAlchemy errors
are mapped to the generic message `"Dashboard delete failed due to a database error."` to
avoid leaking DB internals.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=a038318e6c9a485383d33033f7e2b11f&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=a038318e6c9a485383d33033f7e2b11f&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:** 155:161
**Comment:**
*Security: This response includes raw database exception details, which can disclose internal SQL/DB information. Mirror the delete-tool pattern by returning a generic message for SQLAlchemy failures while keeping detailed logs server-side.
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=fdecc2b3e02257100bcae99ebc853b3e6aa5461dcc5f0620de48f344b12811ff&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=fdecc2b3e02257100bcae99ebc853b3e6aa5461dcc5f0620de48f344b12811ff&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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3565409832
##########
tests/unit_tests/mcp_service/chart/tool/test_restore_chart.py:
##########
@@ -0,0 +1,183 @@
+# 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.
+
+"""Unit tests for the restore_chart MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other chart tool test files.
+"""
+
+from collections.abc import Iterator
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
Review Comment:
**Suggestion:** Add an explicit type annotation to this module-level constant string. [custom_rule]
**Severity Level:** Minor 🧹
<details>
<summary><b>Why it matters? ⭐ </b></summary>
The custom rule requires type hints on relevant variables that can be annotated. This module-level string constant is unannotated and could be written as `str`, so the suggestion identifies a real rule violation.
</details>
<details>
<summary><b>Rule source 📖 </b></summary>
.cursor/rules/dev-standard.mdc (line 28)
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=11f89f00a97f4c7fbcc39f0e1ec96a95&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=11f89f00a97f4c7fbcc39f0e1ec96a95&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:** tests/unit_tests/mcp_service/chart/tool/test_restore_chart.py
**Line:** 33:33
**Comment:**
*Custom Rule: Add an explicit type annotation to this module-level constant string.
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=20c2a19312866ffa23c0982d058a8f022b360bee2e8517f96f4661e3a8b23d27&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=20c2a19312866ffa23c0982d058a8f022b360bee2e8517f96f4661e3a8b23d27&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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #41842:
URL: https://github.com/apache/superset/pull/41842#issuecomment-4949982624
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3565449916
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,154 @@
+# 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)
Review Comment:
✅ **Customized review instruction saved!**
**Instruction:**
> For chart restore resolution in this tool, keep the DAO base_filter enabled in the pre-lookup so behavior mirrors BaseRestoreCommand.validate and preserves the live-UI visibility gate before authorization.
**Applied to:**
- `superset/mcp_service/chart/tool/restore_chart.py`
---
💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*
##########
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)
Review Comment:
✅ **Customized review instruction saved!**
**Instruction:**
> In dashboard restore tools, keep the pre-lookup aligned with BaseRestoreCommand.validate: do not bypass the base filter, and do not surface dashboards hidden from the live UI before the command’s ownership check runs.
**Applied to:**
- `superset/mcp_service/dashboard/tool/**`
---
💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*
##########
tests/unit_tests/mcp_service/dashboard/tool/test_restore_dashboard.py:
##########
@@ -0,0 +1,185 @@
+# 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.
+
+"""Unit tests for the restore_dashboard MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other dashboard tool test files.
+"""
+
+from collections.abc import Iterator
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.dashboard.DashboardDAO.find_by_id_or_uuid"
+_COMMAND = "superset.commands.dashboard.restore.RestoreDashboardCommand"
+
+_UUID = UUID("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")
Review Comment:
✅ **Customized review instruction saved!**
**Instruction:**
> Do not flag unannotated module-level logger/string constants or other inferable locals in mcp_service modules and test suites; this codebase intentionally leaves them unannotated and mypy passes.
**Applied to:**
- `superset/mcp_service/**`
- `tests/**`
---
💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*
##########
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__)
Review Comment:
✅ **Customized review instruction saved!**
**Instruction:**
> Do not flag module-level loggers, string constants, or other trivially inferable locals for missing type annotations in superset/mcp_service modules and test suites.
**Applied to:**
- `superset/mcp_service/**`
- `**/test/**`
- `**/tests/**`
- `**/*test*.<ext>`
---
💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*
##########
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__)
Review Comment:
✅ **Customized review instruction saved!**
**Instruction:**
> Do not flag module-level logger/string constants or other inferable locals for explicit type annotations in mcp_service modules and test suites.
**Applied to:**
- `superset/mcp_service/**`
- `**/test/**`
- `**/tests/**`
- `**/*test*.<ext>`
---
💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*
##########
tests/unit_tests/mcp_service/chart/tool/test_restore_chart.py:
##########
@@ -0,0 +1,183 @@
+# 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.
+
+"""Unit tests for the restore_chart MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other chart tool test files.
+"""
+
+from collections.abc import Iterator
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
Review Comment:
✅ **Customized review instruction saved!**
**Instruction:**
> Do not flag module-level logger/string constants or locals with inferable types for missing annotations in mcp_service modules and their test suites; mypy-based enforcement is sufficient.
**Applied to:**
- `superset/mcp_service/**`
- `tests/unit_tests/mcp_service/**`
---
💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3575515162
##########
superset/mcp_service/dashboard/tool/restore_dashboard.py:
##########
@@ -0,0 +1,185 @@
+# 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.
+
+ Both bypasses mirror ``BaseRestoreCommand.validate``'s own lookup:
+ ``skip_visibility_filter`` unhides the soft-deleted row, and
+ ``skip_base_filter`` keeps an editor's own trash reachable even when the
+ entity's RBAC base_filter has no editorship leg (a lost grant must not
+ hide a row from the one audience that can restore it). The restore
+ audience is enforced by ``RestoreDashboardCommand`` via
+ ``raise_for_editorship``.
+ """
+ from superset.daos.dashboard import DashboardDAO
+
+ return DashboardDAO.find_by_id_or_uuid(
+ str(identifier),
+ skip_base_filter=True,
+ skip_visibility_filter=True,
+ )
Review Comment:
✅ **Customized review instruction saved!**
**Instruction:**
> Do not flag `skip_base_filter=True` in restore-dashboard lookups; restore flows must bypass base_filter to resolve soft-deleted rows and rely on editorship checks for authorization.
**Applied to:**
- `superset/mcp_service/dashboard/tool/**`
---
💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3533181047
##########
superset/mcp_service/dashboard/tool/restore_dashboard.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_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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No dashboard found with identifier: {safe_id}."
+ return RestoreDashboardResponse(success=False, error=msg, error_type="NotFound")
+
+ dashboard_id = dashboard.id
+ dashboard_name = dashboard.dashboard_title
+
+ if dashboard.deleted_at is None:
+ return RestoreDashboardResponse(
+ success=False,
+ error=(
+ f"Dashboard '{dashboard_name}' (id={dashboard_id}) is not in "
+ "trash; nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.dashboard.restore import RestoreDashboardCommand
+
+ with event_logger.log_context(action="mcp.restore_dashboard"):
+ RestoreDashboardCommand(str(dashboard.uuid)).run()
+
+ return RestoreDashboardResponse(
+ success=True,
+ restored_id=dashboard_id,
+ restored_name=dashboard_name,
+ message=(
+ f"Restored dashboard '{dashboard_name}' (id={dashboard_id}) from trash."
+ ),
+ )
Review Comment:
**Suggestion:** `dashboard_name` is inserted directly into response text without sanitization, which lets dashboard titles carry untrusted prompt content into MCP responses. Wrap or sanitize dashboard titles before embedding them in `message`/`error` fields to prevent prompt-injection-through-output. [security]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
⚠️ Dashboard titles can inject delimiters into MCP output.
⚠️ Prompt-injection via restore_dashboard response affects LLM tools.
⚠️ Restore_dashboard inconsistent with dashboard info sanitization rules.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Create or modify a dashboard whose title (dashboard.dashboard_title) contains
LLM-control delimiters or prompt-like content; DashboardDAO treats dashboard_title as a
mutable field in its serializer, and DashboardInfo sanitization uses this field name
(superset/mcp_service/dashboard/schemas.py:18-28).
2. Soft-delete this dashboard so deleted_at on the Dashboard (SoftDeleteMixin in
superset/models/helpers.py:71-85 and Dashboard restore command comments in
superset/commands/dashboard/restore.py:30-40) becomes non-null via existing delete flows.
3. As a user who owns the dashboard (so restore is authorized), call the restore_dashboard
MCP tool with its id or uuid using the documented schema in
superset/mcp_service/dashboard/tool/restore_dashboard.py:79-90.
4. Inside restore_dashboard, the dashboard is loaded via _find_dashboard_for_restore
(restore_dashboard.py:44-53) and dashboard_name is set from dashboard.dashboard_title at
restore_dashboard.py:104-105; this title is user-controlled and not sanitized in this
function.
5. Because dashboard.deleted_at is not None,
RestoreDashboardCommand(str(dashboard.uuid)).run() executes
(restore_dashboard.py:118-121), and the success response at restore_dashboard.py:123-130
is returned, embedding dashboard_name directly in the message string without calling
escape_llm_context_delimiters or sanitize_for_llm_context.
6. Elsewhere, read-path dashboard responses are explicitly sanitized for LLM exposure:
_sanitize_dashboard_info_for_llm_context in
superset/mcp_service/dashboard/schemas.py:12-61 wraps dashboard_title, description,
native_filters, chart slice_name, and datasource_name via sanitize_for_llm_context and
escape_llm_context_delimiters, but restore_dashboard’s success message bypasses this
sanitization, allowing untrusted dashboard titles to carry unescaped delimiters into MCP
tool output.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=2f1abb4983b34ae7837c7ce014978cfb&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=2f1abb4983b34ae7837c7ce014978cfb&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:** 123:130
**Comment:**
*Security: `dashboard_name` is inserted directly into response text without sanitization, which lets dashboard titles carry untrusted prompt content into MCP responses. Wrap or sanitize dashboard titles before embedding them in `message`/`error` fields to prevent prompt-injection-through-output.
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=385c4165ee169cc584a3532f7f6fcd351e0f2c2fca0df0e2188989cb05c9be30&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=385c4165ee169cc584a3532f7f6fcd351e0f2c2fca0df0e2188989cb05c9be30&reaction=dislike'>👎</a>
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,148 @@
+# 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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No chart found with identifier: {safe_id}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ chart_name = chart.slice_name
+
+ if chart.deleted_at is None:
+ return RestoreChartResponse(
+ success=False,
+ error=(
+ f"Chart '{chart_name}' (id={chart_id}) is not in trash; "
+ "nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
Review Comment:
**Suggestion:** The early `NotDeleted` return bypasses the command-layer ownership check, so a user who can see (but not own) a chart can still invoke this mutating tool and get a definitive restore-state response. Enforce ownership before returning this branch (or delegate to `RestoreChartCommand` for this path) so unauthorized callers consistently receive a permission-denied outcome. [security]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
❌ Restore tool reveals chart trash status to non-owners.
⚠️ Ownership requirement in docs not enforced consistently.
⚠️ Mutating tool leaks chart state without permission_denied.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Start the MCP service so chart tools are registered; restore_chart is exported in
superset/mcp_service/chart/tool/__init__.py:18-26 and listed as a write tool in
get_default_instructions at superset/mcp_service/app.py:175-186.
2. Ensure a chart exists that the current user can view via ChartFilter
(superset/charts/filters.py:104-129) but does not own via the Slice.owners relationship
(superset/models/slice.py:114-118); ownership is tracked separately from view access.
3. From an MCP client, call the restore_chart tool with that chart's numeric id or uuid
using the documented schema (superset/mcp_service/chart/tool/restore_chart.py:77-88), so
request.identifier resolves to this chart.
4. restore_chart calls _find_chart_for_restore (restore_chart.py:44-53), which uses
ChartDAO.find_by_id_or_uuid with skip_visibility_filter=True; ChartDAO.base_filter is
ChartFilter (superset/daos/chart.py:45-47), so a non-owner with dataset access still
receives the Slice model.
5. Because chart.deleted_at is None for an active chart, the branch at
restore_chart.py:104-112 executes and returns a RestoreChartResponse with
error_type="NotDeleted" and a detailed message, without ever invoking
RestoreChartCommand.run().
6. In the command path, BaseRestoreCommand.validate (superset/commands/restore.py:76-97)
would call security_manager.raise_for_ownership and raise ChartForbiddenError for
non-owners via RestoreChartCommand (superset/commands/chart/restore.py:29-38), but this
ownership check is bypassed for the NotDeleted branch, so unauthorized callers get
stateful feedback instead of permission_denied.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e56f8d84077c44cdb7f5758bb88234e2&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=e56f8d84077c44cdb7f5758bb88234e2&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:** 104:112
**Comment:**
*Security: The early `NotDeleted` return bypasses the command-layer ownership check, so a user who can see (but not own) a chart can still invoke this mutating tool and get a definitive restore-state response. Enforce ownership before returning this branch (or delegate to `RestoreChartCommand` for this path) so unauthorized callers consistently receive a permission-denied outcome.
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=45e3e5126be6ee494f12b0b48e9c97bfdaaee1b144b5fdb397885b162b623496&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=45e3e5126be6ee494f12b0b48e9c97bfdaaee1b144b5fdb397885b162b623496&reaction=dislike'>👎</a>
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,148 @@
+# 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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No chart found with identifier: {safe_id}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ chart_name = chart.slice_name
+
+ if chart.deleted_at is None:
+ return RestoreChartResponse(
+ success=False,
+ error=(
+ f"Chart '{chart_name}' (id={chart_id}) is not in trash; "
+ "nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.chart.restore import RestoreChartCommand
+
+ with event_logger.log_context(action="mcp.restore_chart"):
+ RestoreChartCommand(str(chart.uuid)).run()
+
+ return RestoreChartResponse(
+ success=True,
+ restored_id=chart_id,
+ restored_name=chart_name,
+ message=f"Restored chart '{chart_name}' (id={chart_id}) from trash.",
+ )
Review Comment:
**Suggestion:** The success/error text interpolates `chart_name` directly into MCP output without LLM-context sanitization. Because chart names are user-controlled content, this can inject prompt-control delimiters into tool responses; sanitize or escape the name before composing response strings. [security]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
⚠️ Chart titles can inject delimiters into MCP responses.
⚠️ Prompt-injection via restore_chart output degrades LLM reliability.
⚠️ Inconsistent sanitization compared to dashboard info serializers.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Create or modify a chart whose title (Slice.slice_name) contains LLM-control delimiters
or prompt-like content; Slice defines slice_name as a user-controlled string column in
superset/models/slice.py:90-92.
2. Soft-delete this chart so deleted_at on the Slice (SoftDeleteMixin in
superset/models/helpers.py:71-85 and Slice base class in superset/models/slice.py:82-83)
becomes non-null via existing delete flows, making it restorable.
3. As a user who owns the chart (so restore is allowed), call the restore_chart MCP tool
using its documented request schema
(superset/mcp_service/chart/tool/restore_chart.py:77-88) from an MCP client, with
request.identifier targeting this chart id or uuid.
4. Inside restore_chart, the chart is loaded via _find_chart_for_restore
(restore_chart.py:44-53) and chart_name is set from chart.slice_name at
restore_chart.py:101-102; no sanitization is applied to this name.
5. Because chart.deleted_at is not None, RestoreChartCommand(str(chart.uuid)).run()
executes (restore_chart.py:115-118), then the success response at restore_chart.py:120-125
is returned, interpolating chart_name directly into the message field without calling
escape_llm_context_delimiters or sanitize_for_llm_context.
6. Other MCP responses deliberately sanitize user-controlled strings before LLM exposure,
e.g. _sanitize_dashboard_info_for_llm_context in
superset/mcp_service/dashboard/schemas.py:12-61 wraps dashboard_title, slice_name, and
datasource_name via sanitize_for_llm_context and escape_llm_context_delimiters, but
restore_chart’s success message omits this, allowing user-controlled chart titles to carry
unescaped delimiters into MCP tool output.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=892256604b334abba12751678045c3fe&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=892256604b334abba12751678045c3fe&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:** 120:125
**Comment:**
*Security: The success/error text interpolates `chart_name` directly into MCP output without LLM-context sanitization. Because chart names are user-controlled content, this can inject prompt-control delimiters into tool responses; sanitize or escape the name before composing response strings.
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=a3fdb2ce1974a8f29990b474e869519757479f04661efe040e27357a5f06b971&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=a3fdb2ce1974a8f29990b474e869519757479f04661efe040e27357a5f06b971&reaction=dislike'>👎</a>
##########
superset/mcp_service/dashboard/tool/restore_dashboard.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_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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No dashboard found with identifier: {safe_id}."
+ return RestoreDashboardResponse(success=False, error=msg, error_type="NotFound")
+
+ dashboard_id = dashboard.id
+ dashboard_name = dashboard.dashboard_title
+
+ if dashboard.deleted_at is None:
+ return RestoreDashboardResponse(
+ success=False,
+ error=(
+ f"Dashboard '{dashboard_name}' (id={dashboard_id}) is not in "
+ "trash; nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
Review Comment:
**Suggestion:** The early `NotDeleted` response is returned before any ownership enforcement, allowing non-owners with visibility to learn restore state through a write-scoped tool. Apply the same ownership gate here as in the command path so unauthorized callers do not receive object-state responses from restore operations. [security]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
❌ Restore_dashboard exposes trash status to non-owner dashboard viewers.
⚠️ Dashboard restore tool diverges from ownership enforcement contract.
⚠️ Unauthorized callers learn dashboard state via write tool.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Start the MCP service so dashboard tools are registered; restore_dashboard is exported
in superset/mcp_service/dashboard/tool/__init__.py:18-27 and advertised as a write tool in
get_default_instructions at superset/mcp_service/app.py:127-139.
2. Ensure a dashboard exists that the current user can view via DashboardAccessFilter
(DashboardDAO.base_filter in superset/daos/dashboard.py:61-62) but does not own (owners
relationship on the Dashboard model, referenced by dashboard_user in
superset/daos/dashboard.py:99-101), giving view rights without ownership.
3. From an MCP client, call the restore_dashboard tool with that dashboard’s id or uuid
using the documented request schema
(superset/mcp_service/dashboard/tool/restore_dashboard.py:79-90), so request.identifier
matches this dashboard.
4. restore_dashboard resolves the dashboard via _find_dashboard_for_restore
(restore_dashboard.py:44-53), which calls DashboardDAO.find_by_id_or_uuid with
skip_visibility_filter=True; because base_filter remains applied per
BaseDAO.find_by_id_or_uuid (superset/daos/base.py:30-59), a non-owner with view access
receives the Dashboard instance.
5. With an active dashboard (dashboard.deleted_at is None), the branch at
restore_dashboard.py:107-115 executes and returns a RestoreDashboardResponse with
error_type="NotDeleted" and a detailed message, without permission_denied=True and without
invoking RestoreDashboardCommand.run().
6. In the normal restore path, RestoreDashboardCommand extends BaseRestoreCommand
(superset/commands/dashboard/restore.py:30-44), and BaseRestoreCommand.validate
(superset/commands/restore.py:76-97) would enforce ownership via
security_manager.raise_for_ownership and raise DashboardForbiddenError for non-owners, but
this pre-command NotDeleted branch bypasses that check, so unauthorized callers use a
write-scoped tool to learn restore state instead of receiving a forbidden response.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=cebfe7b938ab46658de0fd61446b41e7&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=cebfe7b938ab46658de0fd61446b41e7&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:** 107:115
**Comment:**
*Security: The early `NotDeleted` response is returned before any ownership enforcement, allowing non-owners with visibility to learn restore state through a write-scoped tool. Apply the same ownership gate here as in the command path so unauthorized callers do not receive object-state responses from restore operations.
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=79a6c205b02538891cbc97659b4cb955065bcb8ff9b364f7b6974ecf01f1f807&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=79a6c205b02538891cbc97659b4cb955065bcb8ff9b364f7b6974ecf01f1f807&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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3575440355
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,169 @@
+# 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)
Review Comment:
Confirmed and fixed in 352ca176ee — verified BaseRestoreCommand.validate at HEAD does pass skip_base_filter=True with the lost-grant rationale; both pre-lookups now pass both bypasses and the helper docstrings quote the command's reasoning. My earlier justification was written against the pre-editorship command and no longer matched.
##########
superset/mcp_service/dashboard/tool/restore_dashboard.py:
##########
@@ -0,0 +1,177 @@
+# 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)
Review Comment:
Fixed in 352ca176ee — same alignment as the chart tool.
##########
tests/unit_tests/mcp_service/chart/tool/test_restore_chart.py:
##########
@@ -0,0 +1,208 @@
+# 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.
+
+"""Unit tests for the restore_chart MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other chart tool test files.
+"""
+
+from collections.abc import Iterator
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.chart.ChartDAO.find_by_id_or_uuid"
Review Comment:
Added in 352ca176ee — test_restore_chart_lookup_db_error_is_structured mocks the lookup to raise OperationalError and asserts LookupFailed with no leaked exception text.
##########
tests/unit_tests/mcp_service/dashboard/tool/test_restore_dashboard.py:
##########
@@ -0,0 +1,185 @@
+# 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.
+
+"""Unit tests for the restore_dashboard MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other dashboard tool test files.
+"""
+
+from collections.abc import Iterator
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.dashboard.DashboardDAO.find_by_id_or_uuid"
Review Comment:
Both added in 352ca176ee — test_restore_dashboard_sqlalchemy_error_is_generic (masking parity with the chart sibling) and test_restore_dashboard_slug_conflict (asserts the DashboardSlugConflictError type and its user-facing rename guidance pass through).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3565449295
##########
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:
Fixed in 2ab66a25ce — same hardening as the delete tools on #41472. Lookup db failures now return structured LookupFailed.
##########
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:
Fixed in 2ab66a25ce — same hardening as the delete tools on #41472. Same guard as restore_chart.
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,154 @@
+# 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 be an editor of the chart (owners and
+ Admins qualify).
+
+ 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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No chart found with identifier: {safe_id}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ # Chart names are user-controlled; wrap before composing response text so
+ # a hostile name cannot inject prompt content into the tool output.
+ chart_name = sanitize_for_llm_context(chart.slice_name, field_path=("slice_name",))
+
+ if chart.deleted_at is None:
+ return RestoreChartResponse(
+ success=False,
+ error=(
+ f"Chart '{chart_name}' (id={chart_id}) is not in trash; "
+ "nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.chart.restore import RestoreChartCommand
+
+ with event_logger.log_context(action="mcp.restore_chart"):
+ RestoreChartCommand(str(chart.uuid)).run()
+
+ return RestoreChartResponse(
+ success=True,
+ restored_id=chart_id,
+ restored_name=chart_name,
+ message=f"Restored chart '{chart_name}' (id={chart_id}) from trash.",
+ )
+ except ChartForbiddenError:
+ await ctx.warning("Permission denied restoring chart id=%s" % (chart_id,))
+ return RestoreChartResponse(
+ success=False,
+ permission_denied=True,
+ error=(
+ f"You do not have permission to restore chart '{chart_name}' "
+ f"(id={chart_id}). Ask the user to restore it or grant access; "
+ "do not retry."
+ ),
+ error_type="Forbidden",
+ )
+ except ChartNotFoundError:
+ msg = f"Chart id={chart_id} is no longer restorable."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+ except (CommandException, SQLAlchemyError, ValueError) as ex:
+ _rollback()
+ await ctx.error("Chart restore failed: %s: %s" % (type(ex).__name__, ex))
+ return RestoreChartResponse(
+ success=False,
+ error=f"Chart restore failed: {ex}",
+ error_type=type(ex).__name__,
+ )
Review Comment:
Fixed in 2ab66a25ce — same hardening as the delete tools on #41472. SQLAlchemyError now returns a generic message; CommandException text is user-facing by design. With a test.
##########
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 be an editor of the dashboard (owners and Admins qualify).
+
+ 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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No dashboard found with identifier: {safe_id}."
+ return RestoreDashboardResponse(success=False, error=msg, error_type="NotFound")
+
+ dashboard_id = dashboard.id
+ # Dashboard titles are user-controlled; wrap before composing response
+ # text so a hostile title cannot inject prompt content into the output.
+ dashboard_name = sanitize_for_llm_context(
+ dashboard.dashboard_title, field_path=("dashboard_title",)
+ )
+
+ if dashboard.deleted_at is None:
+ return RestoreDashboardResponse(
+ success=False,
+ error=(
+ f"Dashboard '{dashboard_name}' (id={dashboard_id}) is not in "
+ "trash; nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.dashboard.restore import RestoreDashboardCommand
+
+ with event_logger.log_context(action="mcp.restore_dashboard"):
+ RestoreDashboardCommand(str(dashboard.uuid)).run()
+
+ return RestoreDashboardResponse(
+ success=True,
+ restored_id=dashboard_id,
+ restored_name=dashboard_name,
+ message=(
+ f"Restored dashboard '{dashboard_name}' (id={dashboard_id}) from trash."
+ ),
+ )
+ except DashboardForbiddenError:
+ await ctx.warning(
+ "Permission denied restoring dashboard id=%s" % (dashboard_id,)
+ )
+ return RestoreDashboardResponse(
+ success=False,
+ permission_denied=True,
+ error=(
+ f"You do not have permission to restore dashboard "
+ f"'{dashboard_name}' (id={dashboard_id}). Ask the user to "
+ "restore it or grant access; do not retry."
+ ),
+ error_type="Forbidden",
+ )
+ except DashboardNotFoundError:
+ msg = f"Dashboard id={dashboard_id} is no longer restorable."
+ return RestoreDashboardResponse(success=False, error=msg, error_type="NotFound")
+ except (CommandException, SQLAlchemyError, ValueError) as ex:
+ _rollback()
+ await ctx.error("Dashboard restore failed: %s: %s" % (type(ex).__name__, ex))
+ return RestoreDashboardResponse(
+ success=False,
+ error=f"Dashboard restore failed: {ex}",
+ error_type=type(ex).__name__,
Review Comment:
Fixed in 2ab66a25ce — same hardening as the delete tools on #41472. Same sanitization as restore_chart.
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,154 @@
+# 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)
Review Comment:
Declining: keeping base_filter in the pre-lookup exactly mirrors BaseRestoreCommand.validate's own lookup (superset/commands/restore.py — find_by_id with skip_visibility_filter=True, base_filter intact, with a docstring stating 'Restore should not see rows the user cannot see in the live UI'). If the pre-lookup bypassed base_filter, the tool would surface rows the command itself would then refuse, producing a confusing found-then-denied flow that diverges from REST semantics. Editorship is enforced by the command after the visibility gate, same as the REST restore endpoint.
##########
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)
Review Comment:
Declining: keeping base_filter in the pre-lookup exactly mirrors BaseRestoreCommand.validate's own lookup (superset/commands/restore.py — find_by_id with skip_visibility_filter=True, base_filter intact, with a docstring stating 'Restore should not see rows the user cannot see in the live UI'). If the pre-lookup bypassed base_filter, the tool would surface rows the command itself would then refuse, producing a confusing found-then-denied flow that diverges from REST semantics. Editorship is enforced by the command after the visibility gate, same as the REST restore endpoint.
##########
tests/unit_tests/mcp_service/dashboard/tool/test_restore_dashboard.py:
##########
@@ -0,0 +1,185 @@
+# 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.
+
+"""Unit tests for the restore_dashboard MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other dashboard tool test files.
+"""
+
+from collections.abc import Iterator
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.dashboard.DashboardDAO.find_by_id_or_uuid"
+_COMMAND = "superset.commands.dashboard.restore.RestoreDashboardCommand"
+
+_UUID = UUID("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")
Review Comment:
Declining, standing rationale: module-level logger/string constants and locals with inferable types are unannotated across this codebase's mcp_service modules and test suites; mypy passes. Identical future findings will be declined the same way.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #41842:
URL: https://github.com/apache/superset/pull/41842#issuecomment-4899536863
## [Codecov](https://app.codecov.io/gh/apache/superset/pull/41842?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `44.82759%` with `64 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 55.98%. Comparing base ([`101c1e8`](https://app.codecov.io/gh/apache/superset/commit/101c1e88275864dfa13e5e5ae172f26b03970f84?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`77f1406`](https://app.codecov.io/gh/apache/superset/commit/77f1406f8735489c65df6307c1d06d0f317d2233?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 5 commits behind head on master.
| [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/41842?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [superset/mcp\_service/chart/tool/restore\_chart.py](https://app.codecov.io/gh/apache/superset/pull/41842?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fchart%2Ftool%2Frestore_chart.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvY2hhcnQvdG9vbC9yZXN0b3JlX2NoYXJ0LnB5) | 31.91% | [32 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/41842?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...et/mcp\_service/dashboard/tool/restore\_dashboard.py](https://app.codecov.io/gh/apache/superset/pull/41842?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fdashboard%2Ftool%2Frestore_dashboard.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvZGFzaGJvYXJkL3Rvb2wvcmVzdG9yZV9kYXNoYm9hcmQucHk=) | 31.91% | [32 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/41842?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
> :exclamation: There is a different number of reports uploaded between BASE (101c1e8) and HEAD (77f1406). Click for more details.
>
> <details><summary>HEAD has 12 uploads less than BASE</summary>
>
>| Flag | BASE (101c1e8) | HEAD (77f1406) |
>|------|------|------|
>|python|12|2|
>|presto|2|1|
>|hive|2|1|
></details>
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #41842 +/- ##
==========================================
- Coverage 64.77% 55.98% -8.80%
==========================================
Files 2689 2691 +2
Lines 148945 149061 +116
Branches 34369 34373 +4
==========================================
- Hits 96479 83447 -13032
- Misses 50697 64862 +14165
+ Partials 1769 752 -1017
```
| [Flag](https://app.codecov.io/gh/apache/superset/pull/41842/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [hive](https://app.codecov.io/gh/apache/superset/pull/41842/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.20% <44.82%> (+<0.01%)` | :arrow_up: |
| [mysql](https://app.codecov.io/gh/apache/superset/pull/41842/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [postgres](https://app.codecov.io/gh/apache/superset/pull/41842/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [presto](https://app.codecov.io/gh/apache/superset/pull/41842/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `40.74% <44.82%> (+<0.01%)` | :arrow_up: |
| [python](https://app.codecov.io/gh/apache/superset/pull/41842/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `40.80% <44.82%> (-18.53%)` | :arrow_down: |
| [sqlite](https://app.codecov.io/gh/apache/superset/pull/41842/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [unit](https://app.codecov.io/gh/apache/superset/pull/41842/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/41842?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3540861967
##########
tests/unit_tests/mcp_service/dashboard/tool/test_restore_dashboard.py:
##########
@@ -0,0 +1,185 @@
+# 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.
+
+"""Unit tests for the restore_dashboard MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other dashboard tool test files.
+"""
+
+from collections.abc import Iterator
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.dashboard.DashboardDAO.find_by_id_or_uuid"
+_COMMAND = "superset.commands.dashboard.restore.RestoreDashboardCommand"
+
+_UUID = UUID("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")
Review Comment:
**Suggestion:** Add explicit type annotations to these module-level constants so relevant variables in new Python code are typed. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The new module-level constants `_FIND`, `_COMMAND`, and `_UUID` are unannotated values in newly added Python code and can be type hinted (for example, `str` and `UUID`). This matches the rule requiring type hints on relevant variables that can be annotated.
</details>
<details>
<summary><b>Rule source 📖 </b></summary>
.cursor/rules/dev-standard.mdc (line 28)
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=8bf8d834e5254573af25d5b3f4420627&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=8bf8d834e5254573af25d5b3f4420627&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:** tests/unit_tests/mcp_service/dashboard/tool/test_restore_dashboard.py
**Line:** 33:37
**Comment:**
*Custom Rule: Add explicit type annotations to these module-level constants so relevant variables in new Python code are typed.
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=19980939d553e65e96bc3b1c16d58d76b93b942ed5533c16df28ca34a8f63f33&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=19980939d553e65e96bc3b1c16d58d76b93b942ed5533c16df28ca34a8f63f33&reaction=dislike'>👎</a>
##########
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__)
Review Comment:
**Suggestion:** Add an explicit type annotation for this module-level variable to satisfy the type-hint requirement for relevant annotatable variables. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
This is a new Python file, and the module-level logger variable is clearly annotatable as a logging.Logger. The custom rule requires type hints on relevant variables that can be annotated, so omitting an explicit annotation here is a real violation.
</details>
<details>
<summary><b>Rule source 📖 </b></summary>
.cursor/rules/dev-standard.mdc (line 28)
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=28b528b4777a4e848cbce84193c289df&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=28b528b4777a4e848cbce84193c289df&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:** 44:44
**Comment:**
*Custom Rule: Add an explicit type annotation for this module-level variable to satisfy the type-hint requirement for relevant annotatable variables.
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=a86715257e3939c7fa59243898d6f7c80518a3d4dfafe6eb612ac06640df5606&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=a86715257e3939c7fa59243898d6f7c80518a3d4dfafe6eb612ac06640df5606&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__)
Review Comment:
**Suggestion:** Add an explicit type annotation for the module-level logger variable to satisfy the type-hint requirement. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The custom rule requires type hints on relevant Python variables that can be annotated. This module-level logger is unannotated, and it can be typed (for example, as a Logger), so the suggestion identifies a real violation.
</details>
<details>
<summary><b>Rule source 📖 </b></summary>
.cursor/rules/dev-standard.mdc (line 28)
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=6ce371afcabe4814a7232d554646885e&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=6ce371afcabe4814a7232d554646885e&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:** 44:44
**Comment:**
*Custom Rule: Add an explicit type annotation for the module-level logger variable to satisfy the type-hint requirement.
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=b731a3e5eddb43e36686f6d3c0059b1fc369fb21d2077ba218dbc9aaf764be69&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=b731a3e5eddb43e36686f6d3c0059b1fc369fb21d2077ba218dbc9aaf764be69&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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3541019212
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,148 @@
+# 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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No chart found with identifier: {safe_id}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ chart_name = chart.slice_name
+
+ if chart.deleted_at is None:
+ return RestoreChartResponse(
+ success=False,
+ error=(
+ f"Chart '{chart_name}' (id={chart_id}) is not in trash; "
+ "nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
Review Comment:
Declining the reordering: BaseRestoreCommand.validate itself checks deleted_at BEFORE raise_for_ownership (superset/commands/restore.py — found → not-soft-deleted → not_found_exc, then ownership), so the REST restore endpoint has exactly these semantics: a visible-but-not-owned live object gets a state-derived 404 before any ownership error. The tool's NotDeleted branch mirrors that; a visible live chart's liveness is already observable via list/get, so no information crosses a boundary the command layer doesn't already allow. Trashed objects still go through the command and get the ownership check.
##########
superset/mcp_service/dashboard/tool/restore_dashboard.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_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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No dashboard found with identifier: {safe_id}."
+ return RestoreDashboardResponse(success=False, error=msg, error_type="NotFound")
+
+ dashboard_id = dashboard.id
+ dashboard_name = dashboard.dashboard_title
+
+ if dashboard.deleted_at is None:
+ return RestoreDashboardResponse(
+ success=False,
+ error=(
+ f"Dashboard '{dashboard_name}' (id={dashboard_id}) is not in "
+ "trash; nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
Review Comment:
Declining the reordering: BaseRestoreCommand.validate itself checks deleted_at BEFORE raise_for_ownership (superset/commands/restore.py — found → not-soft-deleted → not_found_exc, then ownership), so the REST restore endpoint has exactly these semantics: a visible-but-not-owned live object gets a state-derived 404 before any ownership error. The tool's NotDeleted branch mirrors that; a visible live chart's liveness is already observable via list/get, so no information crosses a boundary the command layer doesn't already allow. Trashed objects still go through the command and get the ownership check.
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,148 @@
+# 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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No chart found with identifier: {safe_id}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ chart_name = chart.slice_name
+
+ if chart.deleted_at is None:
+ return RestoreChartResponse(
+ success=False,
+ error=(
+ f"Chart '{chart_name}' (id={chart_id}) is not in trash; "
+ "nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.chart.restore import RestoreChartCommand
+
+ with event_logger.log_context(action="mcp.restore_chart"):
+ RestoreChartCommand(str(chart.uuid)).run()
+
+ return RestoreChartResponse(
+ success=True,
+ restored_id=chart_id,
+ restored_name=chart_name,
+ message=f"Restored chart '{chart_name}' (id={chart_id}) from trash.",
+ )
Review Comment:
Fixed in a58e6c1079 — the name is wrapped via sanitize_for_llm_context before composing the response message and restored_name, matching the get/list and manage_native_filters convention.
##########
superset/mcp_service/dashboard/tool/restore_dashboard.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_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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No dashboard found with identifier: {safe_id}."
+ return RestoreDashboardResponse(success=False, error=msg, error_type="NotFound")
+
+ dashboard_id = dashboard.id
+ dashboard_name = dashboard.dashboard_title
+
+ if dashboard.deleted_at is None:
+ return RestoreDashboardResponse(
+ success=False,
+ error=(
+ f"Dashboard '{dashboard_name}' (id={dashboard_id}) is not in "
+ "trash; nothing to restore."
+ ),
+ error_type="NotDeleted",
+ )
+
+ try:
+ from superset.commands.dashboard.restore import RestoreDashboardCommand
+
+ with event_logger.log_context(action="mcp.restore_dashboard"):
+ RestoreDashboardCommand(str(dashboard.uuid)).run()
+
+ return RestoreDashboardResponse(
+ success=True,
+ restored_id=dashboard_id,
+ restored_name=dashboard_name,
+ message=(
+ f"Restored dashboard '{dashboard_name}' (id={dashboard_id}) from trash."
+ ),
+ )
Review Comment:
Fixed in a58e6c1079 — the name is wrapped via sanitize_for_llm_context before composing the response message and restored_name, matching the get/list and manage_native_filters convention.
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,148 @@
+# 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
+
+logger = logging.getLogger(__name__)
Review Comment:
Declining: module-level `logger` and locals with types inferable from the assignment are not annotated anywhere in this codebase (every mcp_service module declares bare `logger = logging.getLogger(__name__)`); mypy passes without them. Keeping repo convention.
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,148 @@
+# 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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No chart found with identifier: {safe_id}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ chart_name = chart.slice_name
Review Comment:
Declining: module-level `logger` and locals with types inferable from the assignment are not annotated anywhere in this codebase (every mcp_service module declares bare `logger = logging.getLogger(__name__)`); mypy passes without them. Keeping repo convention.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3541020800
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,148 @@
+# 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
+
+logger = logging.getLogger(__name__)
Review Comment:
✅ **Customized review instruction saved!**
**Instruction:**
> Do not require explicit type annotations for module-level `logger = logging.getLogger(__name__)` in `mcp_service` modules; keep the existing repo convention where these logger variables remain unannotated.
**Applied to:**
- `superset/mcp_service/**`
---
💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*
##########
superset/mcp_service/chart/tool/restore_chart.py:
##########
@@ -0,0 +1,148 @@
+# 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
+
+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:
+ safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+ msg = f"No chart found with identifier: {safe_id}."
+ return RestoreChartResponse(success=False, error=msg, error_type="NotFound")
+
+ chart_id = chart.id
+ chart_name = chart.slice_name
Review Comment:
✅ **Customized review instruction saved!**
**Instruction:**
> Do not flag missing type annotations for module-level loggers or locals whose types are already inferable from the assignment; this repo convention leaves those unannotated.
**Applied to:**
- `**/*.py`
---
💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on PR #41842:
URL: https://github.com/apache/superset/pull/41842#issuecomment-4931545327
Cross-reference: per the discussion on #41472, this PR is the confirmed companion to the delete tools — the maintainer opted to keep them as a reviewed-together pair (and endorsed the restore_* naming, matching the REST route).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3541019832
##########
tests/unit_tests/mcp_service/chart/tool/test_restore_chart.py:
##########
@@ -0,0 +1,182 @@
+# 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.
+
+"""Unit tests for the restore_chart MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other chart tool test files.
+"""
+
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.chart.ChartDAO.find_by_id_or_uuid"
+_COMMAND = "superset.commands.chart.restore.RestoreChartCommand"
+
+_UUID = UUID("11111111-2222-3333-4444-555555555555")
+
+
+@pytest.fixture
+def mcp_server() -> object:
+ return mcp
+
+
+@pytest.fixture(autouse=True)
+def mock_auth():
+ with patch("superset.mcp_service.auth.get_user_from_request") as mock_get_user:
+ mock_user = Mock()
+ mock_user.id = 1
+ mock_user.username = "admin"
+ mock_get_user.return_value = mock_user
+ yield mock_get_user
Review Comment:
Fixture annotations added in a58e6c1079.
##########
tests/unit_tests/mcp_service/dashboard/tool/test_restore_dashboard.py:
##########
@@ -0,0 +1,184 @@
+# 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.
+
+"""Unit tests for the restore_dashboard MCP tool.
+
+Run through the async MCP Client (not direct calls); auth is mocked via the
+autouse mock_auth fixture, matching the other dashboard tool test files.
+"""
+
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+
+_FIND = "superset.daos.dashboard.DashboardDAO.find_by_id_or_uuid"
+_COMMAND = "superset.commands.dashboard.restore.RestoreDashboardCommand"
+
+_UUID = UUID("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")
+
+
+@pytest.fixture
+def mcp_server() -> object:
+ return mcp
+
+
+@pytest.fixture(autouse=True)
+def mock_auth():
+ with patch("superset.mcp_service.auth.get_user_from_request") as mock_get_user:
+ mock_user = Mock()
+ mock_user.id = 1
+ mock_user.username = "admin"
+ mock_get_user.return_value = mock_user
+ yield mock_get_user
Review Comment:
Fixture annotations added in a58e6c1079.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "gkneighb (via GitHub)" <gi...@apache.org>.
gkneighb commented on PR #41842:
URL: https://github.com/apache/superset/pull/41842#issuecomment-4911102670
Sorted — all 8 threads triaged and resolved. Applied: LLM-context sanitization of chart/dashboard names in the restore responses (matching the get/list convention) and fixture annotations. Disputed in-thread: the two suggestions to reorder the NotDeleted check behind an ownership gate — BaseRestoreCommand.validate itself checks deleted_at before raise_for_ownership, so the tool mirrors the REST endpoint's exact semantics; and the logger/local annotation nits (not repo convention).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #41842:
URL: https://github.com/apache/superset/pull/41842#issuecomment-4910865055
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | e53f0898f31ebf08915fe483686541498eb43e98 |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a4db699a4448f00088a2be6 |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-41842--superset-docs-preview.netlify.app](https://deploy-preview-41842--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
|<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#DcoxDoAgDADAv3SWSAwh4A98RqElDGJJZTHGv8t2w73QVVofsAMskBSvXKcL41hb7kb5HqJsckUdhvCuSVBpXuJ-ynPQ3B4dJR8jOudCsdaGgFtiD98P) |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-41842--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #41842:
URL: https://github.com/apache/superset/pull/41842#issuecomment-4965222847
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(mcp): add restore_chart and restore_dashboard tools [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #41842:
URL: https://github.com/apache/superset/pull/41842#discussion_r3575303566
##########
superset/mcp_service/chart/schemas.py:
##########
@@ -2725,6 +2725,35 @@ class ChartFiltersInfo(BaseModel):
)
+class RestoreChartRequest(BaseModel):
+ """Request schema for restore_chart."""
+
+ identifier: int | str = Field(
+ ...,
+ description=(
+ "Chart identifier - numeric ID or UUID string (charts have no slug)."
+ ),
+ )
Review Comment:
**Suggestion:** `RestoreChartRequest.identifier` accepts `int | str` but does not reject booleans. Since `bool` is a subclass of `int`, a request like `{"identifier": true}` can be coerced to chart ID `1` and restore the wrong chart. Add the same pre-validation used in delete schemas to explicitly reject boolean identifiers. [type error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
⚠️ MCP restore_chart may restore unintended chart ID.
⚠️ LLM agents sending booleans risk mis-targeted restores.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. In `superset/mcp_service/chart/schemas.py` lines 49-57 (verified via Read),
`RestoreChartRequest` defines `identifier: int | str = Field(...)` with no
`field_validator` rejecting boolean values.
2. In the same file, `DeleteChartRequest` at lines 82-99 defines `identifier: int | str`
and adds `reject_bool_identifier` (`@field_validator("identifier", mode="before")`) with a
docstring explaining that `identifier=true` would coerce to chart ID 1 and delete the
wrong object (lines 95-96), confirming Pydantic’s bool→int coercion behavior.
3. The MCP tool `restore_chart` in `superset/mcp_service/chart/tool/restore_chart.py`
lines 85-107 accepts a `RestoreChartRequest` and calls
`_find_chart_for_restore(request.identifier)`, passing the validated `identifier` field
directly.
4. `_find_chart_for_restore` in the same file at lines 47-64 calls
`ChartDAO.find_by_id_or_uuid(str(identifier), skip_base_filter=True,
skip_visibility_filter=True)`. With a request payload `{"identifier": true}`, Pydantic
coerces `identifier` to integer `1`, `str(1)` becomes `"1"`, and
`BaseDAO.find_by_id_or_uuid` in `superset/daos/base.py` lines 33-35 treats `"1"` as a
digit, converting it to `int("1")` and looking up chart ID 1. If chart ID 1 is
soft-deleted and the caller has editorship, the tool restores that chart instead of the
intended target, demonstrating the bug.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=05433a0089674f5986959b0aaa044eaf&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=05433a0089674f5986959b0aaa044eaf&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/schemas.py
**Line:** 2731:2736
**Comment:**
*Type Error: `RestoreChartRequest.identifier` accepts `int | str` but does not reject booleans. Since `bool` is a subclass of `int`, a request like `{"identifier": true}` can be coerced to chart ID `1` and restore the wrong chart. Add the same pre-validation used in delete schemas to explicitly reject boolean identifiers.
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=d3f5ff63f7300a0eb2fa3236084f18135b2e710c568d639a5bcdac608b28b754&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41842&comment_hash=d3f5ff63f7300a0eb2fa3236084f18135b2e710c568d639a5bcdac608b28b754&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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org