gkneighb commented on code in PR #41497: URL: https://github.com/apache/superset/pull/41497#discussion_r3540831272
########## tests/unit_tests/mcp_service/theme/tool/test_create_theme.py: ########## @@ -0,0 +1,171 @@ +# 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 create_theme MCP tool.""" + +import importlib +from unittest.mock import MagicMock, Mock, patch + +import pytest +from fastmcp import Client +from marshmallow import ValidationError + +from superset.mcp_service.app import mcp +from superset.utils import json + +# Resolve the module object directly so patch.object targets the module, not +# the function re-exported through __init__.py. +create_theme_module = importlib.import_module( + "superset.mcp_service.theme.tool.create_theme" +) + + +def _make_mock_theme( + theme_id: int = 7, + theme_name: str = "Corporate Blue", + uuid: str = "22222222-2222-2222-2222-222222222222", +) -> MagicMock: + theme = MagicMock() + theme.id = theme_id + theme.theme_name = theme_name + theme.uuid = uuid + return theme + + [email protected] +def mcp_server(): + 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 + + [email protected](create_theme_module.db.session, "commit") +@patch("superset.daos.theme.ThemeDAO.create") [email protected](create_theme_module, "_sanitize_and_validate_theme_config") [email protected] +async def test_create_theme_success_with_dict( + mock_sanitize, mock_create, mock_commit, mcp_server +): + """Happy path: dict json_data is sanitized, persisted, and id/uuid returned.""" + config = {"token": {"colorPrimary": "#1d4ed8"}} + mock_sanitize.return_value = config + mock_create.return_value = _make_mock_theme() + + async with Client(mcp_server) as client: + result = await client.call_tool( + "create_theme", + { + "request": { + "theme_name": "Corporate Blue", + "json_data": config, + } + }, + ) + data = json.loads(result.content[0].text) + + assert data["success"] is True + assert data["id"] == 7 + assert data["uuid"] == "22222222-2222-2222-2222-222222222222" + assert data["theme_name"] == "Corporate Blue" + mock_sanitize.assert_called_once_with(config) + # json_data persisted as a serialized string + create_kwargs = mock_create.call_args.kwargs["attributes"] + assert isinstance(create_kwargs["json_data"], str) + assert json.loads(create_kwargs["json_data"]) == config + mock_commit.assert_called_once() + + [email protected](create_theme_module.db.session, "commit") +@patch("superset.daos.theme.ThemeDAO.create") [email protected](create_theme_module, "_sanitize_and_validate_theme_config") [email protected] +async def test_create_theme_success_with_json_string( + mock_sanitize, mock_create, mock_commit, mcp_server +): + """json_data supplied as a JSON string is parsed and accepted.""" + config = {"token": {"colorPrimary": "#abcdef"}} + mock_sanitize.return_value = config + mock_create.return_value = _make_mock_theme(theme_id=9) + + async with Client(mcp_server) as client: + result = await client.call_tool( + "create_theme", + { + "request": { + "theme_name": "From String", + "json_data": json.dumps(config), + } + }, + ) + data = json.loads(result.content[0].text) + + assert data["success"] is True + assert data["id"] == 9 + mock_sanitize.assert_called_once_with(config) + + +@patch("superset.daos.theme.ThemeDAO.create") [email protected](create_theme_module, "_sanitize_and_validate_theme_config") [email protected] +async def test_create_theme_invalid_config(mock_sanitize, mock_create, mcp_server): + """Sanitizer ValidationError yields a ValidationError response, no DAO call.""" + mock_sanitize.side_effect = ValidationError("Invalid theme configuration structure") + + async with Client(mcp_server) as client: + result = await client.call_tool( + "create_theme", + { + "request": { + "theme_name": "Bad", + "json_data": {"not": "a theme"}, + } + }, + ) + data = json.loads(result.content[0].text) + + assert data["success"] is False + assert data["error_type"] == "ValidationError" + mock_create.assert_not_called() + + +@patch("superset.daos.theme.ThemeDAO.create") [email protected] +async def test_create_theme_invalid_json_string(mock_create, mcp_server): + """A malformed JSON string is rejected before sanitization.""" + async with Client(mcp_server) as client: + result = await client.call_tool( + "create_theme", + { + "request": { + "theme_name": "Broken", + "json_data": "{not valid json", + } + }, + ) + data = json.loads(result.content[0].text) + + assert data["success"] is False + assert data["error_type"] == "ValidationError" + mock_create.assert_not_called() Review Comment: Added test_create_theme_rbac_denied in 33ae92251e, following the mutate-tool convention — RBAC enabled, can_access mocked False, asserts denial and the can_write-on-Theme check. ########## superset/mcp_service/theme/tool/create_theme.py: ########## @@ -0,0 +1,151 @@ +# 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. + +""" +Create theme FastMCP tool + +Creates a reusable Superset theme from an antd design-token configuration. +The supplied json_data is sanitized and validated with the same routine the +REST API uses before the theme is persisted via ThemeDAO. +""" + +import logging +from typing import Any + +from fastmcp import Context +from marshmallow import ValidationError +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.extensions import db, event_logger +from superset.mcp_service.theme.schemas import CreateThemeRequest, CreateThemeResponse +from superset.themes.schemas import _sanitize_and_validate_theme_config +from superset.utils import json + +logger = logging.getLogger(__name__) + + +@tool( + tags=["mutate"], + class_permission_name="Theme", + method_permission_name="write", + annotations=ToolAnnotations( + title="Create theme", + readOnlyHint=False, + destructiveHint=False, + ), +) +async def create_theme( + request: CreateThemeRequest, ctx: Context +) -> CreateThemeResponse: + """Create a reusable theme from antd design tokens. + + Accepts a theme name and an antd design-token configuration (json_data), + supplied either as a JSON object or a JSON string. The configuration is + sanitized and validated the same way the REST API validates themes before + the theme is persisted. + + Required fields: + - theme_name: Human-readable name for the theme + - json_data: The antd design-token configuration (dict or JSON string) + + Example: + ```json + { + "theme_name": "Corporate Blue", + "json_data": {"token": {"colorPrimary": "#1d4ed8"}} + } + ``` + + Returns CreateThemeResponse with the new theme's id and uuid on success, + or an error response (error_type="ValidationError") if the configuration + is invalid. + """ + await ctx.info("Creating theme: theme_name=%s" % (request.theme_name,)) + + # Parse json_data into a dict (accept dict or JSON string) + config_dict: dict[str, Any] + if isinstance(request.json_data, str): + try: + parsed = json.loads(request.json_data) + except (TypeError, json.JSONDecodeError) as exc: + await ctx.warning("Invalid JSON in json_data: %s" % (str(exc),)) + return CreateThemeResponse( + success=False, + error=f"json_data is not valid JSON: {exc}", + error_type="ValidationError", + ) + if not isinstance(parsed, dict): + await ctx.warning("json_data did not parse to an object") + return CreateThemeResponse( + success=False, + error="json_data must be a JSON object", + error_type="ValidationError", + ) + config_dict = parsed + else: + config_dict = request.json_data + + # Sanitize and validate using the same routine as the REST API + try: + sanitized = _sanitize_and_validate_theme_config(config_dict) + except ValidationError as exc: + await ctx.warning("Theme validation failed: %s" % (exc.messages,)) + return CreateThemeResponse( + success=False, + error=str(exc.messages), + error_type="ValidationError", + ) + + try: + from superset.daos.theme import ThemeDAO + + with event_logger.log_context(action="mcp.create_theme"): + theme = ThemeDAO.create( + attributes={ + "theme_name": request.theme_name, + "json_data": json.dumps(sanitized), + "is_system": False, + } + ) Review Comment: Fixed in 33ae92251e — CreateThemeRequest now rejects blank/whitespace names with the same message as the REST ThemePostSchema validator, plus a test. ########## superset/mcp_service/theme/tool/create_theme.py: ########## @@ -0,0 +1,151 @@ +# 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. + +""" +Create theme FastMCP tool + +Creates a reusable Superset theme from an antd design-token configuration. +The supplied json_data is sanitized and validated with the same routine the +REST API uses before the theme is persisted via ThemeDAO. +""" + +import logging +from typing import Any + +from fastmcp import Context +from marshmallow import ValidationError +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.extensions import db, event_logger +from superset.mcp_service.theme.schemas import CreateThemeRequest, CreateThemeResponse +from superset.themes.schemas import _sanitize_and_validate_theme_config +from superset.utils import json + +logger = logging.getLogger(__name__) + + +@tool( + tags=["mutate"], + class_permission_name="Theme", + method_permission_name="write", + annotations=ToolAnnotations( + title="Create theme", + readOnlyHint=False, + destructiveHint=False, + ), +) +async def create_theme( + request: CreateThemeRequest, ctx: Context +) -> CreateThemeResponse: + """Create a reusable theme from antd design tokens. + + Accepts a theme name and an antd design-token configuration (json_data), + supplied either as a JSON object or a JSON string. The configuration is + sanitized and validated the same way the REST API validates themes before + the theme is persisted. + + Required fields: + - theme_name: Human-readable name for the theme + - json_data: The antd design-token configuration (dict or JSON string) + + Example: + ```json + { + "theme_name": "Corporate Blue", + "json_data": {"token": {"colorPrimary": "#1d4ed8"}} + } + ``` + + Returns CreateThemeResponse with the new theme's id and uuid on success, + or an error response (error_type="ValidationError") if the configuration + is invalid. + """ + await ctx.info("Creating theme: theme_name=%s" % (request.theme_name,)) + + # Parse json_data into a dict (accept dict or JSON string) + config_dict: dict[str, Any] + if isinstance(request.json_data, str): + try: + parsed = json.loads(request.json_data) + except (TypeError, json.JSONDecodeError) as exc: + await ctx.warning("Invalid JSON in json_data: %s" % (str(exc),)) + return CreateThemeResponse( + success=False, + error=f"json_data is not valid JSON: {exc}", + error_type="ValidationError", + ) + if not isinstance(parsed, dict): + await ctx.warning("json_data did not parse to an object") + return CreateThemeResponse( + success=False, + error="json_data must be a JSON object", + error_type="ValidationError", + ) + config_dict = parsed + else: + config_dict = request.json_data + + # Sanitize and validate using the same routine as the REST API + try: + sanitized = _sanitize_and_validate_theme_config(config_dict) + except ValidationError as exc: + await ctx.warning("Theme validation failed: %s" % (exc.messages,)) + return CreateThemeResponse( + success=False, + error=str(exc.messages), + error_type="ValidationError", + ) + + try: + from superset.daos.theme import ThemeDAO + + with event_logger.log_context(action="mcp.create_theme"): + theme = ThemeDAO.create( + attributes={ + "theme_name": request.theme_name, + "json_data": json.dumps(sanitized), + "is_system": False, + } + ) + db.session.commit() # pylint: disable=consider-using-transaction + + await ctx.info( + "Theme created: id=%s, uuid=%s" % (theme.id, getattr(theme, "uuid", None)) + ) + return CreateThemeResponse( + success=True, + id=theme.id, + uuid=str(uuid) if (uuid := getattr(theme, "uuid", None)) else None, + theme_name=theme.theme_name, + message=f"Theme '{theme.theme_name}' created successfully", + ) Review Comment: Fixed in 33ae92251e — the create response and message now wrap theme_name via sanitize_for_llm_context like the list/get paths, plus a test with a hostile name. ########## tests/unit_tests/mcp_service/theme/tool/test_create_theme.py: ########## @@ -0,0 +1,171 @@ +# 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 create_theme MCP tool.""" + +import importlib +from unittest.mock import MagicMock, Mock, patch + +import pytest +from fastmcp import Client +from marshmallow import ValidationError + +from superset.mcp_service.app import mcp +from superset.utils import json + +# Resolve the module object directly so patch.object targets the module, not +# the function re-exported through __init__.py. +create_theme_module = importlib.import_module( + "superset.mcp_service.theme.tool.create_theme" +) + + +def _make_mock_theme( + theme_id: int = 7, + theme_name: str = "Corporate Blue", + uuid: str = "22222222-2222-2222-2222-222222222222", +) -> MagicMock: + theme = MagicMock() + theme.id = theme_id + theme.theme_name = theme_name + theme.uuid = uuid + return theme + + [email protected] +def mcp_server(): + 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 + + [email protected](create_theme_module.db.session, "commit") +@patch("superset.daos.theme.ThemeDAO.create") [email protected](create_theme_module, "_sanitize_and_validate_theme_config") [email protected] +async def test_create_theme_success_with_dict( + mock_sanitize, mock_create, mock_commit, mcp_server +): + """Happy path: dict json_data is sanitized, persisted, and id/uuid returned.""" + config = {"token": {"colorPrimary": "#1d4ed8"}} + mock_sanitize.return_value = config + mock_create.return_value = _make_mock_theme() + + async with Client(mcp_server) as client: + result = await client.call_tool( + "create_theme", + { + "request": { + "theme_name": "Corporate Blue", + "json_data": config, + } + }, + ) + data = json.loads(result.content[0].text) + + assert data["success"] is True + assert data["id"] == 7 + assert data["uuid"] == "22222222-2222-2222-2222-222222222222" + assert data["theme_name"] == "Corporate Blue" Review Comment: Addressed in 33ae92251e — the happy-path assertion now tolerates the wrapper (substring match, same as the list/get tests) and a dedicated test asserts a hostile name comes back wrapped in UNTRUSTED-CONTENT delimiters. ########## tests/unit_tests/mcp_service/theme/tool/test_get_theme_info.py: ########## @@ -0,0 +1,105 @@ +# 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 get_theme_info MCP tool.""" + +from unittest.mock import MagicMock, Mock, patch + +import pytest +from fastmcp import Client + +from superset.mcp_service.app import mcp +from superset.utils import json + + +def create_mock_theme( + theme_id: int = 1, + theme_name: str = "Corporate Blue", + uuid: str = "11111111-1111-1111-1111-111111111111", +) -> MagicMock: + theme = MagicMock() + theme.id = theme_id + theme.theme_name = theme_name + theme.json_data = '{"token": {"colorPrimary": "#1d4ed8"}}' + theme.uuid = uuid + theme.is_system = False + theme.is_system_default = False + theme.is_system_dark = False + theme.changed_on = None + theme.created_on = None + return theme + + [email protected] +def mcp_server(): + return mcp Review Comment: Annotations added in 33ae92251e. ########## tests/unit_tests/mcp_service/theme/tool/test_get_theme_info.py: ########## @@ -0,0 +1,105 @@ +# 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 get_theme_info MCP tool.""" + +from unittest.mock import MagicMock, Mock, patch + +import pytest +from fastmcp import Client + +from superset.mcp_service.app import mcp +from superset.utils import json + + +def create_mock_theme( + theme_id: int = 1, + theme_name: str = "Corporate Blue", + uuid: str = "11111111-1111-1111-1111-111111111111", +) -> MagicMock: + theme = MagicMock() + theme.id = theme_id + theme.theme_name = theme_name + theme.json_data = '{"token": {"colorPrimary": "#1d4ed8"}}' + theme.uuid = uuid + theme.is_system = False + theme.is_system_default = False + theme.is_system_dark = False + theme.changed_on = None + theme.created_on = None + return theme + + [email protected] +def mcp_server(): + 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: Annotations added in 33ae92251e. ########## tests/unit_tests/mcp_service/theme/tool/test_get_theme_info.py: ########## @@ -0,0 +1,105 @@ +# 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 get_theme_info MCP tool.""" + +from unittest.mock import MagicMock, Mock, patch + +import pytest +from fastmcp import Client + +from superset.mcp_service.app import mcp +from superset.utils import json + + +def create_mock_theme( + theme_id: int = 1, + theme_name: str = "Corporate Blue", + uuid: str = "11111111-1111-1111-1111-111111111111", +) -> MagicMock: + theme = MagicMock() + theme.id = theme_id + theme.theme_name = theme_name + theme.json_data = '{"token": {"colorPrimary": "#1d4ed8"}}' + theme.uuid = uuid + theme.is_system = False + theme.is_system_default = False + theme.is_system_dark = False + theme.changed_on = None + theme.created_on = None + return theme + + [email protected] +def mcp_server(): + 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 + + +@patch("superset.daos.theme.ThemeDAO.find_by_id") [email protected] +async def test_get_theme_info_by_id_success(mock_find, mcp_server): + """Returns ThemeInfo when the theme is found by numeric ID.""" + mock_find.return_value = create_mock_theme() + async with Client(mcp_server) as client: + result = await client.call_tool( + "get_theme_info", {"request": {"identifier": 1}} + ) + data = json.loads(result.content[0].text) + assert data["id"] == 1 + assert "Corporate Blue" in data["theme_name"] + assert "colorPrimary" in data["json_data"] + Review Comment: Annotations added in 33ae92251e. ########## tests/unit_tests/mcp_service/theme/tool/test_create_theme.py: ########## @@ -0,0 +1,171 @@ +# 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 create_theme MCP tool.""" + +import importlib +from unittest.mock import MagicMock, Mock, patch + +import pytest +from fastmcp import Client +from marshmallow import ValidationError + +from superset.mcp_service.app import mcp +from superset.utils import json + +# Resolve the module object directly so patch.object targets the module, not +# the function re-exported through __init__.py. +create_theme_module = importlib.import_module( + "superset.mcp_service.theme.tool.create_theme" +) + + +def _make_mock_theme( + theme_id: int = 7, + theme_name: str = "Corporate Blue", + uuid: str = "22222222-2222-2222-2222-222222222222", +) -> MagicMock: + theme = MagicMock() + theme.id = theme_id + theme.theme_name = theme_name + theme.uuid = uuid + return theme + + [email protected] +def mcp_server(): + return mcp Review Comment: Annotations added in 33ae92251e. -- 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]
