codeant-ai-for-open-source[bot] commented on code in PR #40961:
URL: https://github.com/apache/superset/pull/40961#discussion_r3493300697
##########
superset/mcp_service/dashboard/schemas.py:
##########
@@ -1528,3 +1543,225 @@ def dashboard_layout_serializer(dashboard: "Dashboard")
-> DashboardLayout:
has_layout=bool(position_json_str),
)
)
+
+
+# Per-dataset caps keep responses small enough for LLM context: wide
+# datasets can have hundreds of columns, which would dwarf the fields an
+# agent actually needs to configure native filters.
+MAX_DASHBOARD_DATASET_COLUMNS = 100
+MAX_DASHBOARD_DATASET_METRICS = 50
Review Comment:
**Suggestion:** Add explicit type annotations to these new module-level
constants (for example as integer finals) to comply with the required typing
rule for relevant variables. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
These are new module-level constants that can be explicitly type-annotated,
and the rule requires type hints for relevant variables in new or modified
Python code. The existing code omits annotations such as `Final[int]` or `int`.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ae111375b51a47fa80ef709ff3d26d49&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ae111375b51a47fa80ef709ff3d26d49&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/dashboard/schemas.py
**Line:** 1548:1552
**Comment:**
*Custom Rule: Add explicit type annotations to these new module-level
constants (for example as integer finals) to comply with the required typing
rule for relevant variables.
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%2F40961&comment_hash=cc5942f6c78761053fe457ab410733d38d44c97214465b01eeae655a2d530d57&reaction=like'>👍</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40961&comment_hash=cc5942f6c78761053fe457ab410733d38d44c97214465b01eeae655a2d530d57&reaction=dislike'>👎</a>
##########
superset/mcp_service/dashboard/schemas.py:
##########
@@ -1528,3 +1543,225 @@ def dashboard_layout_serializer(dashboard: "Dashboard")
-> DashboardLayout:
has_layout=bool(position_json_str),
)
)
+
+
+# Per-dataset caps keep responses small enough for LLM context: wide
+# datasets can have hundreds of columns, which would dwarf the fields an
+# agent actually needs to configure native filters.
+MAX_DASHBOARD_DATASET_COLUMNS = 100
+MAX_DASHBOARD_DATASET_METRICS = 50
+
+
+class DashboardDatasetColumn(BaseModel):
+ """Lean column representation for dashboard dataset context."""
+
+ column_name: str = Field(..., description="Column name")
+ verbose_name: str | None = Field(None, description="Verbose (display)
name")
+ type: str | None = Field(None, description="Column data type")
+ is_dttm: bool | None = Field(None, description="Is datetime column")
+
+
+class DashboardDatasetMetric(BaseModel):
+ """Lean metric representation for dashboard dataset context."""
+
+ metric_name: str = Field(..., description="Saved metric name")
+ verbose_name: str | None = Field(None, description="Verbose (display)
name")
+ expression: str | None = Field(None, description="SQL expression")
+
+
+class DashboardDatasetDatabaseInfo(BaseModel):
+ """Database connection summary for a dashboard dataset."""
+
+ id: int | None = Field(None, description="Database ID")
+ name: str | None = Field(None, description="Database name")
+ backend: str | None = Field(None, description="Database backend (engine)")
+
+
+class DashboardDatasetSummary(BaseModel):
+ """A dataset used by a dashboard's charts, with columns and metrics."""
+
+ id: int | None = Field(None, description="Dataset ID")
+ uuid: str | None = Field(None, description="Dataset UUID")
+ table_name: str | None = Field(None, description="Table name")
+ schema_name: str | None = Field(None, description="Schema name")
+ database: DashboardDatasetDatabaseInfo | None = Field(
+ None, description="Database the dataset belongs to"
+ )
+ chart_count: int = Field(
+ 0, description="Number of charts on the dashboard using this dataset"
+ )
+ columns: List[DashboardDatasetColumn] = Field(
+ default_factory=list, description="Dataset columns"
+ )
+ metrics: List[DashboardDatasetMetric] = Field(
+ default_factory=list, description="Dataset metrics"
+ )
+ total_column_count: int = Field(
+ 0, description="Total number of columns on the dataset"
+ )
+ total_metric_count: int = Field(
+ 0, description="Total number of metrics on the dataset"
+ )
+ columns_truncated: bool = Field(
+ False,
+ description=(
+ "True when the columns list was truncated to keep the response
small"
+ ),
+ )
+ metrics_truncated: bool = Field(
+ False,
+ description=(
+ "True when the metrics list was truncated to keep the response
small"
+ ),
+ )
+
+ @model_serializer(mode="wrap")
+ def _rename_schema_field(self, serializer: Any, info: Any) -> Dict[str,
Any]:
+ """Serialize 'schema_name' as 'schema' to match API conventions."""
+ data = serializer(self)
+ if "schema_name" in data:
+ data["schema"] = data.pop("schema_name")
+ return data
+
+
+class DashboardDatasets(BaseModel):
+ """Response schema for get_dashboard_datasets."""
+
+ id: int | None = Field(None, description="Dashboard ID")
+ dashboard_title: str | None = Field(None, description="Dashboard title")
+ uuid: str | None = Field(None, description="Dashboard UUID")
+ dataset_count: int = Field(
+ 0, description="Number of accessible datasets used by the dashboard"
+ )
+ inaccessible_dataset_count: int = Field(
+ 0,
+ description=(
+ "Number of datasets used by the dashboard that the current user "
+ "cannot access (excluded from 'datasets')"
+ ),
+ )
+ datasets: List[DashboardDatasetSummary] = Field(
+ default_factory=list,
+ description="Datasets used by the dashboard's charts",
+ )
+
+
+def _serialize_dashboard_dataset(
+ datasource: Any, chart_count: int
+) -> DashboardDatasetSummary:
+ """Serialize a datasource to a lean, LLM-safe dataset summary."""
+ all_columns = list(getattr(datasource, "columns", None) or [])
+ all_metrics = list(getattr(datasource, "metrics", None) or [])
+
+ columns = [
+ DashboardDatasetColumn(
+ column_name=escape_llm_context_delimiters(
+ getattr(column, "column_name", None) or ""
+ ),
+ verbose_name=sanitize_for_llm_context(
+ getattr(column, "verbose_name", None),
+ field_path=("columns", str(index), "verbose_name"),
+ ),
+ type=getattr(column, "type", None),
+ is_dttm=getattr(column, "is_dttm", None),
+ )
+ for index, column in
enumerate(all_columns[:MAX_DASHBOARD_DATASET_COLUMNS])
+ ]
+ metrics = [
+ DashboardDatasetMetric(
+ metric_name=escape_llm_context_delimiters(
+ getattr(metric, "metric_name", None) or ""
+ ),
+ verbose_name=sanitize_for_llm_context(
+ getattr(metric, "verbose_name", None),
+ field_path=("metrics", str(index), "verbose_name"),
+ ),
+ expression=sanitize_for_llm_context(
+ getattr(metric, "expression", None),
+ field_path=("metrics", str(index), "expression"),
+ ),
+ )
+ for index, metric in
enumerate(all_metrics[:MAX_DASHBOARD_DATASET_METRICS])
+ ]
+
+ database = getattr(datasource, "database", None)
+ database_info = (
+ DashboardDatasetDatabaseInfo(
+ id=getattr(database, "id", None),
+ name=escape_llm_context_delimiters(
+ getattr(database, "database_name", None)
+ ),
+ backend=getattr(database, "backend", None),
+ )
+ if database is not None
+ else None
+ )
+
+ dataset_uuid = getattr(datasource, "uuid", None)
+ return DashboardDatasetSummary(
+ id=getattr(datasource, "id", None),
+ uuid=str(dataset_uuid) if dataset_uuid else None,
+ table_name=escape_llm_context_delimiters(
+ getattr(datasource, "table_name", None)
+ ),
+ schema_name=escape_llm_context_delimiters(getattr(datasource,
"schema", None)),
+ database=database_info,
+ chart_count=chart_count,
+ columns=columns,
+ metrics=metrics,
+ total_column_count=len(all_columns),
+ total_metric_count=len(all_metrics),
+ columns_truncated=len(all_columns) > MAX_DASHBOARD_DATASET_COLUMNS,
+ metrics_truncated=len(all_metrics) > MAX_DASHBOARD_DATASET_METRICS,
+ )
+
+
+def dashboard_datasets_serializer(dashboard: "Dashboard") -> DashboardDatasets:
+ """Serialize a Dashboard model to the datasets used by its charts.
+
+ Groups the dashboard's charts by datasource (mirroring
+ ``Dashboard.datasets_trimmed_for_slices``) but keeps the full column and
+ metric lists (capped) since native-filter configuration regularly needs
+ columns that no chart references. Datasets the current user cannot
+ access are excluded and only counted.
+ """
+ from superset.mcp_service.auth import has_dataset_access
+
+ slices_by_datasource: Dict[int, List[Any]] = {}
+ for slc in getattr(dashboard, "slices", None) or []:
+ datasource_id = getattr(slc, "datasource_id", None)
+ if datasource_id is None:
+ continue
+ slices_by_datasource.setdefault(datasource_id, []).append(slc)
+
+ datasets: List[DashboardDatasetSummary] = []
+ inaccessible_count = 0
Review Comment:
**Suggestion:** Add an explicit type hint to this newly introduced counter
variable to satisfy the type-hint requirement for relevant variables.
[custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
This is a newly introduced local variable with a clear, annotatable type.
The custom typing rule applies to relevant variables, so the missing annotation
is a real violation.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=37a294767a5c49f0a4ddf60337e71091&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=37a294767a5c49f0a4ddf60337e71091&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/dashboard/schemas.py
**Line:** 1738:1738
**Comment:**
*Custom Rule: Add an explicit type hint to this newly introduced
counter variable to satisfy the type-hint requirement for relevant variables.
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%2F40961&comment_hash=a25e2ec376200fcf8ba1089f721edff099d40a8efc910cd3a972614b91d54769&reaction=like'>👍</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40961&comment_hash=a25e2ec376200fcf8ba1089f721edff099d40a8efc910cd3a972614b91d54769&reaction=dislike'>👎</a>
##########
superset/mcp_service/dashboard/tool/get_dashboard_datasets.py:
##########
@@ -0,0 +1,156 @@
+# 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.
+
+"""
+Get dashboard datasets FastMCP tool
+
+Returns the datasets used by a dashboard's charts, including columns and
+metrics. This is the prerequisite context an agent needs before configuring
+native filters on a dashboard (e.g. picking filter target columns).
+"""
+
+import logging
+from datetime import datetime, timezone
+
+from fastmcp import Context
+from sqlalchemy.orm import subqueryload
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.dashboard.schemas import (
+ dashboard_datasets_serializer,
+ DashboardDatasets,
+ DashboardError,
+ GetDashboardDatasetsRequest,
+)
+from superset.mcp_service.mcp_core import ModelGetInfoCore
+from superset.mcp_service.privacy import (
+ DATA_MODEL_METADATA_ERROR_TYPE,
+ requires_data_model_metadata_access,
+ user_can_view_data_model_metadata,
+)
+
+logger = logging.getLogger(__name__)
Review Comment:
**Suggestion:** Add an explicit type annotation for the module-level logger
variable to satisfy the required type-hinting rule for relevant variables.
[custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The custom rule requires type hints on relevant variables that can be
annotated. The module-level `logger` is a relevant variable and is currently
unannotated, so this is a real violation.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d40cf7aa9da447969f1276bc47b8f0e1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=d40cf7aa9da447969f1276bc47b8f0e1&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/dashboard/tool/get_dashboard_datasets.py
**Line:** 47:47
**Comment:**
*Custom Rule: Add an explicit type annotation for the module-level
logger variable to satisfy the required type-hinting rule for relevant
variables.
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%2F40961&comment_hash=cdb65e7b3271017d6c12bb0d76358190e8e8483c2a0a15cf281092b24ca0061d&reaction=like'>👍</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40961&comment_hash=cdb65e7b3271017d6c12bb0d76358190e8e8483c2a0a15cf281092b24ca0061d&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_datasets.py:
##########
@@ -0,0 +1,387 @@
+# 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 MCP get_dashboard_datasets tool."""
+
+from unittest.mock import Mock, patch
+
+import pytest
+from fastmcp import Client
+
+from superset.mcp_service.app import mcp
+from superset.mcp_service.utils.sanitization import (
+ LLM_CONTEXT_CLOSE_DELIMITER,
+ LLM_CONTEXT_OPEN_DELIMITER,
+)
+from superset.utils import json
+
+
+def _wrapped(value: str) -> str:
+ return
f"{LLM_CONTEXT_OPEN_DELIMITER}\n{value}\n{LLM_CONTEXT_CLOSE_DELIMITER}"
+
+
+def _build_column_mock(
+ name: str,
+ *,
+ verbose_name: str | None = None,
+ type_: str | None = "VARCHAR",
+ is_dttm: bool = False,
+) -> Mock:
+ column = Mock()
+ column.column_name = name
+ column.verbose_name = verbose_name
+ column.type = type_
+ column.is_dttm = is_dttm
+ return column
+
+
+def _build_metric_mock(
+ name: str,
+ *,
+ verbose_name: str | None = None,
+ expression: str | None = None,
+) -> Mock:
+ metric = Mock()
+ metric.metric_name = name
+ metric.verbose_name = verbose_name
+ metric.expression = expression
+ return metric
+
+
+def _build_database_mock(
+ *, database_id: int = 7, name: str = "examples", backend: str =
"postgresql"
+) -> Mock:
+ database = Mock()
+ database.id = database_id
+ database.database_name = name
+ database.backend = backend
+ return database
+
+
+def _build_datasource_mock(
+ *,
+ dataset_id: int,
+ uuid: str | None = None,
+ table_name: str = "my_table",
+ schema: str | None = "public",
+ database: Mock | None = None,
+ columns: list[Mock] | None = None,
+ metrics: list[Mock] | None = None,
+) -> Mock:
+ datasource = Mock()
+ datasource.id = dataset_id
+ datasource.uuid = uuid
+ datasource.table_name = table_name
+ datasource.schema = schema
+ datasource.database = database
+ datasource.columns = columns or []
+ datasource.metrics = metrics or []
+ return datasource
+
+
+def _build_slice_mock(datasource: Mock) -> Mock:
+ slc = Mock()
+ slc.datasource_id = datasource.id
+ slc.datasource = datasource
+ return slc
+
+
+def _build_dashboard_mock(
+ *,
+ dashboard_id: int = 1,
+ title: str = "Test Dashboard",
+ uuid: str | None = "dashboard-uuid-1",
+ slices: list[Mock] | None = None,
+) -> Mock:
+ dashboard = Mock()
+ dashboard.id = dashboard_id
+ dashboard.dashboard_title = title
+ dashboard.uuid = uuid
+ dashboard.slices = slices or []
+ return dashboard
+
+
[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](autouse=True)
+def mock_dataset_access():
+ with patch(
+ "superset.mcp_service.auth.has_dataset_access", return_value=True
+ ) as mock_access:
+ yield mock_access
Review Comment:
**Suggestion:** Add an explicit return type annotation to this fixture
function. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
This fixture function is missing a return type annotation, which is exactly
what the type-hint rule flags.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=564276f169ae4dca9fef2073ff88ecc9&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=564276f169ae4dca9fef2073ff88ecc9&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:**
tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_datasets.py
**Line:** 133:138
**Comment:**
*Custom Rule: Add an explicit return type annotation to this fixture
function.
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%2F40961&comment_hash=9145c73870d68d5a22a979d4d240da9c54a665424b7b34fc4dfaaeec7e165b78&reaction=like'>👍</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40961&comment_hash=9145c73870d68d5a22a979d4d240da9c54a665424b7b34fc4dfaaeec7e165b78&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]