aminghadersohi commented on code in PR #40355:
URL: https://github.com/apache/superset/pull/40355#discussion_r3336183941


##########
superset/mcp_service/theme/tool/update_theme.py:
##########
@@ -0,0 +1,113 @@
+# 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 fastmcp import Context
+from marshmallow import ValidationError
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.theme.schemas import (
+    UpdateThemeRequest,
+    UpdateThemeResponse,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="Theme",
+    method_permission_name="write",
+    annotations=ToolAnnotations(
+        title="Update theme",
+        readOnlyHint=False,
+        destructiveHint=True,
+    ),
+)
+async def update_theme(
+    request: UpdateThemeRequest, ctx: Context
+) -> UpdateThemeResponse:
+    """Update an existing Superset theme's name or Ant Design token 
configuration.
+
+    Provide the ``id`` of the theme to update plus any fields to change.
+    Fields left as ``None`` are preserved from the existing theme.
+    System themes cannot be modified.
+    """
+    await ctx.info("Updating theme: id=%s" % (request.id,))
+
+    try:
+        from superset.commands.theme.exceptions import (
+            SystemThemeProtectedError,
+            ThemeNotFoundError,
+        )
+        from superset.commands.theme.update import UpdateThemeCommand
+        from superset.daos.theme import ThemeDAO
+        from superset.themes.schemas import ThemePutSchema
+
+        # Fetch current theme to support partial updates (merge missing fields)
+        existing = ThemeDAO.find_by_id(request.id)
+        if existing is None:
+            await ctx.warning("Theme not found: id=%s" % (request.id,))
+            return UpdateThemeResponse(id=None, error="Theme not found.")
+
+        theme_name = (
+            request.theme_name
+            if request.theme_name is not None
+            else existing.theme_name
+        )
+        json_data = (
+            request.json_data if request.json_data is not None else 
existing.json_data
+        )

Review Comment:
   Fixed in commit `6e48d04b52`. The root cause is accurate — the read of 
`existing` happened outside the `UpdateThemeCommand` transaction, creating a 
window for a concurrent write to overwrite the newer field value.
   
   The fix: instead of merging `existing` values into the command payload 
(which would send back stale data for fields the caller did not touch), we now 
build `update_properties` with **only the fields explicitly provided by the 
caller**. Schema validation still uses the merged values (required because 
`ThemePutSchema` mandates both `theme_name` and `json_data`), but only the 
caller-supplied fields reach `ThemeDAO.update`. A name-only request can no 
longer silently clobber a concurrently-updated `json_data`, and vice-versa.



##########
tests/unit_tests/mcp_service/theme/tool/test_create_theme.py:
##########
@@ -0,0 +1,364 @@
+# 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.
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+from superset.mcp_service.theme.schemas import CreateThemeRequest, 
UpdateThemeRequest
+from superset.utils import json
+
+
[email protected]
+def mcp_server():
+    return mcp
+
+
[email protected](autouse=True)
+def mock_auth():
+    from unittest.mock import Mock, patch as _patch
+
+    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
+
+
+# ---------------------------------------------------------------------------
+# Schema tests
+# ---------------------------------------------------------------------------
+
+
+def test_create_theme_request_string_json_data() -> None:
+    req = CreateThemeRequest(
+        theme_name="Blue Theme",
+        json_data='{"token": {"colorPrimary": "#1677ff"}}',
+    )
+    assert req.theme_name == "Blue Theme"
+    assert '"colorPrimary"' in req.json_data
+
+
+def test_create_theme_request_dict_json_data() -> None:
+    """json_data accepts a native dict and serializes it to a JSON string."""
+    req = CreateThemeRequest(
+        theme_name="Blue Theme",
+        json_data={"token": {"colorPrimary": "#1677ff"}},
+    )
+    assert isinstance(req.json_data, str)
+    parsed = json.loads(req.json_data)
+    assert parsed["token"]["colorPrimary"] == "#1677ff"
+
+
+def test_create_theme_request_missing_name_fails() -> None:
+    from pydantic import ValidationError
+
+    with pytest.raises(ValidationError):
+        CreateThemeRequest(json_data='{"token": {}}')
+
+
+def test_create_theme_request_missing_json_data_fails() -> None:
+    from pydantic import ValidationError
+
+    with pytest.raises(ValidationError):
+        CreateThemeRequest(theme_name="My Theme")
+
+
+# ---------------------------------------------------------------------------
+# Tool logic tests
+# ---------------------------------------------------------------------------
+
+
+def _make_mock_theme(id: int = 42, theme_name: str = "Blue Theme") -> 
MagicMock:
+    theme = MagicMock()
+    theme.id = id
+    theme.theme_name = theme_name
+    theme.json_data = '{"token": {"colorPrimary": "#1677ff"}}'
+    return theme
+
+
[email protected]
+async def test_create_theme_success(mcp_server: object) -> None:
+    """Happy path: theme created and ID returned."""
+    mock_theme = _make_mock_theme()
+
+    with (
+        patch("superset.mcp_service.theme.tool.create_theme.db") as mock_db,
+        patch(
+            "superset.mcp_service.theme.tool.create_theme.Theme",
+            return_value=mock_theme,
+        ),
+    ):

Review Comment:
   Already fixed. Commit `3298248dfa` moved `db` and `Theme` from inside the 
async function body to module-level imports in `create_theme.py`. The current 
code has:
   
   ```python
   from superset.extensions import db, event_logger
   from superset.models.core import Theme
   ```
   
   at the top of the file, so `superset.mcp_service.theme.tool.create_theme.db` 
and `superset.mcp_service.theme.tool.create_theme.Theme` are valid module-level 
attributes and the patch targets work correctly.



-- 
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