This is an automated email from the ASF dual-hosted git repository.
rebenitez1802 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 7a9fa30a614 feat(mcp): add bounded governed source discovery (#46120)
7a9fa30a614 is described below
commit 7a9fa30a6144c0d09874d2e7e63a69d0dee1d9be
Author: Rafael Benitez <[email protected]>
AuthorDate: Fri Nov 13 09:43:45 2026 -0300
feat(mcp): add bounded governed source discovery (#46120)
---
docs/developer_docs/extensions/mcp.md | 59 +++
superset/daos/semantic_layer.py | 67 +++-
superset/mcp_service/app.py | 2 +
superset/mcp_service/dashboard_scope.py | 1 +
superset/mcp_service/dataset/dataset_utils.py | 5 +-
superset/mcp_service/dataset/discovery.py | 144 ++++++++
superset/mcp_service/dataset/schemas.py | 102 +++++
.../mcp_service/dataset/tool/get_dataset_info.py | 33 +-
superset/mcp_service/semantic_layer/schemas.py | 39 +-
.../mcp_service/semantic_layer/tool/__init__.py | 3 +
.../semantic_layer/tool/list_semantic_views.py | 106 ++++++
superset/mcp_service/worker.py | 1 +
.../dataset/tool/test_dataset_discovery.py | 410 +++++++++++++++++++++
.../mcp_service/native_tool_inventory.json | 64 ++--
.../tool/test_list_semantic_views.py | 295 +++++++++++++++
.../unit_tests/mcp_service/test_dashboard_scope.py | 4 +-
.../mcp_service/test_mcp_tool_registration.py | 2 +
.../unit_tests/mcp_service/test_tool_inventory.py | 4 +-
.../mcp_service/test_worker_metadata_pool.py | 12 +-
19 files changed, 1298 insertions(+), 55 deletions(-)
diff --git a/docs/developer_docs/extensions/mcp.md
b/docs/developer_docs/extensions/mcp.md
index 19207704fcf..fa78d87da79 100644
--- a/docs/developer_docs/extensions/mcp.md
+++ b/docs/developer_docs/extensions/mcp.md
@@ -37,6 +37,65 @@ immediate saves; dataset-only rebinds return a validation
error instead of
clearing saved query roles. Sending the existing dataset ID does not require
a replacement config.
+## Progressive source discovery
+
+Discover source summaries before requesting selected members. All operations
+use the acting user's current permissions and metadata privacy controls;
+discovery does not grant later query access.
+
+### SQL datasets
+
+Use `list_datasets` to select a source, then opt into bounded metadata with
+`get_dataset_info`:
+
+```json
+{"request":{"identifier":13,"discovery":{"section":"summary"}}}
+```
+
+The response contains `source:
{"type":"table","id":13,"uuid":"<dataset-uuid>"}`, `section`, and a
+`summary` with UUID, name, description, `is_virtual`, and `main_dttm_col`. It
does
+not load member relationships or return the dataset's SQL definition.
+
+```json
+{"request":{"identifier":13,"discovery":{"section":"columns","search":"country","page":1,"page_size":25}}}
+```
+
+Choose `columns` or `metrics`. Pages contain `items`, `page`, `page_size`,
+`has_more`, and `next_page`. Repeat the same source, section, search, and page
+size with `next_page`; null means the end. Default page size is 25, maximum
100.
+Search is a literal, case-insensitive substring of member name, verbose name,
+or description, limited to 200 characters. Saved metric expressions and row
+values are never included.
+
+The summary section defaults when omitted and ignores search/pagination.
+Member pages carry both the dataset ID and UUID in `source`.
+`discovery` cannot be combined with explicit `select_columns` (including its
+`columns` alias) or `column_fields`. Omitting `discovery` retains the existing
+response and field-selection behavior. Dataset routing constraints still apply.
+
+### Semantic views
+
+```json
+{"request":{"search":"revenue","page":1,"page_size":25}}
+```
+
+Pass this to `list_semantic_views`. It returns `sources`, each containing
+`source: {"type":"semantic_view","id":42}`, UUID, stored name, and provider
+type, plus the same continuation fields. Search matches stored
name/description;
+page and search limits match dataset member discovery. Access is filtered
before
+SQL pagination. No total count, encrypted configuration, members, selection
+versions, provider calls, or readiness claims are included.
+
+Semantic layers must be enabled. Dataset-read permission and metadata privacy
+checks apply independently of view/layer datasource grants. This tool is
+unavailable when MCP SQL-dataset routing is configured: semantic views are not
+registered SQL datasets. A source summary does not imply that its provider is
+configured or that a particular consumer supports querying it. Fetch selected
+member metadata only when needed through the appropriate metadata tools.
+
+Pages reflect live metadata and grants, not snapshots. Changes between requests
+can move page boundaries; every request checks current access again.
+
## What is MCP?
MCP enables extensions to extend Superset's AI capabilities in two ways:
diff --git a/superset/daos/semantic_layer.py b/superset/daos/semantic_layer.py
index 1cb5da42d6a..9ed1ef8fe2c 100644
--- a/superset/daos/semantic_layer.py
+++ b/superset/daos/semantic_layer.py
@@ -21,7 +21,9 @@ from __future__ import annotations
from typing import Any
+from sqlalchemy import func, or_
from sqlalchemy.exc import StatementError
+from sqlalchemy.orm import Query
from superset_core.semantic_layers.daos import (
AbstractSemanticLayerDAO,
AbstractSemanticViewDAO,
@@ -203,6 +205,50 @@ class SemanticViewDAO(BaseDAO[SemanticView],
AbstractSemanticViewDAO):
for c in candidates
)
+ @staticmethod
+ def apply_access_filter(query: Query) -> Query:
+ """Filter a view/layer join without adding ORM loading options.
+
+ Callers must join SemanticLayer when access is restricted. This same
+ predicate governs ORM discovery and the scalar source index.
+ """
+ if security_manager.can_access_all_datasources():
+ return query
+ perms = security_manager.user_view_menu_names("datasource_access")
+ return query.filter(
+ or_(SemanticView.perm.in_(perms), SemanticLayer.perm.in_(perms))
+ )
+
+ @classmethod
+ def find_accessible_summaries(
+ cls, *, search: str | None, offset: int, limit: int
+ ) -> list[Any]:
+ """Read only stored view identity; never decrypt provider
configuration."""
+ query = db.session.query(
+ SemanticView.id,
+ SemanticView.uuid,
+ SemanticView.name,
+ SemanticLayer.type.label("provider"),
+ ).join(SemanticLayer, SemanticLayer.uuid ==
SemanticView.semantic_layer_uuid)
+ query = cls.apply_access_filter(query)
+ if search:
+ query = query.filter(
+ or_(
+ func.lower(SemanticView.name).contains(
+ search.lower(), autoescape=True
+ ),
+ func.lower(SemanticView.description).contains(
+ search.lower(), autoescape=True
+ ),
+ )
+ )
+ return (
+ query.order_by(func.lower(SemanticView.name), SemanticView.id)
+ .offset(offset)
+ .limit(limit)
+ .all()
+ )
+
@classmethod
def find_accessible(cls) -> list[SemanticView]:
"""Return all views the current user can access, filtered at SQL level.
@@ -214,28 +260,17 @@ class SemanticViewDAO(BaseDAO[SemanticView],
AbstractSemanticViewDAO):
``view.raise_for_access()`` per row, which reads
``view.semantic_layer.perm``
and would otherwise trigger a lazy-load query per view (N+1).
"""
- from sqlalchemy import or_
from sqlalchemy.orm import contains_eager, joinedload
query = db.session.query(SemanticView)
if not security_manager.can_access_all_datasources():
- perms = security_manager.user_view_menu_names("datasource_access")
- query = (
- query.join(
- SemanticLayer,
- SemanticLayer.uuid == SemanticView.semantic_layer_uuid,
- )
- .options(contains_eager(SemanticView.semantic_layer))
- .filter(
- or_(
- SemanticView.perm.in_(perms),
- SemanticLayer.perm.in_(perms),
- )
- )
- )
+ query = query.join(
+ SemanticLayer,
+ SemanticLayer.uuid == SemanticView.semantic_layer_uuid,
+ ).options(contains_eager(SemanticView.semantic_layer))
else:
query = query.options(joinedload(SemanticView.semantic_layer))
- return query.all()
+ return cls.apply_access_filter(query).all()
@classmethod
def find_by_name(cls, name: str, layer_uuid: str) -> SemanticView | None:
diff --git a/superset/mcp_service/app.py b/superset/mcp_service/app.py
index 2fa860e0acf..7bd91a6edff 100644
--- a/superset/mcp_service/app.py
+++ b/superset/mcp_service/app.py
@@ -200,6 +200,7 @@ Dataset Management:
- query_dataset: Query a dataset using its semantic layer (saved metrics,
dimensions, filters) without needing a saved chart
Semantic Layer:
+- list_semantic_views: Search compact permitted semantic source summaries
without loading provider schemas
- list_metrics: Discover metrics across built-in datasets and external
semantic views (1-based pagination)
- get_table: Query a data source (built-in dataset or external semantic view)
by metric/dimension names
- get_compatible_dimensions: Get dimensions compatible with a given
metric/dimension selection
@@ -898,6 +899,7 @@ from superset.mcp_service.semantic_layer.tool import ( #
noqa: F401, E402
get_compatible_metrics,
get_table,
list_metrics,
+ list_semantic_views,
)
from superset.mcp_service.sql_lab.tool import ( # noqa: F401, E402
execute_sql,
diff --git a/superset/mcp_service/dashboard_scope.py
b/superset/mcp_service/dashboard_scope.py
index 2a7f5ee4275..07260898866 100644
--- a/superset/mcp_service/dashboard_scope.py
+++ b/superset/mcp_service/dashboard_scope.py
@@ -1314,6 +1314,7 @@ SCOPE_NEUTRAL_TOOLS = frozenset(
"list_rls_filters",
"list_roles",
"list_saved_queries",
+ "list_semantic_views",
"list_tags",
"list_tasks",
"list_themes",
diff --git a/superset/mcp_service/dataset/dataset_utils.py
b/superset/mcp_service/dataset/dataset_utils.py
index e2f9340b391..ecfcb367644 100644
--- a/superset/mcp_service/dataset/dataset_utils.py
+++ b/superset/mcp_service/dataset/dataset_utils.py
@@ -22,8 +22,9 @@ from typing import Any
from superset.mcp_service.utils import _is_uuid
SQL_DATASET_SOURCE_GUIDANCE: str = (
- "This tool supports SQL datasets only. For semantic views, discover
metrics "
- "with list_metrics and query with get_table."
+ "This tool supports SQL datasets only. For semantic views, discover
sources "
+ "with list_semantic_views, then selected-view metrics with list_metrics "
+ "and query with get_table."
)
diff --git a/superset/mcp_service/dataset/discovery.py
b/superset/mcp_service/dataset/discovery.py
new file mode 100644
index 00000000000..db0eca10663
--- /dev/null
+++ b/superset/mcp_service/dataset/discovery.py
@@ -0,0 +1,144 @@
+# 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.
+
+"""Progressive metadata queries that never materialize dataset
relationships."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from sqlalchemy import and_, func, or_
+
+from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn
+from superset.daos.dataset import DatasetDAO
+from superset.extensions import db
+from superset.mcp_service.dataset.schemas import (
+ DatasetColumnPage,
+ DatasetDiscoveryColumn,
+ DatasetDiscoveryMetric,
+ DatasetDiscoverySource,
+ DatasetDiscoverySummary,
+ DatasetError,
+ DatasetMetricPage,
+ DatasetSummaryResponse,
+ GetDatasetInfoRequest,
+)
+from superset.mcp_service.dataset_scope import get_dataset_scope
+
+
+def discover_dataset(
+ request: GetDatasetInfoRequest,
+) -> DatasetSummaryResponse | DatasetColumnPage | DatasetMetricPage |
DatasetError:
+ """Authorize the source, then fetch a scalar summary or bounded member
page.
+
+ Apply the normal DAO filter before projection/pagination. Each call
resolves
+ current grants; neither a prior page nor a cached discovery grants access.
+ """
+ discovery = request.discovery
+ if discovery is None:
+ raise ValueError("A discovery request is required")
+ identifier = str(request.identifier)
+ if identifier.isdecimal():
+ identity_filter = SqlaTable.id == int(identifier)
+ else:
+ try:
+ identity_filter = SqlaTable.uuid == UUID(identifier)
+ except ValueError:
+ return DatasetError.create("Dataset not found", "not_found")
+
+ query = db.session.query(
+ SqlaTable.id,
+ SqlaTable.uuid,
+ SqlaTable.table_name.label("name"),
+ SqlaTable.description,
+ and_(SqlaTable.sql.is_not(None), SqlaTable.sql !=
"").label("is_virtual"),
+ SqlaTable.main_dttm_col,
+ ).filter(identity_filter, SqlaTable.deleted_at.is_(None))
+ query = DatasetDAO._apply_base_filter(query)
+ if (scope := get_dataset_scope()) is not None:
+ query = query.filter(SqlaTable.uuid.in_(scope))
+ row = query.one_or_none()
+ if row is None:
+ return DatasetError.create("Dataset not found", "not_found")
+ source = DatasetDiscoverySource(id=row.id, uuid=row.uuid)
+ if discovery.section == "summary":
+ return DatasetSummaryResponse(
+ source=source,
+ summary=DatasetDiscoverySummary(
+ uuid=row.uuid,
+ name=row.name,
+ description=row.description,
+ is_virtual=row.is_virtual,
+ main_dttm_col=row.main_dttm_col,
+ ),
+ )
+
+ if discovery.section == "columns":
+ model = TableColumn
+ name = model.column_name
+ members = db.session.query(
+ model.column_name,
+ model.verbose_name,
+ model.description,
+ model.type,
+ func.coalesce(model.filterable, False).label("filterable"),
+ func.coalesce(model.groupby, False).label("groupby"),
+ func.coalesce(model.is_dttm, False).label("is_dttm"),
+ )
+ else:
+ model = SqlMetric
+ name = model.metric_name
+ members = db.session.query(
+ model.metric_name, model.verbose_name, model.description,
model.d3format
+ )
+ members = members.filter(model.table_id == row.id)
+ if discovery.search:
+ # Escape LIKE wildcards: search means a literal substring, not a
pattern.
+ search = discovery.search.lower()
+ members = members.filter(
+ or_(
+ func.lower(name).contains(search, autoescape=True),
+ func.lower(model.verbose_name).contains(search,
autoescape=True),
+ func.lower(model.description).contains(search,
autoescape=True),
+ )
+ )
+ rows = (
+ members.order_by(name, model.id)
+ .offset((discovery.page - 1) * discovery.page_size)
+ .limit(discovery.page_size + 1)
+ .all()
+ )
+ has_more = len(rows) > discovery.page_size
+ page_rows = rows[: discovery.page_size]
+ next_page = discovery.page + 1 if has_more else None
+ if discovery.section == "columns":
+ return DatasetColumnPage(
+ source=source,
+ items=[DatasetDiscoveryColumn(**item._mapping) for item in
page_rows],
+ page=discovery.page,
+ page_size=discovery.page_size,
+ has_more=has_more,
+ next_page=next_page,
+ )
+ return DatasetMetricPage(
+ source=source,
+ items=[DatasetDiscoveryMetric(**item._mapping) for item in page_rows],
+ page=discovery.page,
+ page_size=discovery.page_size,
+ has_more=has_more,
+ next_page=next_page,
+ )
diff --git a/superset/mcp_service/dataset/schemas.py
b/superset/mcp_service/dataset/schemas.py
index c6e7e8652af..d7539f6083a 100644
--- a/superset/mcp_service/dataset/schemas.py
+++ b/superset/mcp_service/dataset/schemas.py
@@ -399,6 +399,88 @@ DEFAULT_GET_DATASET_INFO_COLUMN_FIELDS: List[str] = [
]
+class DatasetDiscoveryRequest(BaseModel):
+ """Read a summary or one bounded page of a selected dataset's members."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ section: Literal["summary", "columns", "metrics"] = "summary"
+ search: str | None = Field(default=None, max_length=200)
+ page: int = Field(default=1, ge=1, strict=True)
+ page_size: int = Field(default=25, ge=1, le=100, strict=True)
+
+
+class DatasetDiscoverySource(BaseModel):
+ """Identity of a SQL dataset for internal and public consumers."""
+
+ type: Literal["table"] = "table"
+ id: int
+ uuid: UUID | None
+
+
+class DatasetDiscoverySummary(BaseModel):
+ """Dataset identity and description without SQL or member relationships."""
+
+ uuid: UUID | None
+ name: str
+ description: str | None
+ is_virtual: bool
+ main_dttm_col: str | None
+
+
+class DatasetSummaryResponse(BaseModel):
+ """Summary response for progressive dataset discovery."""
+
+ source: DatasetDiscoverySource
+ section: Literal["summary"] = "summary"
+ summary: DatasetDiscoverySummary
+
+
+class DatasetDiscoveryColumn(BaseModel):
+ """Safe column metadata; excludes expressions and row values."""
+
+ column_name: str
+ verbose_name: str | None
+ description: str | None
+ type: str | None
+ filterable: bool
+ groupby: bool
+ is_dttm: bool
+
+
+class DatasetDiscoveryMetric(BaseModel):
+ """Saved metric metadata without its SQL expression."""
+
+ metric_name: str
+ verbose_name: str | None
+ description: str | None
+ d3format: str | None
+
+
+class DatasetColumnPage(BaseModel):
+ """A bounded page; repeat the request with next_page to continue."""
+
+ source: DatasetDiscoverySource
+ section: Literal["columns"] = "columns"
+ items: list[DatasetDiscoveryColumn]
+ page: int
+ page_size: int
+ has_more: bool
+ next_page: int | None
+
+
+class DatasetMetricPage(BaseModel):
+ """A bounded page of saved metrics, not ad-hoc metric definitions."""
+
+ source: DatasetDiscoverySource
+ section: Literal["metrics"] = "metrics"
+ items: list[DatasetDiscoveryMetric]
+ page: int
+ page_size: int
+ has_more: bool
+ next_page: int | None
+
+
class GetDatasetInfoRequest(MetadataCacheControl):
"""Request schema for get_dataset_info with support for ID or UUID."""
@@ -444,6 +526,26 @@ class GetDatasetInfoRequest(MetadataCacheControl):
),
]
+ discovery: DatasetDiscoveryRequest | None = Field(
+ default=None,
+ description=(
+ "Opt into progressive metadata: summary (default), columns or
metrics. "
+ "Member pages default to 25, at most 100; use next_page to
continue. "
+ "Cannot be combined with select_columns or column_fields. "
+ "Omit discovery to retain the legacy response."
+ ),
+ )
+
+ @model_validator(mode="after")
+ def discovery_excludes_legacy_selection(self) -> GetDatasetInfoRequest:
+ """Defaults are compatible; explicitly supplied legacy selectors are
not."""
+ if self.discovery is not None and self.model_fields_set & {
+ "select_columns",
+ "column_fields",
+ }:
+ raise ValueError("discovery cannot be combined with legacy field
selectors")
+ return self
+
@field_validator("select_columns", mode="before")
@classmethod
def _parse_select_columns(cls, value: Any) -> Any:
diff --git a/superset/mcp_service/dataset/tool/get_dataset_info.py
b/superset/mcp_service/dataset/tool/get_dataset_info.py
index 9c4eb499cf8..26c53438a93 100644
--- a/superset/mcp_service/dataset/tool/get_dataset_info.py
+++ b/superset/mcp_service/dataset/tool/get_dataset_info.py
@@ -33,8 +33,11 @@ from superset_core.mcp.decorators import tool,
ToolAnnotations
from superset.extensions import event_logger
from superset.mcp_service.dataset.dataset_utils import
SQL_DATASET_SOURCE_GUIDANCE
from superset.mcp_service.dataset.schemas import (
+ DatasetColumnPage,
DatasetError,
DatasetInfo,
+ DatasetMetricPage,
+ DatasetSummaryResponse,
GetDatasetInfoRequest,
serialize_dataset_object,
)
@@ -61,12 +64,24 @@ logger = logging.getLogger(__name__)
@requires_data_model_metadata_access
async def get_dataset_info(
request: GetDatasetInfoRequest, ctx: Context
-) -> DatasetInfo | DatasetError:
+) -> (
+ DatasetInfo
+ | DatasetError
+ | DatasetSummaryResponse
+ | DatasetColumnPage
+ | DatasetMetricPage
+):
"""Get metadata by ID or UUID for SQL datasets only.
- For semantic views, use list_metrics for discovery and get_table for
queries.
+ For semantic views, start with list_semantic_views, then list_metrics
scoped
+ to the selected view and get_table for queries.
- Returns columns, metrics, and schema details.
+ Returns columns, metrics, and schema details. For progressive discovery,
pass
+ ``discovery={"section": "summary"}`` first, then request ``columns`` or
+ ``metrics`` with optional search/page/page_size (default 25, maximum 100).
+ Follow next_page with the same source/search/page_size. Discovery never
loads
+ all member relationships or returns SQL expressions. It cannot be combined
+ with select_columns/column_fields. Omit discovery for the legacy response.
IMPORTANT FOR LLM CLIENTS:
- Use numeric ID (e.g., 123) or UUID string (e.g., "a1b2c3d4-...")
@@ -129,6 +144,18 @@ async def get_dataset_info(
error_type=DATA_MODEL_METADATA_ERROR_TYPE,
)
+ if request.discovery is not None:
+ from superset.mcp_service.dataset.discovery import discover_dataset
+
+ try:
+ with
event_logger.log_context(action="mcp.get_dataset_info.discovery"):
+ return discover_dataset(request)
+ except Exception:
+ logger.exception("Progressive dataset metadata lookup failed")
+ return DatasetError.create(
+ "Unable to retrieve dataset metadata.", "InternalError"
+ )
+
try:
from superset.connectors.sqla.models import SqlaTable
from superset.daos.dataset import DatasetDAO
diff --git a/superset/mcp_service/semantic_layer/schemas.py
b/superset/mcp_service/semantic_layer/schemas.py
index 683bb5ab18e..bd070aeb4eb 100644
--- a/superset/mcp_service/semantic_layer/schemas.py
+++ b/superset/mcp_service/semantic_layer/schemas.py
@@ -21,8 +21,9 @@ from __future__ import annotations
from datetime import datetime
from typing import Any, Literal
+from uuid import UUID
-from pydantic import BaseModel, Field, field_validator, model_validator
+from pydantic import BaseModel, ConfigDict, Field, field_validator,
model_validator
from superset.mcp_service.chart.schemas import DataColumn, PerformanceMetadata
from superset.mcp_service.common.cache_schemas import CacheStatus
@@ -49,6 +50,42 @@ class SemanticLayerError(MCPBaseError):
return cls(error=error, error_type=error_type)
+class ListSemanticViewsRequest(BaseModel):
+ """Search stored semantic sources without loading provider metadata."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ search: str | None = Field(default=None, max_length=200)
+ page: int = Field(default=1, ge=1, strict=True)
+ page_size: int = Field(default=25, ge=1, le=100, strict=True)
+
+
+class SemanticViewSource(BaseModel):
+ """Workspace-local semantic view identity."""
+
+ type: Literal["semantic_view"] = "semantic_view"
+ id: int
+
+
+class SemanticViewSummary(BaseModel):
+ """Stored source identity only; not a claim of query readiness."""
+
+ source: SemanticViewSource
+ uuid: UUID
+ name: str
+ provider: str
+
+
+class SemanticViewPage(BaseModel):
+ """Bounded source summaries without members, configuration or total
counts."""
+
+ sources: list[SemanticViewSummary]
+ page: int
+ page_size: int
+ has_more: bool
+ next_page: int | None
+
+
# ---------------------------------------------------------------------------
# Dimension info (returned inside MetricInfo.compatible_dimensions)
# ---------------------------------------------------------------------------
diff --git a/superset/mcp_service/semantic_layer/tool/__init__.py
b/superset/mcp_service/semantic_layer/tool/__init__.py
index e345cf1f5af..2203e4a2559 100644
--- a/superset/mcp_service/semantic_layer/tool/__init__.py
+++ b/superset/mcp_service/semantic_layer/tool/__init__.py
@@ -25,3 +25,6 @@ from superset.mcp_service.semantic_layer.tool.get_table
import get_table # noqa
from superset.mcp_service.semantic_layer.tool.list_metrics import ( # noqa:
F401
list_metrics,
)
+from superset.mcp_service.semantic_layer.tool.list_semantic_views import ( #
noqa: F401
+ list_semantic_views,
+)
diff --git a/superset/mcp_service/semantic_layer/tool/list_semantic_views.py
b/superset/mcp_service/semantic_layer/tool/list_semantic_views.py
new file mode 100644
index 00000000000..8888a4daf36
--- /dev/null
+++ b/superset/mcp_service/semantic_layer/tool/list_semantic_views.py
@@ -0,0 +1,106 @@
+# 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.
+
+"""Compact, access-filtered source discovery without contacting a provider."""
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.daos.semantic_layer import SemanticViewDAO
+from superset.mcp_service.dataset_scope import (
+ get_dataset_scope,
+ MCPDatasetScopeError,
+ UNSUPPORTED_TOOL_ERROR,
+)
+from superset.mcp_service.privacy import (
+ DATA_MODEL_METADATA_ERROR_TYPE,
+ requires_data_model_metadata_access,
+ user_can_view_data_model_metadata,
+)
+from superset.mcp_service.semantic_layer.schemas import (
+ ListSemanticViewsRequest,
+ SemanticLayerError,
+ SemanticViewPage,
+ SemanticViewSource,
+ SemanticViewSummary,
+)
+from superset.semantic_layers.access import (
+ is_semantic_layers_enabled,
+ SemanticLayersDisabledError,
+)
+
+
+@tool(
+ tags=["discovery", "semantic"],
+ class_permission_name="Dataset",
+ annotations=ToolAnnotations(
+ title="List semantic views",
+ readOnlyHint=True,
+ destructiveHint=False,
+ openWorldHint=False,
+ ),
+)
+@requires_data_model_metadata_access
+async def list_semantic_views(
+ request: ListSemanticViewsRequest | None = None,
+ ctx: Context | None = None,
+) -> SemanticViewPage | SemanticLayerError:
+ """Search permitted semantic source summaries before loading any members.
+
+ Wrap parameters in ``request``. Search matches stored names/descriptions.
+ Pages start at 1, default to 25 and allow at most 100 sources. Continue
with
+ ``next_page`` and the same search/page_size. No totals, schemas,
credentials,
+ member counts or provider requests are included. A summary is not a claim
+ that the provider is configured, queryable or supported by a given
consumer.
+ Use selected-view metadata tools only when member details are needed.
+ """
+ if not is_semantic_layers_enabled():
+ return SemanticLayerError.create(
+ error=SemanticLayersDisabledError.message,
+ error_type="SemanticLayersDisabledError",
+ )
+ if not user_can_view_data_model_metadata():
+ return SemanticLayerError.create(
+ error="You don't have permission to access dataset details for
your role.",
+ error_type=DATA_MODEL_METADATA_ERROR_TYPE,
+ )
+ # The auth hook also refuses this tool in dataset-scoped mode. Retain the
+ # guard for direct service callers: semantic views are not SQL datasets.
+ if get_dataset_scope() is not None:
+ raise MCPDatasetScopeError(UNSUPPORTED_TOOL_ERROR)
+ request = request or ListSemanticViewsRequest()
+ rows = SemanticViewDAO.find_accessible_summaries(
+ search=request.search,
+ offset=(request.page - 1) * request.page_size,
+ limit=request.page_size + 1,
+ )
+ has_more = len(rows) > request.page_size
+ return SemanticViewPage(
+ sources=[
+ SemanticViewSummary(
+ source=SemanticViewSource(id=row.id),
+ uuid=row.uuid,
+ name=row.name,
+ provider=row.provider,
+ )
+ for row in rows[: request.page_size]
+ ],
+ page=request.page,
+ page_size=request.page_size,
+ has_more=has_more,
+ next_page=request.page + 1 if has_more else None,
+ )
diff --git a/superset/mcp_service/worker.py b/superset/mcp_service/worker.py
index 7e11915cdc4..42014a22a8b 100644
--- a/superset/mcp_service/worker.py
+++ b/superset/mcp_service/worker.py
@@ -107,6 +107,7 @@ METADATA_ONLY_TOOLS = frozenset(
"list_rls_filters",
"list_roles",
"list_saved_queries",
+ "list_semantic_views",
"list_tags",
"list_tasks",
"list_themes",
diff --git
a/tests/unit_tests/mcp_service/dataset/tool/test_dataset_discovery.py
b/tests/unit_tests/mcp_service/dataset/tool/test_dataset_discovery.py
new file mode 100644
index 00000000000..a12ee7e5625
--- /dev/null
+++ b/tests/unit_tests/mcp_service/dataset/tool/test_dataset_discovery.py
@@ -0,0 +1,410 @@
+# 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.
+
+"""Progressive metadata enforces real SQL access filters before bounded
reads."""
+
+from __future__ import annotations
+
+import importlib
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+from pydantic import ValidationError
+from sqlalchemy import Column, create_engine, event, MetaData, Table, text
+from sqlalchemy.pool import StaticPool
+
+from superset.connectors.sqla.models import Database, SqlaTable, SqlMetric,
TableColumn
+from superset.mcp_service.app import mcp
+from superset.mcp_service.dataset.discovery import discover_dataset
+from superset.mcp_service.dataset.schemas import GetDatasetInfoRequest
+from superset.mcp_service.privacy import DATA_MODEL_METADATA_ERROR_TYPE
+from superset.utils import json
+
+
[email protected](
+ "discovery",
+ [
+ {"section": "columns", "page": 0},
+ {"section": "metrics", "page_size": 101},
+ {"section": "columns", "page_size": True},
+ {"section": "columns", "search": "x" * 201},
+ {"section": "columns", "unknown": True},
+ ],
+)
+def test_discovery_rejects_invalid_parameters(discovery):
+ with pytest.raises(ValidationError):
+ GetDatasetInfoRequest(identifier=1, discovery=discovery)
+
+
[email protected]("selector", ["select_columns", "columns",
"column_fields"])
+def test_discovery_rejects_explicit_legacy_selectors(selector):
+ with pytest.raises(ValidationError, match="legacy field selectors"):
+ GetDatasetInfoRequest.model_validate(
+ {"identifier": 1, "discovery": {}, selector: ["column_name"]}
+ )
+ # Defaults do not count as explicit selection, and legacy requests still
work.
+ assert (
+ GetDatasetInfoRequest(identifier=1, discovery={}).discovery.section ==
"summary"
+ )
+ assert (
+ GetDatasetInfoRequest(identifier=1, **{selector:
["column_name"]}).discovery
+ is None
+ )
+
+
[email protected]
+def session_engine():
+ """Sequential MCP worker calls share this isolated in-memory database."""
+ engine = create_engine(
+ "sqlite://", connect_args={"check_same_thread": False},
poolclass=StaticPool
+ )
+ yield engine
+ engine.dispose()
+
+
[email protected]
+def catalog(session, monkeypatch):
+ """Use mapped scalar columns with deliberately no relationship/config
tables."""
+ metadata = MetaData()
+ specs = {
+ Database: ["id"],
+ SqlaTable: [
+ "id",
+ "uuid",
+ "table_name",
+ "description",
+ "sql",
+ "main_dttm_col",
+ "deleted_at",
+ "database_id",
+ "perm",
+ "schema_perm",
+ "catalog_perm",
+ ],
+ TableColumn: [
+ "id",
+ "table_id",
+ "column_name",
+ "verbose_name",
+ "description",
+ "type",
+ "filterable",
+ "groupby",
+ "is_dttm",
+ ],
+ SqlMetric: [
+ "id",
+ "table_id",
+ "metric_name",
+ "verbose_name",
+ "description",
+ "d3format",
+ ],
+ }
+ tables = {}
+ for model, names in specs.items():
+ tables[model] = Table(
+ model.__tablename__,
+ metadata,
+ *[
+ Column(
+ name,
+ model.__table__.c[name].type,
+ primary_key=model.__table__.c[name].primary_key,
+ )
+ for name in names
+ ],
+ )
+ metadata.create_all(session.get_bind())
+ session.execute(tables[Database].insert(), {"id": 1})
+ session.execute(
+ tables[SqlaTable].insert(),
+ [
+ {
+ "id": n,
+ "uuid": UUID(int=n),
+ "table_name": f"source{n}",
+ "description": "Visible description",
+ "sql": "SELECT secret FROM hidden" if n == 1 else None,
+ "main_dttm_col": None,
+ "deleted_at": None,
+ "database_id": 1,
+ "perm": f"source{n}",
+ "schema_perm": "schema",
+ "catalog_perm": "catalog",
+ }
+ for n in [1, 2]
+ ],
+ )
+ session.execute(
+ tables[TableColumn].insert(),
+ [
+ {
+ "id": n,
+ "table_id": 1,
+ "column_name": f"column{n:03}",
+ "verbose_name": None,
+ "description": "literal_%" if n == 3 else "description",
+ "type": "VARCHAR",
+ "filterable": True,
+ "groupby": True,
+ "is_dttm": False,
+ }
+ for n in range(1, 111)
+ ],
+ )
+ session.execute(
+ tables[SqlMetric].insert(),
+ [
+ {
+ "id": n,
+ "table_id": 1,
+ "metric_name": f"metric{n:03}",
+ "verbose_name": None,
+ "description": None,
+ "d3format": ".2f",
+ }
+ for n in range(1, 31)
+ ],
+ )
+ from superset import security_manager
+
+ grants = {
+ "datasource_access": {"source1"},
+ "schema_access": set(),
+ "catalog_access": set(),
+ }
+ monkeypatch.setattr(security_manager, "can_access_all_datasources",
lambda: False)
+ monkeypatch.setattr(security_manager, "get_accessible_databases", lambda:
[])
+ monkeypatch.setattr(
+ security_manager, "user_view_menu_names", lambda kind:
grants.get(kind, set())
+ )
+ monkeypatch.setattr("superset.utils.core.get_user_id", lambda: None)
+ monkeypatch.setattr(
+ "superset.mcp_service.dataset.discovery.get_dataset_scope", lambda:
None
+ )
+ statements = []
+
+ def record(_connection, _cursor, statement, _parameters, _context, _many):
+ statements.append(statement)
+
+ event.listen(session.get_bind(), "before_cursor_execute", record)
+ yield grants, statements
+ event.remove(session.get_bind(), "before_cursor_execute", record)
+
+
[email protected](
+ "discovery",
+ [
+ {},
+ {"section": "summary", "search": None, "page": 1, "page_size": 25},
+ {"section": "summary", "search": "not a match", "page": 3,
"page_size": 10},
+ ],
+)
+def test_summary_projects_no_members_or_sql(catalog, discovery):
+ _, statements = catalog
+ result = discover_dataset(
+ GetDatasetInfoRequest(identifier=str(UUID(int=1)), discovery=discovery)
+ )
+ assert result.model_dump(mode="json") == {
+ "source": {"type": "table", "id": 1, "uuid": str(UUID(int=1))},
+ "section": "summary",
+ "summary": {
+ "uuid": str(UUID(int=1)),
+ "name": "source1",
+ "description": "Visible description",
+ "is_virtual": True,
+ "main_dttm_col": None,
+ },
+ }
+ assert len(statements) == 1
+ assert "table_columns" not in statements[0]
+ assert "sql_metrics" not in statements[0]
+ assert (
+ "tables.sql AS" not in statements[0]
+ ) # Only the is_virtual predicate is selected.
+ assert "secret" not in str(result)
+
+
+def test_member_pages_use_sql_limit_and_reauthorize(catalog):
+ grants, statements = catalog
+ first = discover_dataset(
+ GetDatasetInfoRequest(identifier=1, discovery={"section": "columns"})
+ )
+ assert first.source.uuid == UUID(int=1)
+ assert len(first.items) == 25
+ assert first.next_page == 2
+ assert first.has_more
+ assert [item.column_name for item in first.items] == [
+ f"column{n:03}" for n in range(1, 26)
+ ]
+ assert len(statements) == 2
+ assert "LIMIT" in statements[-1]
+ statements.clear()
+ second = discover_dataset(
+ GetDatasetInfoRequest(identifier=1, discovery={"section": "columns",
"page": 2})
+ )
+ assert second.items[0].column_name == "column026"
+ grants["datasource_access"].clear()
+ statements.clear()
+ denied = discover_dataset(
+ GetDatasetInfoRequest(identifier=1, discovery={"section": "columns",
"page": 3})
+ )
+ assert denied.error_type == "not_found"
+ assert len(statements) == 1
+ assert "table_columns" not in statements[0]
+
+
+def test_search_is_literal_and_metrics_have_no_expressions(catalog):
+ result = discover_dataset(
+ GetDatasetInfoRequest(
+ identifier=1, discovery={"section": "columns", "search": "_%"}
+ )
+ )
+ assert [item.column_name for item in result.items] == ["column003"]
+ assert result.next_page is None
+ metrics = discover_dataset(
+ GetDatasetInfoRequest(identifier=1, discovery={"section": "metrics",
"page": 2})
+ )
+ assert metrics.source.uuid == UUID(int=1)
+ assert len(metrics.items) == 5
+ assert metrics.next_page is None
+ assert all(
+ set(item.model_dump())
+ == {"metric_name", "verbose_name", "description", "d3format"}
+ for item in metrics.items
+ )
+
+
[email protected]("kind", ["schema_access", "catalog_access"])
+def test_dataset_schema_and_catalog_grants(catalog, kind):
+ grants, _ = catalog
+ grants["datasource_access"].clear()
+ grants[kind].add("schema" if kind == "schema_access" else "catalog")
+ assert (
+ discover_dataset(GetDatasetInfoRequest(identifier=2,
discovery={})).source.id
+ == 2
+ )
+
+
+def test_inaccessible_missing_deleted_and_routing_sources(
+ catalog, session, monkeypatch
+):
+ grants, _ = catalog
+ for identifier in [2, 999, "not-an-id"]:
+ assert (
+ discover_dataset(
+ GetDatasetInfoRequest(identifier=identifier, discovery={})
+ ).error_type
+ == "not_found"
+ )
+ session.execute(text("UPDATE tables SET deleted_at = '2026-01-01' WHERE id
= 1"))
+ assert (
+ discover_dataset(GetDatasetInfoRequest(identifier=1,
discovery={})).error_type
+ == "not_found"
+ )
+ session.execute(text("UPDATE tables SET deleted_at = NULL WHERE id = 1"))
+ monkeypatch.setattr(
+ "superset.mcp_service.dataset.discovery.get_dataset_scope",
+ lambda: frozenset({UUID(int=2)}),
+ )
+ assert (
+ discover_dataset(GetDatasetInfoRequest(identifier=1,
discovery={})).error_type
+ == "not_found"
+ )
+
+
[email protected]
+async def test_tool_discovery_does_not_enter_legacy_loader(catalog):
+ module = importlib.import_module(
+ "superset.mcp_service.dataset.tool.get_dataset_info"
+ )
+ with (
+ patch(
+ "superset.mcp_service.auth.get_user_from_request",
+ return_value=Mock(id=1, username="admin", is_guest_user=False),
+ ),
+ patch.object(module, "user_can_view_data_model_metadata",
return_value=True),
+ patch.object(
+ module,
+ "subqueryload",
+ side_effect=AssertionError("legacy relationship load"),
+ ),
+ patch.object(
+ module,
+ "serialize_dataset_object",
+ side_effect=AssertionError("legacy serializer"),
+ ),
+ ):
+ async with Client(mcp) as client:
+ response = await client.call_tool(
+ "get_dataset_info", {"request": {"identifier": 1, "discovery":
{}}}
+ )
+ assert json.loads(response.content[0].text)["section"] == "summary"
+
+
[email protected]
+async def test_discovery_privacy_denial_precedes_queries():
+ module = importlib.import_module(
+ "superset.mcp_service.dataset.tool.get_dataset_info"
+ )
+ with (
+ patch(
+ "superset.mcp_service.auth.get_user_from_request",
+ return_value=Mock(id=1, username="admin", is_guest_user=False),
+ ),
+ patch.object(module, "user_can_view_data_model_metadata",
return_value=False),
+ patch(
+ "superset.mcp_service.dataset.discovery.discover_dataset",
+ side_effect=AssertionError("must not query"),
+ ),
+ ):
+ async with Client(mcp) as client:
+ response = await client.call_tool(
+ "get_dataset_info", {"request": {"identifier": 1, "discovery":
{}}}
+ )
+ assert (
+ json.loads(response.content[0].text)["error_type"]
+ == DATA_MODEL_METADATA_ERROR_TYPE
+ )
+
+
[email protected]
+async def test_discovery_backend_error_is_sanitized():
+ module = importlib.import_module(
+ "superset.mcp_service.dataset.tool.get_dataset_info"
+ )
+ with (
+ patch(
+ "superset.mcp_service.auth.get_user_from_request",
+ return_value=Mock(id=1, username="admin", is_guest_user=False),
+ ),
+ patch.object(module, "user_can_view_data_model_metadata",
return_value=True),
+ patch(
+ "superset.mcp_service.dataset.discovery.discover_dataset",
+ side_effect=RuntimeError("private database details"),
+ ),
+ ):
+ async with Client(mcp) as client:
+ response = await client.call_tool(
+ "get_dataset_info", {"request": {"identifier": 1, "discovery":
{}}}
+ )
+ result = json.loads(response.content[0].text)
+ assert result["error_type"] == "InternalError"
+ assert result["error"] == "Unable to retrieve dataset metadata."
diff --git a/tests/unit_tests/mcp_service/native_tool_inventory.json
b/tests/unit_tests/mcp_service/native_tool_inventory.json
index c017852235e..f0a6b3a5f13 100644
--- a/tests/unit_tests/mcp_service/native_tool_inventory.json
+++ b/tests/unit_tests/mcp_service/native_tool_inventory.json
@@ -248,12 +248,12 @@
"readOnlyHint": false
},
"compact_description_chars": 38,
- "description_chars": 837,
+ "description_chars": 917,
"entry_bytes": {
- "structured": 11423,
- "text_only": 3748
+ "structured": 11531,
+ "text_only": 3856
},
- "input_schema_bytes": 2632,
+ "input_schema_bytes": 2659,
"output_schema_bytes": 7659
},
"generate_explore_link": {
@@ -503,14 +503,14 @@
"openWorldHint": false,
"readOnlyHint": true
},
- "compact_description_chars": 175,
- "description_chars": 1567,
+ "compact_description_chars": 222,
+ "description_chars": 2045,
"entry_bytes": {
- "structured": 9371,
- "text_only": 3444
+ "structured": 13879,
+ "text_only": 4683
},
- "input_schema_bytes": 1575,
- "output_schema_bytes": 5911
+ "input_schema_bytes": 2326,
+ "output_schema_bytes": 9180
},
"get_instance_info": {
"annotations": {
@@ -522,11 +522,11 @@
"compact_description_chars": 79,
"description_chars": 88,
"entry_bytes": {
- "structured": 3917,
+ "structured": 3957,
"text_only": 618
},
"input_schema_bytes": 291,
- "output_schema_bytes": 3283
+ "output_schema_bytes": 3323
},
"get_layer_annotation_info": {
"annotations": {
@@ -714,11 +714,11 @@
"compact_description_chars": 253,
"description_chars": 294,
"entry_bytes": {
- "structured": 2306,
+ "structured": 2350,
"text_only": 806
},
"input_schema_bytes": 269,
- "output_schema_bytes": 1484
+ "output_schema_bytes": 1528
},
"health_check": {
"annotations": {
@@ -928,6 +928,22 @@
"input_schema_bytes": 2040,
"output_schema_bytes": 4036
},
+ "list_semantic_views": {
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": null,
+ "openWorldHint": false,
+ "readOnlyHint": true
+ },
+ "compact_description_chars": 267,
+ "description_chars": 550,
+ "entry_bytes": {
+ "structured": 2955,
+ "text_only": 1280
+ },
+ "input_schema_bytes": 464,
+ "output_schema_bytes": 1659
+ },
"list_tags": {
"annotations": {
"destructiveHint": false,
@@ -986,11 +1002,11 @@
"compact_description_chars": 263,
"description_chars": 284,
"entry_bytes": {
- "structured": 6340,
+ "structured": 6384,
"text_only": 2526
},
"input_schema_bytes": 2020,
- "output_schema_bytes": 3798
+ "output_schema_bytes": 3842
},
"manage_dashboard_certification": {
"annotations": {
@@ -1048,10 +1064,10 @@
"readOnlyHint": false
},
"compact_description_chars": 226,
- "description_chars": 1912,
+ "description_chars": 2092,
"entry_bytes": {
- "structured": 5489,
- "text_only": 3452
+ "structured": 5671,
+ "text_only": 3634
},
"input_schema_bytes": 1196,
"output_schema_bytes": 2021
@@ -1267,12 +1283,12 @@
},
"totals": {
"catalog_bytes": {
- "structured": 531994,
- "text_only": 217637
+ "structured": 540013,
+ "text_only": 220447
},
"compact_catalog_bytes": {
- "structured": 477437,
- "text_only": 163080
+ "structured": 484466,
+ "text_only": 164900
},
"largest_entry": {
"structured": {
@@ -1284,6 +1300,6 @@
"name": "manage_native_filters"
}
},
- "tool_count": 79
+ "tool_count": 80
}
}
diff --git
a/tests/unit_tests/mcp_service/semantic_layer/tool/test_list_semantic_views.py
b/tests/unit_tests/mcp_service/semantic_layer/tool/test_list_semantic_views.py
new file mode 100644
index 00000000000..89eab0da6d4
--- /dev/null
+++
b/tests/unit_tests/mcp_service/semantic_layer/tool/test_list_semantic_views.py
@@ -0,0 +1,295 @@
+# 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.
+
+"""Semantic source discovery reads authorized scalar projections, never
providers."""
+
+from __future__ import annotations
+
+import importlib
+import inspect
+from unittest.mock import Mock, patch, PropertyMock
+from uuid import UUID
+
+import pytest
+from fastmcp import Client
+from fastmcp.exceptions import ToolError
+from pydantic import ValidationError
+from sqlalchemy import Column, create_engine, event, MetaData, Table
+from sqlalchemy.pool import StaticPool
+
+from superset.daos.semantic_layer import SemanticViewDAO
+from superset.mcp_service.app import mcp
+from superset.mcp_service.dashboard_scope import DashboardScope
+from superset.mcp_service.dataset_scope import (
+ enforce_call_dataset_scope,
+ MCPDatasetScopeError,
+ SCOPED_TOOLS,
+)
+from superset.mcp_service.privacy import (
+ DATA_MODEL_METADATA_ERROR_TYPE,
+ tool_requires_data_model_metadata_access,
+)
+from superset.mcp_service.semantic_layer.schemas import
ListSemanticViewsRequest
+from superset.semantic_layers.models import SemanticLayer, SemanticView
+from superset.utils import json
+
+module = importlib.import_module(
+ "superset.mcp_service.semantic_layer.tool.list_semantic_views"
+)
+
+
[email protected](
+ "parameters",
+ [
+ {"page": 0},
+ {"page_size": 101},
+ {"page_size": True},
+ {"search": "x" * 201},
+ {"include_metrics": True},
+ ],
+)
+def test_source_request_bounds(parameters):
+ with pytest.raises(ValidationError):
+ ListSemanticViewsRequest(**parameters)
+
+
[email protected]
+def session_engine():
+ """Sequential MCP worker calls share this isolated in-memory database."""
+ engine = create_engine(
+ "sqlite://", connect_args={"check_same_thread": False},
poolclass=StaticPool
+ )
+ yield engine
+ engine.dispose()
+
+
[email protected]
+def sources(session, monkeypatch):
+ """Encrypted configuration columns are deliberately absent from this
database."""
+ metadata = MetaData()
+ tables = {}
+ for model, names in [
+ (SemanticLayer, ["uuid", "type", "perm"]),
+ (
+ SemanticView,
+ ["id", "uuid", "name", "description", "perm",
"semantic_layer_uuid"],
+ ),
+ ]:
+ tables[model] = Table(
+ model.__tablename__,
+ metadata,
+ *[
+ Column(
+ name,
+ model.__table__.c[name].type,
+ primary_key=model.__table__.c[name].primary_key,
+ )
+ for name in names
+ ],
+ )
+ metadata.create_all(session.get_bind())
+ session.execute(
+ tables[SemanticLayer].insert(),
+ [
+ {
+ "uuid": UUID(int=n),
+ "type": "snowflake" if n == 1 else "metricflow",
+ "perm": f"layer{n}",
+ }
+ for n in [1, 2]
+ ],
+ )
+ session.execute(
+ tables[SemanticView].insert(),
+ [
+ {
+ "id": n,
+ "uuid": UUID(int=n),
+ "name": f"Source{n:03}",
+ "description": "literal_%" if n == 3 else "description",
+ "perm": f"view{n}",
+ "semantic_layer_uuid": UUID(int=1 if n < 100 else 2),
+ }
+ for n in range(1, 111)
+ ],
+ )
+ from superset import security_manager
+
+ grants = {"layer1"}
+ monkeypatch.setattr(security_manager, "can_access_all_datasources",
lambda: False)
+ monkeypatch.setattr(security_manager, "user_view_menu_names", lambda
_kind: grants)
+ monkeypatch.setattr(module, "user_can_view_data_model_metadata", lambda:
True)
+ monkeypatch.setattr(module, "is_semantic_layers_enabled", lambda: True)
+ monkeypatch.setattr(module, "get_dataset_scope", lambda: None)
+ statements = []
+
+ def record(_connection, _cursor, statement, _parameters, _context, _many):
+ statements.append(statement)
+
+ event.listen(session.get_bind(), "before_cursor_execute", record)
+ yield grants, statements
+ event.remove(session.get_bind(), "before_cursor_execute", record)
+
+
+def test_scalar_index_filters_before_paging_and_never_loads_config(sources):
+ grants, statements = sources
+ with patch.object(
+ SemanticLayer,
+ "implementation",
+ new_callable=PropertyMock,
+ side_effect=AssertionError("provider called"),
+ ):
+ rows = SemanticViewDAO.find_accessible_summaries(
+ search=None, offset=25, limit=26
+ )
+ assert len(rows) == 26
+ assert rows[0].id == 26
+ assert len(statements) == 1
+ assert "LIMIT" in statements[0]
+ assert "OFFSET" in statements[0]
+ assert "configuration" not in statements[0]
+ assert "semantic_layers.name" not in statements[0]
+ grants.clear()
+ grants.add("view110")
+ rows = SemanticViewDAO.find_accessible_summaries(search=None, offset=0,
limit=26)
+ assert [row.id for row in rows] == [110]
+ assert rows[0].provider == "metricflow"
+ grants.clear()
+ assert (
+ SemanticViewDAO.find_accessible_summaries(search=None, offset=0,
limit=26) == []
+ )
+
+
+def test_source_search_literal_substring(sources):
+ rows = SemanticViewDAO.find_accessible_summaries(search="_%", offset=0,
limit=26)
+ assert [row.id for row in rows] == [3]
+ rows = SemanticViewDAO.find_accessible_summaries(
+ search="sOURCE003", offset=0, limit=26
+ )
+ assert [row.id for row in rows] == [3]
+
+
[email protected]
+async def test_tool_default_page_and_continuation(sources):
+ with patch(
+ "superset.mcp_service.auth.get_user_from_request",
+ return_value=Mock(id=1, username="admin", is_guest_user=False),
+ ):
+ async with Client(mcp) as client:
+ first = json.loads(
+ (await client.call_tool("list_semantic_views",
{})).content[0].text
+ )
+ second = json.loads(
+ (
+ await client.call_tool(
+ "list_semantic_views", {"request": {"page":
first["next_page"]}}
+ )
+ )
+ .content[0]
+ .text
+ )
+ assert len(first["sources"]) == 25
+ assert first["has_more"]
+ assert first["next_page"] == 2
+ assert second["sources"][0]["source"] == {"type": "semantic_view", "id":
26}
+ assert set(first) == {"sources", "page", "page_size", "has_more",
"next_page"}
+ assert set(first["sources"][0]) == {"source", "uuid", "name", "provider"}
+
+
[email protected]
[email protected]("view_access", [False, True])
+async def test_dashboard_filters_do_not_replace_source_grants(sources,
view_access):
+ grants, _ = sources
+ grants.clear()
+ if view_access:
+ grants.add("view110")
+ scope = DashboardScope(
+ dashboard_id=7,
+ chart_filters={11: {"filters": [{"col": "country", "op": "==", "val":
"US"}]}},
+ )
+ with (
+ patch(
+ "superset.mcp_service.dashboard_scope.get_request_dashboard_scope",
+ return_value=scope,
+ ),
+ patch(
+ "superset.mcp_service.auth.get_user_from_request",
+ return_value=Mock(id=1, username="reader", is_guest_user=False),
+ ),
+ patch.object(
+ SemanticViewDAO,
+ "find_accessible_summaries",
+ wraps=SemanticViewDAO.find_accessible_summaries,
+ ) as discovery,
+ ):
+ async with Client(mcp) as client:
+ response = json.loads(
+ (await client.call_tool("list_semantic_views",
{})).content[0].text
+ )
+ discovery.assert_called_once_with(search=None, offset=0, limit=26)
+ assert [source["source"]["id"] for source in response["sources"]] == (
+ [110] if view_access else []
+ )
+
+
[email protected]
[email protected]("gate", ["feature", "privacy", "routing"])
+async def test_source_gate_precedes_dao(gate, monkeypatch):
+ monkeypatch.setattr(module, "is_semantic_layers_enabled", lambda: gate !=
"feature")
+ monkeypatch.setattr(
+ module, "user_can_view_data_model_metadata", lambda: gate != "privacy"
+ )
+ monkeypatch.setattr(
+ module, "get_dataset_scope", lambda: frozenset() if gate == "routing"
else None
+ )
+ with (
+ patch(
+ "superset.mcp_service.auth.get_user_from_request",
+ return_value=Mock(id=1, username="admin", is_guest_user=False),
+ ),
+ patch.object(
+ SemanticViewDAO,
+ "find_accessible_summaries",
+ side_effect=AssertionError("DAO called before gate"),
+ ),
+ ):
+ async with Client(mcp) as client:
+ if gate == "routing":
+ with pytest.raises(ToolError, match="configured dataset
scope"):
+ await client.call_tool("list_semantic_views", {})
+ else:
+ result = json.loads(
+ (await client.call_tool("list_semantic_views",
{})).content[0].text
+ )
+ assert result["error_type"] == (
+ "SemanticLayersDisabledError"
+ if gate == "feature"
+ else DATA_MODEL_METADATA_ERROR_TYPE
+ )
+
+
+def test_index_remains_outside_dataset_routing_allowlist():
+ assert "list_semantic_views" not in SCOPED_TOOLS
+ assert tool_requires_data_model_metadata_access(module.list_semantic_views)
+
+
+def test_routing_auth_hook_refuses_source_index(monkeypatch):
+ monkeypatch.setattr(
+ "superset.mcp_service.dataset_scope.get_dataset_scope", lambda:
frozenset()
+ )
+ with pytest.raises(MCPDatasetScopeError, match="configured dataset scope"):
+ enforce_call_dataset_scope("list_semantic_views", inspect.Signature(),
(), {})
diff --git a/tests/unit_tests/mcp_service/test_dashboard_scope.py
b/tests/unit_tests/mcp_service/test_dashboard_scope.py
index f067d79600c..c9c37bd04fc 100644
--- a/tests/unit_tests/mcp_service/test_dashboard_scope.py
+++ b/tests/unit_tests/mcp_service/test_dashboard_scope.py
@@ -685,7 +685,9 @@ def
test_unclassified_tools_are_refused_under_scope(tool_name: str) -> None:
apply_call_dashboard_scope(tool_name, inspect.Signature(), (), {})
[email protected]("tool_name", ["list_charts", "get_catalog"])
[email protected](
+ "tool_name", ["list_charts", "get_catalog", "list_semantic_views"]
+)
def test_neutral_tools_pass_untouched(tool_name: str) -> None:
kwargs = {"request": {"page": 1}}
with scope_header(encode(scope_payload({"11": {"filters": [CLIENT_A]}}))):
diff --git a/tests/unit_tests/mcp_service/test_mcp_tool_registration.py
b/tests/unit_tests/mcp_service/test_mcp_tool_registration.py
index 387172a084b..7b1e582bc6c 100644
--- a/tests/unit_tests/mcp_service/test_mcp_tool_registration.py
+++ b/tests/unit_tests/mcp_service/test_mcp_tool_registration.py
@@ -97,6 +97,7 @@ EXPECTED_TOOL_OUTPUT_FIELDS = {
"list_rls_filters": "rls_filters",
"list_roles": "roles",
"list_saved_queries": "saved_queries",
+ "list_semantic_views": "sources",
"list_tags": "tags",
"list_tasks": "tasks",
"list_themes": "themes",
@@ -126,6 +127,7 @@ EXPECTED_TOP_LEVEL_OUTPUT_FIELDS = {
"get_chart_info": {"id", "slice_name", "viz_type", "form_data"},
"get_dashboard_info": {"dashboard_title", "charts", "filter_state"},
"get_dataset_info": {"table_name", "schema", "columns", "metrics"},
+ "list_semantic_views": {"sources", "page", "page_size", "has_more",
"next_page"},
"open_sql_lab_with_context": {"url", "title", "database_id"},
"update_chart_preview": {"chart", "error", "form_data", "success"},
}
diff --git a/tests/unit_tests/mcp_service/test_tool_inventory.py
b/tests/unit_tests/mcp_service/test_tool_inventory.py
index 113e1fc7cf0..f907548e715 100644
--- a/tests/unit_tests/mcp_service/test_tool_inventory.py
+++ b/tests/unit_tests/mcp_service/test_tool_inventory.py
@@ -86,7 +86,8 @@ TOOL_BUDGETS = {
"get_dashboard_info": 5_000,
"get_dashboard_layout": 1_600,
"get_database_info": 1_400,
- "get_dataset_info": 2_400,
+ # Progressive discovery adds bounded summary/member request fields (2,935
bytes).
+ "get_dataset_info": 3_100,
"get_instance_info": 900,
"get_layer_annotation_info": 1_100,
"get_query_info": 1_100,
@@ -119,6 +120,7 @@ TOOL_BUDGETS = {
"list_rls_filters": 2_600,
"list_roles": 2_700,
"list_saved_queries": 3_000,
+ "list_semantic_views": 1_200, # Compact source index: 1,074 measured
bytes.
"list_tags": 3_100,
"list_tasks": 2_700,
"list_themes": 3_000,
diff --git a/tests/unit_tests/mcp_service/test_worker_metadata_pool.py
b/tests/unit_tests/mcp_service/test_worker_metadata_pool.py
index 419af34fb56..6da1ad9be87 100644
--- a/tests/unit_tests/mcp_service/test_worker_metadata_pool.py
+++ b/tests/unit_tests/mcp_service/test_worker_metadata_pool.py
@@ -878,8 +878,9 @@ async def
test_saturated_default_pool_never_waits_for_a_connection(
@pytest.mark.asyncio
[email protected]("tool_name", ["list_charts", "list_semantic_views"])
async def test_metadata_only_tools_answer_while_warehouse_bound_is_full(
- app: Any, default_pool_engine: Engine
+ app: Any, default_pool_engine: Engine, tool_name: str
) -> None:
"""Slow warehouse calls fill their bound; listing tools keep succeeding.
@@ -900,7 +901,7 @@ async def
test_metadata_only_tools_answer_while_warehouse_bound_is_full(
release.wait(timeout=5)
return "slow"
- def list_charts() -> int:
+ def list_metadata() -> int:
"""Answer from the metadata database alone."""
return db.session.execute(text("SELECT 1")).scalar()
@@ -910,7 +911,7 @@ async def
test_metadata_only_tools_answer_while_warehouse_bound_is_full(
patch("superset.mcp_service.worker._get_pool", return_value=pool),
):
mcp.tool(mcp_auth_hook(slow_query, tool_name="slow_query"))
- mcp.tool(mcp_auth_hook(list_charts, tool_name="list_charts"))
+ mcp.tool(mcp_auth_hook(list_metadata, tool_name=tool_name),
name=tool_name)
async with Client(mcp) as client:
slow = [
asyncio.create_task(client.call_tool("slow_query", {}))
@@ -921,10 +922,7 @@ async def
test_metadata_only_tools_answer_while_warehouse_bound_is_full(
with pytest.raises(ToolError, match="server busy"):
await client.call_tool("slow_query", {})
listed = await asyncio.gather(
- *(
- client.call_tool("list_charts", {})
- for _ in range(metadata_workers)
- )
+ *(client.call_tool(tool_name, {}) for _ in
range(metadata_workers))
)
finally:
release.set()