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


##########
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:
   This is intentional and was specifically required by a prior review. 
`ActionLogFilter.value` is typed as `str | int | float | bool | list[...]` — no 
`datetime` allowed — so the value must be an ISO string. The DAO filter layer 
in `ColumnOperatorEnum.apply()` handles the string-to-datetime comparison 
correctly at the SQL level. Passing a `datetime` object would cause a Pydantic 
validation error when `ActionLogList.filters_applied` tries to validate the 
injected filter.



##########
tests/unit_tests/mcp_service/task/tool/test_task_tools.py:
##########
@@ -0,0 +1,249 @@
+# 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.
+
+"""Unit tests for list_tasks and get_task_info MCP tools."""
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastmcp import Client
+from pydantic import ValidationError
+
+from superset.mcp_service.app import mcp
+from superset.mcp_service.task.schemas import ListTasksRequest, 
TaskColumnFilter
+from superset.utils import json
+
+SAMPLE_UUID = str(uuid.uuid4())
+
+
+def create_mock_task(
+    task_id: int = 1,
+    task_uuid: str | None = None,
+    task_type: str = "sql_execution",
+    task_key: str = "default-key",
+    task_name: str | None = None,
+    status: str = "success",
+    scope: str = "private",
+    changed_on: datetime | None = None,
+    created_on: datetime | None = None,
+) -> MagicMock:
+    task = MagicMock()
+    task.id = task_id
+    task.uuid = task_uuid or SAMPLE_UUID
+    task.task_type = task_type
+    task.task_key = task_key
+    task.task_name = task_name
+    task.status = status
+    task.scope = scope
+    task.changed_on = changed_on or datetime(2024, 1, 2, 10, 0, 0, 
tzinfo=timezone.utc)
+    task.created_on = created_on or datetime(2024, 1, 1, 9, 0, 0, 
tzinfo=timezone.utc)
+    return task
+
+
[email protected]
+def mcp_server():
+    return mcp
+
+
[email protected](autouse=True)
+def mock_auth():
+    from unittest.mock import Mock
+
+    with patch("superset.mcp_service.auth.get_user_from_request") as 
mock_get_user:
+        mock_user = Mock()
+        mock_user.id = 1
+        mock_user.username = "testuser"
+        mock_get_user.return_value = mock_user
+        yield mock_get_user
+
+
+class TestTaskColumnFilterSchema:
+    def test_valid_filter_columns_accepted(self):
+        for col in ("task_type", "status", "scope"):
+            f = TaskColumnFilter(col=col, opr="eq", value="test")
+            assert f.col == col
+
+    def test_invalid_filter_column_rejected(self):
+        with pytest.raises(ValidationError):
+            TaskColumnFilter(col="user_id", opr="eq", value=1)
+
+    def test_uuid_column_rejected(self):
+        with pytest.raises(ValidationError):
+            TaskColumnFilter(col="uuid", opr="eq", value="some-uuid")
+
+
+@patch("superset.daos.tasks.TaskDAO.list")
[email protected]
+async def test_list_tasks_basic(mock_list, mcp_server):
+    """Basic task listing returns structured response."""
+    task = create_mock_task()
+    mock_list.return_value = ([task], 1)
+
+    async with Client(mcp_server) as client:
+        result = await client.call_tool("list_tasks", {})
+
+    data = json.loads(result.content[0].text)
+    assert data["tasks"] is not None
+    assert len(data["tasks"]) == 1
+    assert data["tasks"][0]["id"] == 1
+    assert data["tasks"][0]["task_type"] == "sql_execution"
+    assert data["tasks"][0]["status"] == "success"
+
+
+@patch("superset.daos.tasks.TaskDAO.list")
[email protected]
+async def test_list_tasks_with_status_filter(mock_list, mcp_server):
+    """Status filter is passed through to the DAO correctly."""
+    task = create_mock_task(status="pending")
+    mock_list.return_value = ([task], 1)
+
+    async with Client(mcp_server) as client:
+        request = ListTasksRequest(
+            filters=[{"col": "status", "opr": "eq", "value": "pending"}]
+        )
+        result = await client.call_tool("list_tasks", {"request": 
request.model_dump()})
+
+    data = json.loads(result.content[0].text)
+    assert len(data["tasks"]) == 1
+    assert data["tasks"][0]["status"] == "pending"

Review Comment:
   Fixed in 28461c7591 — added assertions on 
`mock_list.call_args.kwargs["column_operators"]` to confirm the status filter 
(col, opr, value) was forwarded correctly to the DAO.



-- 
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