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


##########
superset/mcp_service/theme/tool/create_theme.py:
##########
@@ -0,0 +1,157 @@
+# 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.mcp_service.utils.sanitization import sanitize_for_llm_context
+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))
+        )
+        # Wrap the user-controlled name like the list/get responses do, so
+        # the create path is not an unsanitized echo channel into LLM context.
+        safe_name = sanitize_for_llm_context(
+            theme.theme_name, field_path=("theme_name",)
+        )
+        return CreateThemeResponse(
+            success=True,
+            id=theme.id,
+            uuid=str(uuid) if (uuid := getattr(theme, "uuid", None)) else None,
+            theme_name=safe_name,
+            message=f"Theme '{safe_name}' created successfully",
+        )
+
+    except SQLAlchemyError as exc:
+        db.session.rollback()  # pylint: disable=consider-using-transaction
+        logger.exception("Failed to create theme")
+        await ctx.error("Failed to create theme: %s" % (str(exc),))
+        return CreateThemeResponse(
+            success=False,
+            error=f"Failed to create theme: {exc}",
+            error_type="CreateFailedError",

Review Comment:
   **Suggestion:** Database exception text is returned directly to the client, 
which can expose internal SQL/schema details and stack-level operational 
information. Return a generic user-facing message and keep raw exception 
details only in server logs. [security]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ MCP clients receive raw SQLAlchemy error details.
   - ⚠️ LLM agents can see schema and table names.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Observe that create_theme is exposed as an MCP tool
   (superset/mcp_service/theme/tool/create_theme.py:53-78), exported in
   superset/mcp_service/theme/tool/__init__.py:18-26, and listed to MCP clients 
in
   superset/mcp_service/app.py:149-152 under "Theme Management", so its 
responses are
   surfaced to FastMCP clients (see
   tests/unit_tests/mcp_service/theme/tool/test_create_theme.py:21-31 using
   Client.call_tool("create_theme", ...)).
   
   2. In superset/mcp_service/theme/tool/create_theme.py, note the 
SQLAlchemyError handler at
   lines 144-152: on any database failure during ThemeDAO.create or 
db.session.commit,
   db.session.rollback() is called (line 145), logger.exception logs the error 
(line 146),
   ctx.error emits "Failed to create theme: %s" % str(exc) (line 147), and
   CreateThemeResponse is returned with error=f"Failed to create theme: {exc}" 
and
   error_type="CreateFailedError" (lines 148-151).
   
   3. Reproduce by misconfiguring the Theme table or database connection so 
commit raises
   SQLAlchemyError (for example, missing table or revoked permissions), or by 
patching
   create_theme_module.db.session.commit to raise SQLAlchemyError in a test 
similar to
   test_create_theme_success_with_dict at
   tests/unit_tests/mcp_service/theme/tool/test_create_theme.py:6-16.
   
   4. Call client.call_tool("create_theme", {"request": {"theme_name": 
"Broken", "json_data":
   {...}}}) as in the existing tests (lines 21-31), and inspect 
result.content[0].text: the
   JSON-decoded CreateThemeResponse (parsed with json.loads in tests) will 
contain the full
   string representation of the SQLAlchemyError in the error field, exposing 
internal
   SQL/server details to MCP clients and any attached LLM.
   ```
   </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=cdf9110221c148ed8bee9fe73306c828&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=cdf9110221c148ed8bee9fe73306c828&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:** 147:151
   **Comment:**
        *Security: Database exception text is returned directly to the client, 
which can expose internal SQL/schema details and stack-level operational 
information. Return a generic user-facing message and keep raw exception 
details only in server logs.
   
   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=8ba666d2ed124e42de81c9e8d5fd8a31f063ce74de9ee1201408654e9402d593&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41497&comment_hash=8ba666d2ed124e42de81c9e8d5fd8a31f063ce74de9ee1201408654e9402d593&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