bito-code-review[bot] commented on code in PR #41611: URL: https://github.com/apache/superset/pull/41611#discussion_r3508672123
########## 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: <div> <div id="suggestion"> <div id="issue"><b>Function complexity exceeds thresholds</b></div> <div id="fix"> The `get_table` function has too many return statements (18 > 6), branches (30 > 12), and statements (114 > 50). Consider extracting helper functions for validation, datasource resolution, and response formatting. </div> </div> <small><i>Code Review Run #18462e</i></small> </div> --- Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>) - [ ] Yes, avoid them ########## 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: <div> <div id="suggestion"> <div id="issue"><b>Missing unit tests for validate_names</b></div> <div id="fix"> Add unit tests for `validate_names`. Adaptive rules [11730] and [11731] require tests for new MCP utilities covering success paths, error scenarios, and validation failures. Place tests in the appropriate test directory following established MCP patterns. </div> </div> <small><i>Code Review Run #18462e</i></small> </div> --- Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>) - [ ] Yes, avoid them ########## 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: <div> <div id="suggestion"> <div id="issue"><b>Missing unit tests for new DAO method</b></div> <div id="fix"> `find_accessible` is a new permission-filtering DAO method added without unit tests in `dao_test.py`. It is only exercised indirectly through mocked calls in `test_list_metrics.py`, leaving the permission branches (`can_access_all_datasources` path, view-level `perm.in_`, layer-level `perm.in_`) unverified at the unit level. </div> </div> <small><i>Code Review Run #18462e</i></small> </div> --- Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>) - [ ] Yes, avoid them -- 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]
