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


##########
superset/mcp_service/dashboard/schemas.py:
##########
@@ -1528,3 +1512,217 @@ def dashboard_layout_serializer(dashboard: "Dashboard") 
-> DashboardLayout:
             has_layout=bool(position_json_str),
         )
     )
+
+
+# ---------------------------------------------------------------------------
+# manage_native_filters schemas
+# ---------------------------------------------------------------------------
+
+
+class BaseNewFilterSpec(BaseModel):
+    """Common fields shared by all new native filter specs."""
+
+    name: str = Field(..., min_length=1, description="Filter display name")
+    description: str = Field("", description="Optional filter description")
+    scope_chart_ids: List[int] | None = Field(
+        None,
+        description=(
+            "Chart IDs this filter should apply to. When omitted the filter "
+            "applies to all charts on the dashboard. All IDs must belong to "
+            "charts that are on the dashboard."
+        ),
+    )
+
+
+class FilterSelectSpec(BaseNewFilterSpec):
+    """Spec for a new dropdown (filter_select) native filter."""
+
+    filter_type: Literal["filter_select"] = Field(
+        ..., description="Discriminator - must be 'filter_select'"
+    )
+    dataset_id: int = Field(..., description="ID of the dataset to filter on")
+    column: str = Field(
+        ..., min_length=1, description="Name of the dataset column to filter 
on"
+    )
+    multi_select: bool = Field(
+        True, description="Allow selecting multiple values (default True)"
+    )
+    default_to_first_item: bool = Field(
+        False, description="Default the filter to the first item in the list"
+    )
+    enable_empty_filter: bool = Field(
+        False, description="Require a value before the filter is applied"
+    )
+    sort_ascending: bool | None = Field(
+        None,
+        description=(
+            "Sort filter values ascending (True) or descending (False). "
+            "When omitted, values are not explicitly sorted."
+        ),
+    )
+    search_all_options: bool = Field(
+        False, description="Query the database on search rather than 
client-side"
+    )
+
+
+class FilterTimeSpec(BaseNewFilterSpec):
+    """Spec for a new time range (filter_time) native filter."""
+
+    filter_type: Literal["filter_time"] = Field(
+        ..., description="Discriminator - must be 'filter_time'"
+    )
+    default_time_range: str | None = Field(
+        None,
+        description=(
+            "Default time range value, e.g. 'Last week', 'Last month', "
+            "'2024-01-01 : 2024-12-31'. When omitted the filter has no 
default."
+        ),
+    )
+
+
+NewNativeFilterSpec = Annotated[
+    FilterSelectSpec | FilterTimeSpec,
+    Field(discriminator="filter_type"),
+]
+
+
+class NativeFilterUpdateSpec(BaseModel):
+    """Partial update for an existing native filter.
+
+    Only ``id`` is required; any other provided field is merged into the
+    existing filter configuration. Fields that only apply to one filter
+    type (e.g. ``multi_select`` for filter_select, ``default_time_range``
+    for filter_time) are rejected when used on the wrong filter type.
+    """
+
+    id: str = Field(..., min_length=1, description="ID of the filter to 
update")
+    name: str | None = Field(None, min_length=1, description="New display 
name")
+    description: str | None = Field(None, description="New description")
+    dataset_id: int | None = Field(
+        None, description="New target dataset ID (filter_select only)"
+    )
+    column: str | None = Field(
+        None, min_length=1, description="New target column name (filter_select 
only)"
+    )
+    multi_select: bool | None = Field(
+        None, description="Allow multiple values (filter_select only)"
+    )
+    default_to_first_item: bool | None = Field(
+        None, description="Default to first item (filter_select only)"
+    )
+    enable_empty_filter: bool | None = Field(
+        None, description="Require a value (filter_select only)"
+    )
+    sort_ascending: bool | None = Field(
+        None, description="Sort values ascending/descending (filter_select 
only)"
+    )
+    search_all_options: bool | None = Field(
+        None, description="Search all options in the database (filter_select 
only)"
+    )
+    default_time_range: str | None = Field(
+        None, description="Default time range (filter_time only)"
+    )
+    scope_chart_ids: List[int] | None = Field(
+        None,
+        description=(
+            "Chart IDs this filter should apply to. Replaces the current "
+            "scope. All IDs must belong to charts on the dashboard."
+        ),
+    )
+
+
+class ManageNativeFiltersRequest(BaseModel):
+    """Request schema for the manage_native_filters tool."""
+
+    dashboard_id: int = Field(..., description="ID of the dashboard to modify")
+    add: List[NewNativeFilterSpec] = Field(
+        default_factory=list,
+        description=(
+            "New filters to create. Supported types: filter_select "
+            "(dropdown) and filter_time (time range). Other filter types "
+            "(numerical range, time column, time grain) are not yet "
+            "supported by this tool."
+        ),
+    )
+    update: List[NativeFilterUpdateSpec] = Field(
+        default_factory=list,
+        description="Partial updates to existing filters, addressed by filter 
ID",
+    )
+    remove: List[str] = Field(
+        default_factory=list,
+        description="IDs of filters to delete from the dashboard",
+    )
+    reorder: List[str] | None = Field(
+        None,
+        description=(
+            "Complete ordered list of filter IDs defining the new filter "
+            "order. Must include every filter that remains on the dashboard "
+            "(after removals); newly added filters are appended "
+            "automatically and may be omitted."
+        ),
+    )

Review Comment:
   Declining: `manage_native_filters` is a write tool receiving a 
fully-structured Pydantic model (`ManageNativeFiltersRequest`), not a read tool 
with list-filter string params. The double-serialization issue referenced in 
the codebase applies to ModelListCore's `filters`/`select_columns` parameters 
where LLMs commonly pass comma-separated strings. For a write tool like this, 
the LLM constructs the entire request object as structured JSON; pre-validators 
for every list field would add complexity without a demonstrated failure mode.



##########
superset/mcp_service/dashboard/tool/manage_native_filters.py:
##########
@@ -0,0 +1,508 @@
+# 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_native_filters
+
+Adds, updates, removes, and reorders native filters on a dashboard by
+translating high-level operations into the ``deleted`` / ``modified`` /
+``reordered`` payload consumed by ``UpdateDashboardNativeFiltersCommand``.
+"""
+
+import copy
+import logging
+from typing import Any, cast
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.dashboard.constants import generate_id
+from superset.mcp_service.dashboard.schemas import (
+    FilterSelectSpec,
+    FilterTimeSpec,
+    ManageNativeFiltersRequest,
+    ManageNativeFiltersResponse,
+    NativeFilterSummary,
+    NativeFilterUpdateSpec,
+)
+from superset.mcp_service.utils import (
+    escape_llm_context_delimiters,
+    sanitize_for_llm_context,
+)
+from superset.mcp_service.utils.url_utils import get_superset_base_url
+from superset.utils import json
+
+logger = logging.getLogger(__name__)
+
+# Control values that map to filter_select controlValues keys.
+_SELECT_CONTROL_FIELDS: dict[str, str] = {
+    "multi_select": "multiSelect",
+    "default_to_first_item": "defaultToFirstItem",
+    "enable_empty_filter": "enableEmptyFilter",
+    "sort_ascending": "sortAscending",
+    "search_all_options": "searchAllOptions",
+}
+
+
+class _FilterValidationError(Exception):
+    """Raised internally when a filter operation fails validation."""
+
+
+def _empty_data_mask() -> dict[str, Any]:
+    """Return the default data mask for a filter with no applied value."""
+    return {"filterState": {"value": None}, "extraFormData": {}}
+
+
+def _time_data_mask(default_time_range: str | None) -> dict[str, Any]:
+    """Build the default data mask for a time filter.
+
+    When ``default_time_range`` is empty the filter starts unset (the empty
+    mask); otherwise the range is applied as both the filter state value and
+    the ``time_range`` extra form data.
+    """
+    if not default_time_range:
+        return _empty_data_mask()
+    return {
+        "filterState": {"value": default_time_range},
+        "extraFormData": {"time_range": default_time_range},
+    }
+
+
+def _validate_dataset_column(dataset_id: int, column: str) -> None:
+    """Validate that the dataset exists and contains the given column."""
+    from superset.daos.dataset import DatasetDAO
+
+    dataset = DatasetDAO.find_by_id(dataset_id)
+    if not dataset:
+        raise _FilterValidationError(
+            f"Dataset with ID {dataset_id} not found."
+            " Use list_datasets to get valid dataset IDs."
+        )
+    column_names = [c.column_name for c in dataset.columns]
+    if column not in column_names:
+        raise _FilterValidationError(
+            f"Column '{column}' not found in dataset {dataset_id}. "
+            f"Available columns: {', '.join(sorted(column_names))}."
+        )

Review Comment:
   Partially valid — `_validate_dataset_column` does expose column names for 
any dataset reachable by ID without an explicit dataset-access check. Whether 
this is in scope depends on how Superset's role matrix treats Dashboard-write 
users: if they're expected to be able to see dataset columns for dashboards 
they can edit, this is intended behavior; if not, a `raise_for_access` call on 
the dataset should precede the column lookup. Escalating to @aminghadersohi for 
a decision on whether dataset access should be checked here before returning 
column names in error messages.



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