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


##########
superset/mcp_service/saved_query/tool/get_saved_query_info.py:
##########
@@ -0,0 +1,129 @@
+# 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 saved query info FastMCP tool
+
+This module contains the FastMCP tool for getting detailed information
+about a specific saved SQL query.
+"""
+
+import logging
+from datetime import datetime, timezone
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.mcp_core import ModelGetInfoCore
+from superset.mcp_service.saved_query.schemas import (
+    GetSavedQueryInfoRequest,
+    SavedQueryError,
+    SavedQueryInfo,
+    serialize_saved_query_object,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@tool(
+    tags=["discovery"],
+    class_permission_name="SavedQuery",
+    annotations=ToolAnnotations(
+        title="Get saved query info",
+        readOnlyHint=True,
+        destructiveHint=False,
+    ),
+)
+async def get_saved_query_info(
+    request: GetSavedQueryInfoRequest, ctx: Context
+) -> SavedQueryInfo | SavedQueryError:
+    """Get saved query details by ID or UUID.
+
+    Returns the full saved query including SQL text, label, database,
+    schema, and timestamps.
+
+    IMPORTANT FOR LLM CLIENTS:
+    - Use numeric ID (e.g., 42) or UUID string (e.g., "a1b2c3d4-...")
+    - To find a saved query ID, use the list_saved_queries tool first
+
+    Example usage:
+    ```json
+    {
+        "identifier": 42
+    }
+    ```
+
+    Or with UUID:
+    ```json
+    {
+        "identifier": "a1b2c3d4-5678-90ab-cdef-1234567890ab"
+    }
+    ```
+    """
+    await ctx.info(
+        "Retrieving saved query information: identifier=%s" % 
(request.identifier,)
+    )
+
+    try:
+        from superset.daos.query import SavedQueryDAO
+
+        with 
event_logger.log_context(action="mcp.get_saved_query_info.lookup"):
+            get_tool = ModelGetInfoCore(
+                dao_class=SavedQueryDAO,
+                output_schema=SavedQueryInfo,
+                error_schema=SavedQueryError,
+                serializer=serialize_saved_query_object,
+                supports_slug=False,
+                logger=logger,
+            )
+
+            result = get_tool.run_tool(request.identifier)
+
+        if isinstance(result, SavedQueryInfo):
+            await ctx.info(
+                "Saved query information retrieved successfully: "
+                "saved_query_id=%s, label=%s, db_id=%s"
+                % (
+                    result.id,
+                    result.label,
+                    result.db_id,
+                )
+            )
+        else:
+            await ctx.warning(
+                "Saved query retrieval failed: error_type=%s, error=%s"
+                % (result.error_type, result.error)
+            )
+
+        return result
+
+    except Exception as e:

Review Comment:
   Thanks for the review! This asymmetry between list tools and get-info tools 
is intentional and consistent with the existing patterns in the codebase:
   
   - **List tools** (`list_saved_queries`, `list_queries`): catch, log with 
request context, then re-raise — so `GlobalErrorHandlerMiddleware` returns a 
structured error response at the transport boundary.
   - **Get-info tools** (`get_saved_query_info`, `get_query_info`): catch and 
return a typed error schema directly, giving callers a stable typed union 
response (`SavedQueryInfo | SavedQueryError`).
   
   The pattern for `list_saved_queries` mirrors `list_queries.py` exactly.



##########
superset/mcp_service/query/tool/list_queries.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.
+
+"""
+List queries FastMCP tool
+
+This module contains the FastMCP tool for listing SQL query history
+with filtering, search, and pagination.
+"""
+
+import logging
+
+from fastmcp import Context
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset.extensions import event_logger
+from superset.mcp_service.mcp_core import ModelListCore
+from superset.mcp_service.query.schemas import (
+    ALL_QUERY_COLUMNS,
+    DEFAULT_QUERY_COLUMNS,
+    ListQueriesRequest,
+    QueryError,
+    QueryFilter,
+    QueryInfo,
+    QueryList,
+    serialize_query_object,
+    SORTABLE_QUERY_COLUMNS,
+)
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_LIST_QUERIES_REQUEST = ListQueriesRequest()
+
+
+@tool(
+    tags=["core"],
+    class_permission_name="Query",
+    annotations=ToolAnnotations(
+        title="List queries",
+        readOnlyHint=True,
+        destructiveHint=False,
+    ),
+)
+async def list_queries(
+    request: ListQueriesRequest | None = None,
+    ctx: Context | None = None,
+) -> QueryList | QueryError:
+    """List SQL query history with filtering and search.
+
+    Returns recent queries executed by the current user (or all queries for
+    admins), including SQL text, status, timing, and database information.
+    Results are ordered by start_time descending (most recent first) by 
default.
+
+    Sortable columns for order_column: id, start_time, end_time, status,
+    database_id, changed_on
+    """
+    if ctx is None:
+        raise RuntimeError("FastMCP context is required for list_queries")
+
+    request = request or _DEFAULT_LIST_QUERIES_REQUEST.model_copy(deep=True)
+
+    await ctx.info(
+        "Listing queries: page=%s, page_size=%s, search=%s"
+        % (
+            request.page,
+            request.page_size,
+            request.search,
+        )
+    )
+    await ctx.debug(
+        "Query listing parameters: filters=%s, order_column=%s, "
+        "order_direction=%s, select_columns=%s"
+        % (
+            request.filters,
+            request.order_column,
+            request.order_direction,
+            request.select_columns,
+        )
+    )
+
+    try:
+        from superset.daos.query import QueryDAO
+
+        def _serialize_query(obj: object, cols: list[str] | None) -> QueryInfo 
| None:
+            return serialize_query_object(obj)
+
+        list_tool = ModelListCore(
+            dao_class=QueryDAO,
+            output_schema=QueryInfo,
+            item_serializer=_serialize_query,
+            filter_type=QueryFilter,
+            default_columns=DEFAULT_QUERY_COLUMNS,
+            search_columns=["tab_name", "sql"],
+            list_field_name="queries",
+            output_list_schema=QueryList,
+            all_columns=ALL_QUERY_COLUMNS,
+            sortable_columns=SORTABLE_QUERY_COLUMNS,
+            logger=logger,
+        )
+
+        with event_logger.log_context(action="mcp.list_queries.query"):
+            result = list_tool.run_tool(
+                filters=request.filters,
+                search=request.search,
+                select_columns=request.select_columns,
+                order_column=request.order_column or "start_time",
+                order_direction=request.order_direction,
+                page=max(request.page - 1, 0),
+                page_size=request.page_size,
+            )
+
+        await ctx.info(
+            "Queries listed successfully: count=%s, total_count=%s, 
total_pages=%s"
+            % (
+                len(result.queries) if hasattr(result, "queries") else 0,
+                getattr(result, "total_count", None),
+                getattr(result, "total_pages", None),
+            )
+        )
+
+        columns_to_filter = result.columns_requested
+        await ctx.debug(
+            "Applying field filtering via serialization context: columns=%s"
+            % (columns_to_filter,)
+        )
+        with event_logger.log_context(action="mcp.list_queries.serialization"):
+            return result.model_dump(
+                mode="json",
+                context={"select_columns": columns_to_filter},
+            )
+
+    except Exception as e:
+        await ctx.error(
+            "Query listing failed: page=%s, page_size=%s, error=%s, 
error_type=%s"
+            % (
+                request.page,
+                request.page_size,
+                str(e),
+                type(e).__name__,
+            )
+        )
+        raise

Review Comment:
   Thanks for the note! The `ctx.error()` call before re-raising is not 
redundant — it logs request-scoped context (page number, page size) into the 
**MCP protocol stream**, where LLM clients observing the conversation can see 
it. The `GlobalErrorHandlerMiddleware` processes the exception at the transport 
layer but doesn't have access to the tool's request parameters.
   
   This pattern is intentional and mirrors `list_queries.py` exactly, so both 
list tools behave consistently.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to