Copilot commented on code in PR #40361:
URL: https://github.com/apache/superset/pull/40361#discussion_r3326664474


##########
superset/mcp_service/saved_query/tool/update_saved_query.py:
##########
@@ -0,0 +1,142 @@
+# 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.
+
+import logging
+from typing import Any
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.saved_query.schemas import (
+    UpdateSavedQueryRequest,
+    UpdateSavedQueryResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+_LOGGABLE_FIELDS = (
+    "label",
+    "sql",
+    "db_id",
+    "schema",
+    "description",
+    "template_parameters",
+)
+
+
+def _build_update_properties(request: "UpdateSavedQueryRequest") -> dict[str, 
Any]:
+    """Return only the fields the caller explicitly provided."""
+    fields = {
+        "label": request.label,
+        "sql": request.sql,
+        "db_id": request.db_id,
+        "schema": request.schema,
+        "description": request.description,
+        "template_parameters": request.template_parameters,
+    }
+    return {k: v for k, v in fields.items() if v is not None}
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="SavedQuery",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Update saved query",
+        readOnlyHint=False,
+        destructiveHint=True,
+    ),
+)
+async def update_saved_query(
+    request: UpdateSavedQueryRequest, ctx: Context
+) -> UpdateSavedQueryResponse:
+    """Update an existing saved query's label, SQL, database, schema, or 
description.
+
+    All fields except ``id`` are optional — only provided fields are changed.
+    The query must already exist and the caller must have write access to
+    the SavedQuery resource.
+
+    Example: rename only
+    ```json
+    {"id": 42, "label": "Monthly Revenue"}
+    ```
+
+    Example: update SQL and description
+    ```json
+    {"id": 42, "sql": "SELECT * FROM orders LIMIT 100", "description": "All 
orders"}
+    ```
+    """
+    changed = [f for f in _LOGGABLE_FIELDS if getattr(request, f, None) is not 
None]
+    await ctx.info("Updating saved query: id=%s, fields=%s" % (request.id, 
changed))
+
+    try:
+        from superset.commands.query.exceptions import (
+            SavedQueryInvalidError,
+            SavedQueryNotFoundError,
+            SavedQueryUpdateFailedError,
+        )
+        from superset.commands.query.update import UpdateSavedQueryCommand
+        from superset.mcp_service.utils.url_utils import get_superset_base_url
+
+        properties = _build_update_properties(request)
+
+        with event_logger.log_context(action="mcp.update_saved_query.update"):
+            saved_query = UpdateSavedQueryCommand(request.id, properties).run()
+

Review Comment:
   update_saved_query allows requests with only `id` and no other fields. That 
results in a no-op update (still hitting the DB/transaction) and makes it hard 
for tool callers to detect they forgot to pass changes. Consider returning a 
validation error when no updatable fields are provided.



##########
superset/commands/query/create.py:
##########
@@ -0,0 +1,75 @@
+# 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.
+import logging
+from functools import partial
+from typing import Any
+
+from flask import g
+from flask_appbuilder.models.sqla import Model
+from marshmallow import ValidationError
+
+from superset.commands.base import BaseCommand, CreateMixin
+from superset.commands.query.exceptions import (
+    SavedQueryCreateFailedError,
+    SavedQueryInvalidError,
+)
+from superset.daos.query import SavedQueryDAO
+from superset.utils.decorators import on_error, transaction
+
+logger = logging.getLogger(__name__)
+
+
+class CreateSavedQueryCommand(CreateMixin, BaseCommand):
+    def __init__(self, data: dict[str, Any]):
+        self._properties = data.copy()
+
+    @transaction(on_error=partial(on_error, 
reraise=SavedQueryCreateFailedError))
+    def run(self) -> Model:
+        self.validate()
+        self._properties["user_id"] = g.user.id
+        saved_query = SavedQueryDAO.create(attributes=self._properties)
+        return saved_query
+
+    def validate(self) -> None:
+        from superset.extensions import db, security_manager
+        from superset.models.core import Database
+
+        exceptions: list[ValidationError] = []
+
+        db_id = self._properties.get("db_id")
+        if not db_id:
+            exceptions.append(ValidationError("db_id is required", 
field_name="db_id"))
+            raise SavedQueryInvalidError(exceptions=exceptions)

Review Comment:
   CreateSavedQueryCommand.validate() uses `if not db_id`, which treats `0` as 
“missing” and returns a misleading "db_id is required" error. Using an explicit 
None check keeps the error semantics correct for all integer inputs.



##########
superset/mcp_service/saved_query/tool/create_saved_query.py:
##########
@@ -0,0 +1,126 @@
+# 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.
+
+import logging
+from typing import Any
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.saved_query.schemas import (
+    CreateSavedQueryRequest,
+    CreateSavedQueryResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="SavedQuery",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Create saved query",
+        readOnlyHint=False,
+        destructiveHint=False,
+    ),
+)
+async def create_saved_query(
+    request: CreateSavedQueryRequest, ctx: Context
+) -> CreateSavedQueryResponse:

Review Comment:
   No unit tests are added for the new create_saved_query tool behavior 
(success, invalid db_id, access denied, create failure). There are existing MCP 
tool tests for similar SQL Lab mutations (e.g. 
tests/unit_tests/mcp_service/sql_lab/tool/test_save_sql_query.py), so adding 
analogous tests would help prevent regressions.



##########
superset/commands/query/create.py:
##########
@@ -0,0 +1,75 @@
+# 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.
+import logging
+from functools import partial
+from typing import Any
+
+from flask import g
+from flask_appbuilder.models.sqla import Model
+from marshmallow import ValidationError
+
+from superset.commands.base import BaseCommand, CreateMixin
+from superset.commands.query.exceptions import (
+    SavedQueryCreateFailedError,
+    SavedQueryInvalidError,
+)
+from superset.daos.query import SavedQueryDAO
+from superset.utils.decorators import on_error, transaction
+
+logger = logging.getLogger(__name__)
+
+
+class CreateSavedQueryCommand(CreateMixin, BaseCommand):
+    def __init__(self, data: dict[str, Any]):
+        self._properties = data.copy()
+
+    @transaction(on_error=partial(on_error, 
reraise=SavedQueryCreateFailedError))
+    def run(self) -> Model:
+        self.validate()
+        self._properties["user_id"] = g.user.id
+        saved_query = SavedQueryDAO.create(attributes=self._properties)
+        return saved_query
+
+    def validate(self) -> None:
+        from superset.extensions import db, security_manager
+        from superset.models.core import Database
+
+        exceptions: list[ValidationError] = []
+
+        db_id = self._properties.get("db_id")
+        if not db_id:
+            exceptions.append(ValidationError("db_id is required", 
field_name="db_id"))
+            raise SavedQueryInvalidError(exceptions=exceptions)

Review Comment:
   CreateSavedQueryCommand.validate() uses `if not db_id`, which treats `0` as 
“missing” and returns a misleading "db_id is required" error. Using an explicit 
None check keeps the error semantics correct for all integer inputs.



##########
superset/mcp_service/saved_query/tool/update_saved_query.py:
##########
@@ -0,0 +1,142 @@
+# 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.
+
+import logging
+from typing import Any
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.saved_query.schemas import (
+    UpdateSavedQueryRequest,
+    UpdateSavedQueryResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+_LOGGABLE_FIELDS = (
+    "label",
+    "sql",
+    "db_id",
+    "schema",
+    "description",
+    "template_parameters",
+)
+
+
+def _build_update_properties(request: "UpdateSavedQueryRequest") -> dict[str, 
Any]:
+    """Return only the fields the caller explicitly provided."""
+    fields = {
+        "label": request.label,
+        "sql": request.sql,
+        "db_id": request.db_id,
+        "schema": request.schema,
+        "description": request.description,
+        "template_parameters": request.template_parameters,
+    }
+    return {k: v for k, v in fields.items() if v is not None}
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="SavedQuery",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Update saved query",
+        readOnlyHint=False,
+        destructiveHint=True,
+    ),
+)
+async def update_saved_query(
+    request: UpdateSavedQueryRequest, ctx: Context
+) -> UpdateSavedQueryResponse:
+    """Update an existing saved query's label, SQL, database, schema, or 
description.
+
+    All fields except ``id`` are optional — only provided fields are changed.
+    The query must already exist and the caller must have write access to
+    the SavedQuery resource.
+
+    Example: rename only
+    ```json
+    {"id": 42, "label": "Monthly Revenue"}
+    ```
+
+    Example: update SQL and description
+    ```json
+    {"id": 42, "sql": "SELECT * FROM orders LIMIT 100", "description": "All 
orders"}
+    ```
+    """
+    changed = [f for f in _LOGGABLE_FIELDS if getattr(request, f, None) is not 
None]
+    await ctx.info("Updating saved query: id=%s, fields=%s" % (request.id, 
changed))
+
+    try:
+        from superset.commands.query.exceptions import (
+            SavedQueryInvalidError,
+            SavedQueryNotFoundError,
+            SavedQueryUpdateFailedError,
+        )
+        from superset.commands.query.update import UpdateSavedQueryCommand
+        from superset.mcp_service.utils.url_utils import get_superset_base_url
+
+        properties = _build_update_properties(request)
+
+        with event_logger.log_context(action="mcp.update_saved_query.update"):
+            saved_query = UpdateSavedQueryCommand(request.id, properties).run()
+

Review Comment:
   update_saved_query allows requests with only `id` and no other fields. That 
results in a no-op update (still hitting the DB/transaction) and makes it hard 
for tool callers to detect they forgot to pass changes. Consider returning a 
validation error when no updatable fields are provided.



##########
superset/mcp_service/saved_query/tool/update_saved_query.py:
##########
@@ -0,0 +1,142 @@
+# 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.
+
+import logging
+from typing import Any
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.saved_query.schemas import (
+    UpdateSavedQueryRequest,
+    UpdateSavedQueryResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+_LOGGABLE_FIELDS = (
+    "label",
+    "sql",
+    "db_id",
+    "schema",
+    "description",
+    "template_parameters",
+)
+
+
+def _build_update_properties(request: "UpdateSavedQueryRequest") -> dict[str, 
Any]:
+    """Return only the fields the caller explicitly provided."""
+    fields = {
+        "label": request.label,
+        "sql": request.sql,
+        "db_id": request.db_id,
+        "schema": request.schema,
+        "description": request.description,
+        "template_parameters": request.template_parameters,
+    }
+    return {k: v for k, v in fields.items() if v is not None}
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="SavedQuery",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Update saved query",
+        readOnlyHint=False,
+        destructiveHint=True,
+    ),
+)
+async def update_saved_query(
+    request: UpdateSavedQueryRequest, ctx: Context
+) -> UpdateSavedQueryResponse:

Review Comment:
   No unit tests are added for the new update_saved_query tool behavior 
(success, not-found vs access-filtered IDs, invalid db_id, update failure, and 
the 'no fields to update' validation). The repo has established MCP tool 
testing patterns (e.g. 
tests/unit_tests/mcp_service/sql_lab/tool/test_save_sql_query.py) that can be 
followed here.



##########
superset/mcp_service/saved_query/tool/create_saved_query.py:
##########
@@ -0,0 +1,126 @@
+# 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.
+
+import logging
+from typing import Any
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.saved_query.schemas import (
+    CreateSavedQueryRequest,
+    CreateSavedQueryResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="SavedQuery",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Create saved query",
+        readOnlyHint=False,
+        destructiveHint=False,
+    ),
+)
+async def create_saved_query(
+    request: CreateSavedQueryRequest, ctx: Context
+) -> CreateSavedQueryResponse:

Review Comment:
   No unit tests are added for the new create_saved_query tool behavior 
(success, invalid db_id, access denied, create failure). There are existing MCP 
tool tests for similar SQL Lab mutations (e.g. 
tests/unit_tests/mcp_service/sql_lab/tool/test_save_sql_query.py), so adding 
analogous tests would help prevent regressions.



##########
superset/mcp_service/saved_query/tool/update_saved_query.py:
##########
@@ -0,0 +1,142 @@
+# 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.
+
+import logging
+from typing import Any
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.saved_query.schemas import (
+    UpdateSavedQueryRequest,
+    UpdateSavedQueryResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+_LOGGABLE_FIELDS = (
+    "label",
+    "sql",
+    "db_id",
+    "schema",
+    "description",
+    "template_parameters",
+)
+
+
+def _build_update_properties(request: "UpdateSavedQueryRequest") -> dict[str, 
Any]:
+    """Return only the fields the caller explicitly provided."""
+    fields = {
+        "label": request.label,
+        "sql": request.sql,
+        "db_id": request.db_id,
+        "schema": request.schema,
+        "description": request.description,
+        "template_parameters": request.template_parameters,
+    }
+    return {k: v for k, v in fields.items() if v is not None}
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="SavedQuery",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Update saved query",
+        readOnlyHint=False,
+        destructiveHint=True,
+    ),
+)
+async def update_saved_query(
+    request: UpdateSavedQueryRequest, ctx: Context
+) -> UpdateSavedQueryResponse:

Review Comment:
   No unit tests are added for the new update_saved_query tool behavior 
(success, not-found vs access-filtered IDs, invalid db_id, update failure, and 
the 'no fields to update' validation). The repo has established MCP tool 
testing patterns (e.g. 
tests/unit_tests/mcp_service/sql_lab/tool/test_save_sql_query.py) that can be 
followed here.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to