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


##########
superset/mcp_service/dashboard/tool/manage_dashboard_markdown.py:
##########
@@ -0,0 +1,473 @@
+# 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.
+
+"""
+MCP tool: manage_dashboard_markdown
+
+Adds, updates, and removes markdown/header/divider layout components on a
+dashboard by translating high-level operations into ``position_json`` tree
+edits. Analogous to ``manage_native_filters``, which does the same for the
+flat native-filter list in ``json_metadata`` — this tool exists so callers
+don't have to hand-build the full raw layout tree just to add a text tile
+or section header (see ``generate_dashboard``'s ``position_json`` docstring).
+"""
+
+import logging
+from collections import Counter
+from typing import Any, Dict
+
+from fastmcp import Context
+from sqlalchemy.exc import SQLAlchemyError
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import db, event_logger
+from superset.mcp_service.dashboard.constants import generate_id, 
GRID_COLUMN_COUNT
+from superset.mcp_service.dashboard.layout_placement import (
+    collect_available_tab_names,
+    ensure_layout_structure,
+    find_next_row_position,
+    find_parent_key,
+    find_tab_insert_target,
+    remove_component_and_prune,
+)
+from superset.mcp_service.dashboard.layout_validation import (
+    rebuild_parent_chains,
+    validate_dashboard_layout,
+)
+from superset.mcp_service.dashboard.schemas import (
+    DashboardComponentSummary,
+    DashboardComponentUpdateSpec,
+    HeaderComponentSpec,
+    ManageDashboardMarkdownRequest,
+    ManageDashboardMarkdownResponse,
+    MarkdownComponentSpec,
+    NewDashboardComponentSpec,
+)
+from superset.mcp_service.dashboard.tool.governance_utils import (
+    dashboard_url,
+    find_and_authorize_dashboard,
+)
+from superset.utils import json
+
+logger = logging.getLogger(__name__)
+
+# Maps the tool-facing discriminator to the position_json component type.
+_LAYOUT_TYPE_BY_COMPONENT_TYPE: dict[str, str] = {
+    "markdown": "MARKDOWN",
+    "header": "HEADER",
+    "divider": "DIVIDER",
+}
+_COMPONENT_TYPE_BY_LAYOUT_TYPE = {
+    v: k for k, v in _LAYOUT_TYPE_BY_COMPONENT_TYPE.items()
+}
+
+# HEADER and DIVIDER are full-width bands placed directly on GRID/TAB — ROW
+# does not accept them as children (see layout_validation._PARENT_MAX_DEPTH).
+# MARKDOWN composes with charts, so it is wrapped in its own new ROW instead.
+_ROW_WRAPPED_LAYOUT_TYPES = frozenset({"MARKDOWN"})
+
+
+class _ComponentOperationError(Exception):
+    """Raised internally when a component operation fails validation."""
+
+
+def _build_component_meta(spec: NewDashboardComponentSpec) -> Dict[str, Any]:
+    """Build the position_json ``meta`` object for a new component spec."""
+    if isinstance(spec, MarkdownComponentSpec):
+        return {"code": spec.code, "width": spec.width, "height": spec.height}
+    if isinstance(spec, HeaderComponentSpec):
+        return {
+            "text": spec.text,
+            "headerSize": spec.header_size,
+            "background": spec.background,
+        }
+    # DividerComponentSpec carries no content, only placement.
+    return {}
+
+
+def _resolve_target_container(layout: Dict[str, Any], target_tab: str | None) 
-> str:
+    """Return the GRID_ID or TAB component ID a new component should attach to.
+
+    Raises ``_ComponentOperationError`` when *target_tab* is specified but
+    does not match any tab, listing the available tabs (or noting there are
+    none) so the caller can retry unambiguously.
+    """
+    tab_target = find_tab_insert_target(layout, target_tab=target_tab)
+
+    if target_tab is not None and tab_target is None:
+        available = collect_available_tab_names(layout)
+        if available:
+            raise _ComponentOperationError(
+                f"Tab '{target_tab}' not found. Available tabs: {', 
'.join(available)}."
+            )
+        raise _ComponentOperationError(
+            "Dashboard has no tabs. Remove target_tab to add to the "
+            "default grid layout."
+        )
+
+    return tab_target if tab_target else "GRID_ID"
+
+
+def _add_component_to_layout(
+    layout: Dict[str, Any], spec: NewDashboardComponentSpec
+) -> str:
+    """Insert a new markdown/header/divider component into *layout*.
+
+    Returns the new component's ID. New nodes are linked with empty
+    ``parents`` — the caller rebuilds the whole tree's parent chains via
+    ``rebuild_parent_chains`` after all operations are applied.
+    """
+    parent_id = _resolve_target_container(layout, spec.target_tab)
+
+    layout_type = _LAYOUT_TYPE_BY_COMPONENT_TYPE[spec.component_type]
+    component_id = generate_id(layout_type)
+    while component_id in layout:
+        component_id = generate_id(layout_type)
+    layout[component_id] = {
+        "id": component_id,
+        "type": layout_type,
+        "children": [],
+        "meta": _build_component_meta(spec),
+        "parents": [],
+    }
+
+    if layout_type in _ROW_WRAPPED_LAYOUT_TYPES:
+        row_key = find_next_row_position(layout)
+        layout[row_key] = {
+            "id": row_key,
+            "type": "ROW",
+            "children": [component_id],
+            "meta": {"background": "BACKGROUND_TRANSPARENT"},
+            "parents": [],
+        }
+        ensure_layout_structure(layout, row_key, parent_id)
+    else:
+        ensure_layout_structure(layout, component_id, parent_id)
+
+    return component_id
+
+
+def _apply_component_update(  # noqa: C901
+    spec: DashboardComponentUpdateSpec, node: Dict[str, Any], component_type: 
str
+) -> None:
+    """Merge *spec* into *node*'s meta in place.
+
+    Raises ``_ComponentOperationError`` when a field that only applies to a
+    different component type is set.
+    """
+    markdown_fields = ("code", "width", "height")
+    header_fields = ("text", "header_size", "background")
+
+    if component_type != "markdown":
+        if set_fields := [f for f in markdown_fields if getattr(spec, f) is 
not None]:
+            raise _ComponentOperationError(
+                f"Component '{spec.id}' has type '{component_type}'; fields "
+                f"{set_fields} only apply to markdown components."
+            )
+    if component_type != "header":
+        if set_fields := [f for f in header_fields if getattr(spec, f) is not 
None]:
+            raise _ComponentOperationError(
+                f"Component '{spec.id}' has type '{component_type}'; fields "
+                f"{set_fields} only apply to header components."
+            )
+
+    meta = dict(node.get("meta") or {})
+    if component_type == "markdown":
+        if spec.code is not None:
+            meta["code"] = spec.code
+        if spec.width is not None:
+            meta["width"] = spec.width
+        if spec.height is not None:
+            meta["height"] = spec.height
+    elif component_type == "header":
+        if spec.text is not None:
+            meta["text"] = spec.text
+        if spec.header_size is not None:
+            meta["headerSize"] = spec.header_size
+        if spec.background is not None:
+            meta["background"] = spec.background
+    node["meta"] = meta
+
+
+def _validate_markdown_width(
+    layout: Dict[str, Any], component_id: str, width: int
+) -> None:
+    """Reject a resize that exceeds the space left by the row's siblings."""
+    parent_id = find_parent_key(layout, component_id)
+    parent = layout.get(parent_id) if parent_id is not None else None
+    if not parent or parent.get("type") != "ROW":
+        return
+    sibling_width = sum(
+        (layout[child_id].get("meta") or {}).get("width", 0)
+        for child_id in parent.get("children", [])
+        if child_id != component_id
+    )
+    if width > (available_width := max(0, GRID_COLUMN_COUNT - sibling_width)):
+        raise _ComponentOperationError(
+            f"Cannot resize component '{component_id}' to width {width}: "
+            f"available width in row '{parent_id}' is {available_width} 
columns."
+        )
+
+
+def _apply_updates(
+    layout: Dict[str, Any],
+    updates: list[DashboardComponentUpdateSpec],
+    existing_components: Dict[str, Dict[str, Any]],
+) -> list[str]:
+    """Apply every update spec in order; returns the updated component IDs."""
+    update_ids = [spec.id for spec in updates]
+    if duplicates := sorted(
+        cid for cid, count in Counter(update_ids).items() if count > 1
+    ):

Review Comment:
   fixed in 0cd982cce87bf5b37b3913fca3dc95231fe6b41f



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