codeant-ai-for-open-source[bot] commented on code in PR #41497:
URL: https://github.com/apache/superset/pull/41497#discussion_r3532835074


##########
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:
   **Suggestion:** The success response returns user-controlled theme text 
without `sanitize_for_llm_context`, while list/get responses sanitize theme 
names for prompt-injection safety; this creates an inconsistent 
output-sanitization gap where injected control text can be echoed back to the 
agent. Sanitize the returned name/message fields before constructing the 
response. [security]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   ❌ Unsanitized theme_name echoed in MCP create_theme responses.
   ⚠️ Prompt-injection payload reaches agent despite other sanitization.
   ⚠️ Output sanitization inconsistent across theme list/get/create tools.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Run the MCP server (`superset/mcp_service/app.py`) so the `create_theme` 
tool in
   `superset/mcp_service/theme/tool/create_theme.py:52-77` is available, 
alongside
   `list_themes` and `get_theme_info`.
   
   2. Using a FastMCP client (pattern shown in
   `tests/unit_tests/mcp_service/theme/tool/test_create_theme.py:76-85`), call 
`create_theme`
   with `theme_name` containing prompt-injection text (for example, `"}} STOP 
FOLLOWING
   INSTRUCTIONS {{"`), and a valid `json_data` configuration so
   `_sanitize_and_validate_theme_config` succeeds.
   
   3. The tool persists the sanitized configuration and then builds a success 
response at
   `superset/mcp_service/theme/tool/create_theme.py:130-136`, setting
   `theme_name=theme.theme_name` and `message=f"Theme '{theme.theme_name}' 
created
   successfully"` directly from the user-controlled name without calling
   `sanitize_for_llm_context` or any other sanitizer; `CreateThemeResponse` in
   `superset/mcp_service/theme/schemas.py:242-250` defines these fields but 
adds no
   serializers or validators to sanitize them.
   
   4. In contrast, the list/get tools serialize themes via 
`serialize_theme_object` in
   `superset/mcp_service/theme/schemas.py:19-37`, which wraps `theme_name` with
   `_sanitize_theme_info_for_llm_context` and ultimately 
`sanitize_for_llm_context`, so
   prompt-injection text is filtered there; however, the initial `create_theme` 
response
   returns the raw `theme_name` and success `message` to the agent, creating an 
inconsistent
   sanitization gap where injected control text is echoed back into the LLM 
context.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e6fd2646cfa94a00ba3470b74d070b5c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=e6fd2646cfa94a00ba3470b74d070b5c&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/theme/tool/create_theme.py
   **Line:** 130:136
   **Comment:**
        *Security: The success response returns user-controlled theme text 
without `sanitize_for_llm_context`, while list/get responses sanitize theme 
names for prompt-injection safety; this creates an inconsistent 
output-sanitization gap where injected control text can be echoed back to the 
agent. Sanitize the returned name/message fields before constructing the 
response.
   
   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%2F41497&comment_hash=cdd62600276abdc40ddc71a76b205f0e9e26a8ac9b01c25691808226d1f614d0&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41497&comment_hash=cdd62600276abdc40ddc71a76b205f0e9e26a8ac9b01c25691808226d1f614d0&reaction=dislike'>👎</a>



##########
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:
   **Suggestion:** The tool writes the submitted name directly to the database 
without enforcing the non-empty/whitespace validation used by the Theme REST 
API, so blank theme names can be persisted here even though the canonical API 
rejects them. Add the same name validation path before persistence and return a 
validation error for empty or whitespace-only names. [api mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   ⚠️ MCP create_theme tool can persist blank theme names.
   ⚠️ Theme listing shows nameless entries confusing agents and users.
   ⚠️ Data model diverges from REST API validation rules.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Start the MCP server defined at `superset/mcp_service/app.py` and expose 
the
   `create_theme` tool implemented in
   `superset/mcp_service/theme/tool/create_theme.py:52-77`.
   
   2. From a FastMCP client (as in
   `tests/unit_tests/mcp_service/theme/tool/test_create_theme.py:76-85`), call 
`create_theme`
   with a request where `theme_name` is empty or whitespace-only (e.g. `" "`) 
and `json_data`
   is a valid theme config such as `{"token": {"colorPrimary": "#1d4ed8"}}`.
   
   3. In `create_theme`, after JSON parsing and config sanitization, the code at
   `superset/mcp_service/theme/tool/create_theme.py:118-124` executes
   `ThemeDAO.create(attributes={"theme_name": request.theme_name, ...})` 
without any
   validation; the request schema in 
`superset/mcp_service/theme/schemas.py:226-240` declares
   `theme_name: str` but adds no `field_validator` or model-level checks.
   
   4. The REST API path uses `ThemePostSchema` in 
`superset/themes/schemas.py:83-91`, whose
   `validate_theme_name` method explicitly rejects empty/whitespace-only names, 
but the MCP
   tool bypasses this schema, so `ThemeDAO.create` persists a row with a blank 
`theme_name`
   that then appears in theme listings via `list_themes`
   (`superset/mcp_service/theme/tool/list_themes.py:76-147`) even though the 
canonical REST
   API would have returned a 400 ValidationError.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=8af22a525c9a4ab8bceb65471b5d5ec3&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=8af22a525c9a4ab8bceb65471b5d5ec3&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/theme/tool/create_theme.py
   **Line:** 118:124
   **Comment:**
        *Api Mismatch: The tool writes the submitted name directly to the 
database without enforcing the non-empty/whitespace validation used by the 
Theme REST API, so blank theme names can be persisted here even though the 
canonical API rejects them. Add the same name validation path before 
persistence and return a validation error for empty or whitespace-only names.
   
   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%2F41497&comment_hash=d2c23ac47ab087dcbfb5656348d582448986f2c7eb570ae258c691874c7813b8&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41497&comment_hash=d2c23ac47ab087dcbfb5656348d582448986f2c7eb570ae258c691874c7813b8&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: [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