bito-code-review[bot] commented on code in PR #41611: URL: https://github.com/apache/superset/pull/41611#discussion_r3531347904
########## superset/mcp_service/semantic_layer/tool/get_table.py: ########## @@ -0,0 +1,437 @@ +# 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: get_table + +Query a data source (built-in dataset or external semantic view) using +metric and dimension names, returning tabular results. +""" + +import logging +import time +from typing import Any + +from fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.commands.exceptions import CommandException +from superset.exceptions import OAuth2Error, OAuth2RedirectError, SupersetException +from superset.extensions import event_logger +from superset.mcp_service.chart.schemas import PerformanceMetadata +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 ( + GetTableRequest, + GetTableResponse, + SemanticLayerError, +) +from superset.mcp_service.utils.cache_utils import get_cache_status_from_result +from superset.mcp_service.utils.oauth2_utils import build_oauth2_redirect_message +from superset.mcp_service.utils.query_utils import validate_names +from superset.mcp_service.utils.response_utils import format_data_columns + +logger = logging.getLogger(__name__) + + +def _build_query_dict( + request: GetTableRequest, + time_col: str | None, +) -> dict[str, Any]: + """Assemble the query dict for QueryContextFactory.""" + filters: list[dict[str, Any]] = [ + {"col": f.col, "op": f.op, "val": f.val} for f in request.filters + ] + if request.time_range and time_col: + filters.append( + {"col": time_col, "op": "TEMPORAL_RANGE", "val": request.time_range} + ) + + query_dict: dict[str, Any] = { + "filters": filters, + "columns": request.dimensions, + "metrics": request.metrics, + "row_limit": request.row_limit, + "order_desc": request.order_desc, + } + if time_col: + query_dict["granularity"] = time_col + if request.order_by: + query_dict["orderby"] = [ + (col, not request.order_desc) for col in request.order_by + ] + return query_dict + + +@tool( + tags=["data", "semantic"], + class_permission_name="Dataset", + annotations=ToolAnnotations( + title="Get table", + readOnlyHint=True, + destructiveHint=False, + ), +) +@requires_data_model_metadata_access +async def get_table( # noqa: C901 Review Comment: <!-- Bito Reply --> The refactoring of `get_table` into smaller, specialized helper functions is a positive change that improves maintainability and readability by reducing the complexity of the main function. This approach aligns with best practices for managing function size and complexity, making the code easier to test and reason about. ########## superset/mcp_service/utils/query_utils.py: ########## @@ -0,0 +1,40 @@ +# 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. + +"""Shared query validation utilities for MCP tools.""" + +import difflib + + +def validate_names( + requested: list[str], + valid: set[str], + kind: str, +) -> list[str]: + """Return list of error messages for names not found in *valid*. + + Includes close-match suggestions when available. + """ + errors: list[str] = [] + for name in requested: + if name not in valid: + suggestions = difflib.get_close_matches(name, valid, n=3, cutoff=0.6) + msg = f"Unknown {kind}: '{name}'" + if suggestions: + msg += f". Did you mean: {', '.join(suggestions)}?" + errors.append(msg) + return errors Review Comment: <!-- Bito Reply --> The addition of unit tests for `validate_names` in `tests/unit_tests/mcp_service/utils/test_query_utils.py` effectively addresses the requirement to cover success paths, error scenarios, and validation failures. These tests ensure that the utility correctly identifies unknown names, provides appropriate close-match suggestions, and handles custom error labels as expected. ########## superset/daos/semantic_layer.py: ########## @@ -201,6 +201,29 @@ def validate_update_uniqueness( for c in candidates ) + @classmethod + def find_accessible(cls) -> list[SemanticView]: + """Return all views the current user can access, filtered at SQL level. + + Mirrors the permission filter in ``DatasourceDAO.build_semantic_view_query`` + to avoid per-row Python-level access checks when listing all views. + """ + from sqlalchemy import or_ + + query = db.session.query(SemanticView) + if not security_manager.can_access_all_datasources(): + perms = security_manager.user_view_menu_names("datasource_access") + query = query.outerjoin( + SemanticLayer, + SemanticLayer.uuid == SemanticView.semantic_layer_uuid, + ).filter( + or_( + SemanticView.perm.in_(perms), + SemanticLayer.perm.in_(perms), + ) + ) + return query.all() Review Comment: <!-- Bito Reply --> The user has addressed the reviewer's suggestion regarding missing unit tests for the `find_accessible` method. The user confirmed that unit tests covering the `can_access_all_datasources` path, view-level `perm.in_`, layer-level `perm.in_`, and the no-permissions-granted case have been added to `tests/unit_tests/semantic_layers/dao_test.py`. -- 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]
