gkneighb commented on code in PR #41472: URL: https://github.com/apache/superset/pull/41472#discussion_r3555942249
########## superset/mcp_service/dashboard/tool/delete_dashboard.py: ########## @@ -0,0 +1,166 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +MCP tool: delete_dashboard +""" + +import logging +from typing import Any + +from fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.commands.dashboard.exceptions import ( + DashboardDeleteFailedReportsExistError, + DashboardForbiddenError, + DashboardNotFoundError, +) +from superset.commands.exceptions import CommandException +from superset.extensions import event_logger +from superset.mcp_service.dashboard.schemas import ( + DeleteDashboardRequest, + DeleteDashboardResponse, +) +from superset.mcp_service.utils import escape_llm_context_delimiters + +logger = logging.getLogger(__name__) + + +def _find_dashboard_by_identifier(identifier: int | str) -> Any | None: + """Resolve a dashboard by numeric ID, UUID string, or slug. Returns None.""" + from superset.daos.dashboard import DashboardDAO + + if isinstance(identifier, int) or ( + isinstance(identifier, str) and identifier.isdigit() + ): + return DashboardDAO.find_by_id(int(identifier)) + # Try UUID, then fall back to slug. + dashboard = DashboardDAO.find_by_id(identifier, id_column="uuid") + if dashboard: + return dashboard + try: + return DashboardDAO.get_by_id_or_slug(identifier) + except DashboardNotFoundError: + return None + + +def _rollback() -> None: Review Comment: Docstrings/annotations added in 0439d6b2b2 / 3fb2247d16. ########## tests/unit_tests/mcp_service/dashboard/tool/test_delete_dashboard.py: ########## @@ -0,0 +1,143 @@ +# 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 delete_dashboard MCP tool. + +Run through the async MCP Client; auth is mocked via the autouse mock_auth +fixture, matching the other dashboard tool test files. +""" + +from unittest.mock import Mock, patch + +import pytest +from fastmcp import Client + +from superset.mcp_service.app import mcp + +_FIND = ( + "superset.mcp_service.dashboard.tool.delete_dashboard._find_dashboard_by_identifier" +) +_RUN = "superset.commands.dashboard.delete.DeleteDashboardCommand.run" + + [email protected] +def mcp_server() -> object: + return mcp Review Comment: Docstrings/annotations added in 0439d6b2b2 / 3fb2247d16. ########## tests/unit_tests/mcp_service/dashboard/tool/test_delete_dashboard.py: ########## @@ -0,0 +1,143 @@ +# 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 delete_dashboard MCP tool. + +Run through the async MCP Client; auth is mocked via the autouse mock_auth +fixture, matching the other dashboard tool test files. +""" + +from unittest.mock import Mock, patch + +import pytest +from fastmcp import Client + +from superset.mcp_service.app import mcp + +_FIND = ( + "superset.mcp_service.dashboard.tool.delete_dashboard._find_dashboard_by_identifier" +) +_RUN = "superset.commands.dashboard.delete.DeleteDashboardCommand.run" + + [email protected] +def mcp_server() -> object: + return mcp + + [email protected](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: Docstrings/annotations added in 0439d6b2b2 / 3fb2247d16. ########## superset/mcp_service/chart/tool/delete_chart.py: ########## @@ -0,0 +1,140 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +MCP tool: delete_chart +""" + +import logging + +from fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.commands.chart.exceptions import ( + ChartDeleteFailedReportsExistError, + ChartForbiddenError, + ChartNotFoundError, +) +from superset.commands.exceptions import CommandException +from superset.extensions import event_logger +from superset.mcp_service.chart.chart_helpers import find_chart_by_identifier +from superset.mcp_service.chart.schemas import ( + DeleteChartRequest, + DeleteChartResponse, +) +from superset.mcp_service.utils import escape_llm_context_delimiters + +logger = logging.getLogger(__name__) Review Comment: Declining: bare `logger = logging.getLogger(__name__)` is the convention in every mcp_service module; mypy passes without the annotation. ########## superset/mcp_service/chart/tool/delete_chart.py: ########## @@ -0,0 +1,161 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +MCP tool: delete_chart +""" + +import logging + +from fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset import is_feature_enabled +from superset.commands.chart.exceptions import ( + ChartDeleteFailedReportsExistError, + ChartForbiddenError, + ChartNotFoundError, +) +from superset.commands.exceptions import CommandException +from superset.extensions import event_logger +from superset.mcp_service.chart.chart_helpers import find_chart_by_identifier +from superset.mcp_service.chart.schemas import ( + DeleteChartRequest, + DeleteChartResponse, +) +from superset.mcp_service.utils import escape_llm_context_delimiters + +logger = logging.getLogger(__name__) Review Comment: Declining: bare `logger = logging.getLogger(__name__)` is the convention in every mcp_service module; mypy passes without the annotation. ########## superset/mcp_service/dashboard/tool/delete_dashboard.py: ########## @@ -0,0 +1,188 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +MCP tool: delete_dashboard +""" + +import logging +from typing import Any + +from fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset import is_feature_enabled +from superset.commands.dashboard.exceptions import ( + DashboardDeleteFailedReportsExistError, + DashboardForbiddenError, + DashboardNotFoundError, +) +from superset.commands.exceptions import CommandException +from superset.extensions import event_logger +from superset.mcp_service.dashboard.schemas import ( + DeleteDashboardRequest, + DeleteDashboardResponse, +) +from superset.mcp_service.utils import escape_llm_context_delimiters + +logger = logging.getLogger(__name__) Review Comment: Declining: bare `logger = logging.getLogger(__name__)` is the convention in every mcp_service module; mypy passes without the annotation. ########## superset/mcp_service/dashboard/tool/delete_dashboard.py: ########## @@ -0,0 +1,188 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +MCP tool: delete_dashboard +""" + +import logging +from typing import Any + +from fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset import is_feature_enabled +from superset.commands.dashboard.exceptions import ( + DashboardDeleteFailedReportsExistError, + DashboardForbiddenError, + DashboardNotFoundError, +) +from superset.commands.exceptions import CommandException +from superset.extensions import event_logger +from superset.mcp_service.dashboard.schemas import ( + DeleteDashboardRequest, + DeleteDashboardResponse, +) +from superset.mcp_service.utils import escape_llm_context_delimiters + +logger = logging.getLogger(__name__) + + +def _find_dashboard_by_identifier(identifier: int | str) -> Any | None: + """Resolve a dashboard by numeric ID, UUID string, or slug. Returns None.""" + from superset.daos.dashboard import DashboardDAO + + if isinstance(identifier, int) or ( + isinstance(identifier, str) and identifier.isdigit() + ): + return DashboardDAO.find_by_id(int(identifier)) + # Try UUID, then fall back to slug. + dashboard = DashboardDAO.find_by_id(identifier, id_column="uuid") + if dashboard: + return dashboard + try: + return DashboardDAO.get_by_id_or_slug(identifier) + except DashboardNotFoundError: + return None + + +def _rollback() -> None: + from superset import db + + try: + db.session.rollback() # pylint: disable=consider-using-transaction + except SQLAlchemyError: + logger.warning( + "Database rollback failed during delete_dashboard error handling" + ) + + +def _routes_to_soft_delete() -> bool: + """Mirror the ``BaseDAO.delete`` routing predicate so the response can + report whether the row was trashed (restorable) or permanently removed.""" + from superset.models.dashboard import Dashboard + from superset.models.helpers import SoftDeleteMixin + + return issubclass(Dashboard, SoftDeleteMixin) and is_feature_enabled("SOFT_DELETE") + + +@tool( + tags=["mutate"], + class_permission_name="Dashboard", + annotations=ToolAnnotations( + title="Delete dashboard", + readOnlyHint=False, + destructiveHint=True, + ), +) +async def delete_dashboard( + request: DeleteDashboardRequest, ctx: Context +) -> DeleteDashboardResponse: + """Delete a dashboard. + + Identify the dashboard by numeric ID, UUID string, or slug. When the + ``SOFT_DELETE`` feature flag is enabled the dashboard is moved to trash and + can be restored by an owner or Admin; otherwise the delete is permanent and + cannot be undone. The ``soft_deleted`` response field reports which + happened. It removes the dashboard container only — the charts on it are + NOT deleted. The caller must own the dashboard (or be an Admin); dashboards + with attached alerts/reports cannot be deleted until those are removed. + + Example: + ```json + {"identifier": 42} + ``` + + Returns success with the deleted dashboard's id/title, or an error. When the + caller lacks permission, ``permission_denied`` is true — do not retry; ask + the user. + """ + await ctx.info("Deleting dashboard: identifier=%s" % (request.identifier,)) + + dashboard = _find_dashboard_by_identifier(request.identifier) + if not dashboard: + safe_id = escape_llm_context_delimiters(str(request.identifier)[:200]) + msg = ( + f"No dashboard found with identifier: {safe_id}. " + "Use list_dashboards to get valid dashboard IDs." + ) + return DeleteDashboardResponse(success=False, error=msg, error_type="NotFound") + + dashboard_id = dashboard.id + dashboard_name = dashboard.dashboard_title Review Comment: Declining: bare `logger = logging.getLogger(__name__)` is the convention in every mcp_service module; mypy passes without the annotation. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
