-
Notifications
You must be signed in to change notification settings - Fork 17.9k
feat(mcp): add list and get tools for action log and tasks #40304
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9a6c927
feat(mcp): add list and get tools for action log and tasks
aminghadersohi ef38144
fix(mcp): convert dttm cutoff to ISO string so filters_applied validates
aminghadersohi 6a26ba7
fix(mcp): field filtering and search for action-log and task list tools
aminghadersohi 59b0914
fix(mcp): add task_key/task_name to TaskInfo and strengthen test cove…
aminghadersohi 0f926b6
fix(mcp): use ActionLogFilter for injected default dttm filter
aminghadersohi 0f9b0ee
ci: trigger CI for fix
aminghadersohi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| # 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,243 @@ | ||
| # 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. | ||
|
|
||
| """Pydantic schemas for action-log MCP tools.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from datetime import datetime | ||
| from typing import Annotated, Any, Literal | ||
|
|
||
| from pydantic import ( | ||
| BaseModel, | ||
| ConfigDict, | ||
| Field, | ||
| field_validator, | ||
| model_serializer, | ||
| model_validator, | ||
| PositiveInt, | ||
| ) | ||
|
|
||
| from superset.daos.base import ColumnOperator, ColumnOperatorEnum | ||
| from superset.mcp_service.constants import DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE | ||
| from superset.mcp_service.system.schemas import PaginationInfo | ||
| from superset.mcp_service.utils.schema_utils import ( | ||
| parse_json_or_list, | ||
| parse_json_or_model_list, | ||
| ) | ||
|
|
||
| DEFAULT_LOG_COLUMNS: list[str] = ["id", "action", "user_id", "dttm"] | ||
| ALL_LOG_COLUMNS: list[str] = [ | ||
| "id", | ||
| "action", | ||
| "user_id", | ||
| "dttm", | ||
| "dashboard_id", | ||
| "slice_id", | ||
| "json", | ||
| ] | ||
| LOG_SORTABLE_COLUMNS: list[str] = ["id", "dttm"] | ||
|
|
||
|
|
||
| class ActionLogFilter(ColumnOperator): | ||
| """Filter object for action-log listing. | ||
|
|
||
| col: Column to filter on. | ||
| opr: Operator to use. | ||
| value: Value to filter by. | ||
| """ | ||
|
|
||
| col: Literal["action", "user_id", "dashboard_id", "slice_id", "dttm"] = Field( | ||
| ..., | ||
| description="Column to filter on.", | ||
| ) | ||
| opr: ColumnOperatorEnum = Field(..., description="Operator to use.") | ||
| value: str | int | float | bool | list[str | int | float | bool] = Field( | ||
| ..., description="Value to filter by" | ||
| ) | ||
|
|
||
|
|
||
| class ActionLogInfo(BaseModel): | ||
| id: int | None = Field(None, description="Log entry ID") | ||
| action: str | None = Field(None, description="Action name") | ||
| user_id: int | None = Field( | ||
| None, description="ID of the user who performed the action" | ||
| ) | ||
| dttm: str | datetime | None = Field(None, description="Timestamp of the action") | ||
| dashboard_id: int | None = Field(None, description="Associated dashboard ID") | ||
| slice_id: int | None = Field(None, description="Associated chart/slice ID") | ||
| json: str | None = Field(None, description="JSON payload of the action") | ||
|
|
||
| model_config = ConfigDict( | ||
| from_attributes=True, | ||
| ser_json_timedelta="iso8601", | ||
| populate_by_name=True, | ||
| ) | ||
|
|
||
| def model_post_init(self, __context: Any) -> None: | ||
| if isinstance(self.dttm, datetime) and self.dttm.tzinfo is None: | ||
| from datetime import timezone | ||
|
|
||
| object.__setattr__(self, "dttm", self.dttm.replace(tzinfo=timezone.utc)) | ||
|
|
||
| @model_serializer(mode="wrap") | ||
| def _filter_fields_by_context(self, serializer: Any, info: Any) -> dict[str, Any]: | ||
| data = serializer(self) | ||
| if info.context and isinstance(info.context, dict): | ||
| select_columns = info.context.get("select_columns") | ||
| if select_columns: | ||
| requested_fields = set(select_columns) | ||
| return {k: v for k, v in data.items() if k in requested_fields} | ||
| return data | ||
|
|
||
|
|
||
| class ActionLogList(BaseModel): | ||
| action_logs: list[ActionLogInfo] | ||
| count: int | ||
| total_count: int | ||
| page: int | ||
| page_size: int | ||
| total_pages: int | ||
| has_previous: bool | ||
| has_next: bool | ||
| columns_requested: list[str] = Field(default_factory=list) | ||
| columns_loaded: list[str] = Field(default_factory=list) | ||
| columns_available: list[str] = Field(default_factory=list) | ||
| sortable_columns: list[str] = Field(default_factory=list) | ||
| filters_applied: list[ActionLogFilter] = Field(default_factory=list) | ||
| pagination: PaginationInfo | None = None | ||
| timestamp: datetime | None = None | ||
| model_config = ConfigDict(ser_json_timedelta="iso8601") | ||
|
|
||
|
|
||
| class ListActionLogsRequest(BaseModel): | ||
| """Request schema for list_action_logs.""" | ||
|
|
||
| filters: Annotated[ | ||
| list[ActionLogFilter], | ||
| Field( | ||
| default_factory=list, | ||
| description=( | ||
| "List of filter objects (col, opr, value). " | ||
| "Filter columns: action, user_id, dashboard_id, slice_id, dttm. " | ||
| "Cannot be used with 'search'." | ||
| ), | ||
| ), | ||
| ] | ||
| select_columns: Annotated[ | ||
| list[str], | ||
| Field( | ||
| default_factory=list, | ||
| description="Columns to return. Defaults to common columns.", | ||
| ), | ||
| ] | ||
| search: Annotated[ | ||
| str | None, | ||
| Field( | ||
| default=None, | ||
| description=( | ||
| "Text search string matched against action. " | ||
| "Cannot be used together with 'filters'." | ||
| ), | ||
| ), | ||
| ] | ||
| order_column: Annotated[ | ||
| str | None, | ||
| Field(default=None, description="Column to sort by (default: dttm)"), | ||
| ] | ||
| order_direction: Annotated[ | ||
| Literal["asc", "desc"], | ||
| Field(default="desc", description="Sort direction ('asc' or 'desc')"), | ||
| ] | ||
| page: Annotated[ | ||
| PositiveInt, | ||
| Field(default=1, description="Page number (1-based)"), | ||
| ] | ||
| page_size: Annotated[ | ||
| int, | ||
| Field( | ||
| default=DEFAULT_PAGE_SIZE, | ||
| gt=0, | ||
| le=MAX_PAGE_SIZE, | ||
| description=f"Items per page (max {MAX_PAGE_SIZE})", | ||
| ), | ||
| ] | ||
|
|
||
| @field_validator("filters", mode="before") | ||
| @classmethod | ||
| def parse_filters(cls, v: Any) -> list[ActionLogFilter]: | ||
| return parse_json_or_model_list(v, ActionLogFilter, "filters") | ||
|
|
||
| @field_validator("select_columns", mode="before") | ||
| @classmethod | ||
| def parse_columns(cls, v: Any) -> list[str]: | ||
| return parse_json_or_list(v, "select_columns") | ||
|
|
||
| @model_validator(mode="after") | ||
| def validate_search_and_filters(self) -> "ListActionLogsRequest": | ||
| if self.search and self.filters: | ||
| raise ValueError( | ||
| "Cannot use both 'search' and 'filters' simultaneously. " | ||
| "Use 'search' for text matching on action, or 'filters' for " | ||
| "column-based filtering, but not both." | ||
| ) | ||
| return self | ||
|
|
||
|
|
||
| class ActionLogError(BaseModel): | ||
| error: str = Field(..., description="Error message") | ||
| error_type: str = Field(..., description="Error type") | ||
| timestamp: str | datetime | None = Field(None, description="Error timestamp") | ||
| model_config = ConfigDict(ser_json_timedelta="iso8601") | ||
|
|
||
| @classmethod | ||
| def create(cls, error: str, error_type: str) -> "ActionLogError": | ||
| from datetime import timezone | ||
|
|
||
| return cls( | ||
| error=error, | ||
| error_type=error_type, | ||
| timestamp=datetime.now(timezone.utc), | ||
| ) | ||
|
|
||
|
|
||
| class GetActionLogInfoRequest(BaseModel): | ||
| """Request schema for get_action_log_info (ID-only lookup).""" | ||
|
|
||
| identifier: Annotated[ | ||
| int, | ||
| Field(description="Log entry ID (integer)"), | ||
| ] | ||
|
|
||
|
|
||
| def serialize_action_log_object(log: Any) -> ActionLogInfo | None: | ||
| if not log: | ||
| return None | ||
| dttm = getattr(log, "dttm", None) | ||
| if isinstance(dttm, datetime) and dttm.tzinfo is None: | ||
| from datetime import timezone | ||
|
|
||
| dttm = dttm.replace(tzinfo=timezone.utc) | ||
| return ActionLogInfo( | ||
| id=getattr(log, "id", None), | ||
| action=getattr(log, "action", None), | ||
| user_id=getattr(log, "user_id", None), | ||
| dttm=dttm, | ||
| dashboard_id=getattr(log, "dashboard_id", None), | ||
| slice_id=getattr(log, "slice_id", None), | ||
| json=getattr(log, "json", None), | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| # 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. | ||
|
|
||
| from .get_action_log_info import get_action_log_info | ||
| from .list_action_logs import list_action_logs | ||
|
|
||
| __all__ = [ | ||
| "list_action_logs", | ||
| "get_action_log_info", | ||
| ] |
97 changes: 97 additions & 0 deletions
97
superset/mcp_service/action_log/tool/get_action_log_info.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| # 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 action log info MCP tool.""" | ||
|
|
||
| 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.action_log.schemas import ( | ||
| ActionLogError, | ||
| ActionLogInfo, | ||
| GetActionLogInfoRequest, | ||
| serialize_action_log_object, | ||
| ) | ||
| from superset.mcp_service.mcp_core import ModelGetInfoCore | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| @tool( | ||
| tags=["discovery"], | ||
| class_permission_name="Log", | ||
| annotations=ToolAnnotations( | ||
| title="Get action log info", | ||
| readOnlyHint=True, | ||
| destructiveHint=False, | ||
| ), | ||
| ) | ||
| async def get_action_log_info( | ||
| request: GetActionLogInfoRequest, | ||
| ctx: Context, | ||
| ) -> ActionLogInfo | ActionLogError: | ||
| """Get a single action log entry by its integer ID. | ||
|
|
||
| Returns the action, user_id, timestamp (dttm), dashboard_id, slice_id, | ||
| and JSON payload for the specified log record. | ||
|
|
||
| ADMIN-ONLY: This tool requires admin privileges. | ||
|
|
||
| Use list_action_logs to discover log IDs. | ||
| """ | ||
| await ctx.info("Retrieving action log: identifier=%s" % (request.identifier,)) | ||
|
|
||
| try: | ||
| from superset.daos.log import LogDAO | ||
|
|
||
| with event_logger.log_context(action="mcp.get_action_log_info.lookup"): | ||
| get_tool = ModelGetInfoCore( | ||
| dao_class=LogDAO, | ||
| output_schema=ActionLogInfo, | ||
| error_schema=ActionLogError, | ||
| serializer=serialize_action_log_object, | ||
| supports_slug=False, | ||
| logger=logger, | ||
| ) | ||
| result = get_tool.run_tool(request.identifier) | ||
|
|
||
| if isinstance(result, ActionLogInfo): | ||
| await ctx.info( | ||
| "Action log retrieved: id=%s, action=%s" % (result.id, result.action) | ||
| ) | ||
| else: | ||
| await ctx.warning( | ||
| "Action log retrieval failed: error_type=%s, error=%s" | ||
| % (result.error_type, result.error) | ||
| ) | ||
|
|
||
| return result | ||
|
|
||
| except Exception as e: | ||
| await ctx.error( | ||
| "Action log retrieval failed: identifier=%s, error=%s, error_type=%s" | ||
| % (request.identifier, str(e), type(e).__name__) | ||
| ) | ||
| return ActionLogError( | ||
| error=f"Failed to get action log info: {str(e)}", | ||
| error_type="InternalError", | ||
| timestamp=datetime.now(timezone.utc), | ||
| ) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ActionLogError is missing the sanitize_for_llm_context validator present in all other error schemas. Error messages could contain unsanitized content when exposed to LLM context. Add the validator decorator to match DashboardError (line 123-127), ChartError (line 188-191), and DatasetError (line 301-304).
Code suggestion
Code Review Run #8033ab
Should Bito avoid suggestions like this for future reviews? (Manage Rules)