codeant-ai-for-open-source[bot] commented on code in PR #40344: URL: https://github.com/apache/superset/pull/40344#discussion_r3305697722
########## superset/mcp_service/action_log/tool/list_action_logs.py: ########## @@ -0,0 +1,153 @@ +# 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 action logs MCP tool.""" + +import logging +from datetime import datetime, timedelta, timezone + +from fastmcp import Context +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.daos.base import ColumnOperator, ColumnOperatorEnum +from superset.extensions import event_logger +from superset.mcp_service.action_log.schemas import ( + ActionLogError, + ActionLogFilter, + ActionLogInfo, + ActionLogList, + ALL_LOG_COLUMNS, + DEFAULT_LOG_COLUMNS, + ListActionLogsRequest, + LOG_SORTABLE_COLUMNS, + serialize_action_log_object, +) +from superset.mcp_service.mcp_core import ModelListCore + +logger = logging.getLogger(__name__) + +_DEFAULT_LIST_ACTION_LOGS_REQUEST = ListActionLogsRequest() + + +@tool( + tags=["core"], + class_permission_name="Log", + annotations=ToolAnnotations( + title="List action logs", + readOnlyHint=True, + destructiveHint=False, + ), +) +async def list_action_logs( + request: ListActionLogsRequest | None = None, + ctx: Context | None = None, +) -> ActionLogList | ActionLogError: + """List Superset action logs with filtering and pagination. + + Returns audit log entries recording user interactions with dashboards and + charts. Defaults to the last 7 days to avoid pulling large result sets. + + ADMIN-ONLY: This tool requires admin privileges. Non-admin users will + receive a permission error. + + Sortable columns for order_column: id, dttm + Filter columns: action, user_id, dashboard_id, slice_id, dttm + + When no dttm filter is provided the tool automatically applies + dttm >= (now - 7 days). Add an explicit dttm filter to override. + """ + if ctx is None: + raise RuntimeError("FastMCP context is required for list_action_logs") + + request = request or _DEFAULT_LIST_ACTION_LOGS_REQUEST.model_copy(deep=True) + + await ctx.info( + "Listing action logs: page=%s, page_size=%s" % (request.page, request.page_size) + ) + await ctx.debug( + "Action log parameters: filters=%s, order_column=%s, order_direction=%s" + % (request.filters, request.order_column, request.order_direction) + ) + + try: + from superset.daos.log import LogDAO + + # Inject default 7-day dttm filter unless caller already provides one + filters: list[ColumnOperator] = list(request.filters) + has_dttm_filter = any(getattr(f, "col", None) == "dttm" for f in filters) + if not has_dttm_filter: + cutoff = (datetime.now(timezone.utc) - timedelta(days=7)).isoformat() + default_filter = ActionLogFilter( + col="dttm", + opr=ColumnOperatorEnum.gte, + value=cutoff, + ) Review Comment: **Suggestion:** The default `dttm` filter is built as an ISO string (`.isoformat()`), but the DAO filtering layer compares directly against the SQLAlchemy `DateTime` column. Passing a string here can produce backend-dependent comparisons (especially around timezone handling for a timezone-naive column) and can exclude valid rows near the cutoff. Build the cutoff as a `datetime` value (aligned with the column type) and only serialize it to string when preparing response metadata. [type error] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ MCP action-log listing may omit logs near seven-day cutoff. - ⚠️ Admin audit views via MCP see incomplete or inconsistent results. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Start the MCP service so tools are registered via `superset/mcp_service/app.py:24-27`, which imports and registers the `list_action_logs` tool. 2. From an MCP client, invoke the `list_action_logs` tool without providing any `dttm` filter (e.g., `request=None` or `ListActionLogsRequest` with `filters=[]`), causing `list_action_logs()` in `superset/mcp_service/action_log/tool/list_action_logs.py:55-77` to clone the default request. 3. In `list_action_logs()` at `list_action_logs.py:89-99`, `filters` is initialized from `request.filters`, `has_dttm_filter` is False, and the code builds `cutoff = (datetime.now(timezone.utc) - timedelta(days=7)).isoformat()` (line 93) and an `ActionLogFilter(col="dttm", opr=ColumnOperatorEnum.gte, value=cutoff)` (lines 94-98), so the `value` passed down is a string, not a `datetime`. 4. `ModelListCore.run_tool()` in `superset/mcp_service/mcp_core.py:248-50` forwards this filter as `column_operators` to `LogDAO.list()`, which in turn calls `BaseDAO.apply_column_operators()` at `superset/daos/base.py:258-30`; there, `ColumnOperatorEnum.gte.apply(column, value)` (lines 58-79) is applied directly to `Log.dttm` (a `DateTime` column defined in `superset/models/core.py:4-18`) with the string `cutoff`, relying on backend-specific string-to-datetime coercion. Because `Log.dttm` is timezone-naive (`default=datetime.utcnow`) while the cutoff string is built from an aware UTC datetime, and the comparison is against a raw string, rows near the 7‑day boundary can be inconsistently included or excluded depending on how the database/dialect coerces the string, leading to subtly incorrect default results for this tool. ``` </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d49f22c80db348edaf21362136fda158&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=d49f22c80db348edaf21362136fda158&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/action_log/tool/list_action_logs.py **Line:** 93:98 **Comment:** *Type Error: The default `dttm` filter is built as an ISO string (`.isoformat()`), but the DAO filtering layer compares directly against the SQLAlchemy `DateTime` column. Passing a string here can produce backend-dependent comparisons (especially around timezone handling for a timezone-naive column) and can exclude valid rows near the cutoff. Build the cutoff as a `datetime` value (aligned with the column type) and only serialize it to string when preparing response metadata. 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%2F40344&comment_hash=a322a22db60e2166b13817106e7bf5b0e3826d31c90773d07559b83c1c05e8b5&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40344&comment_hash=a322a22db60e2166b13817106e7bf5b0e3826d31c90773d07559b83c1c05e8b5&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]
