This is an automated email from the ASF dual-hosted git repository. alexandrusoare pushed a commit to branch alexandrusoare/feat/canvas-instrumentation in repository https://gitbox.apache.org/repos/asf/superset.git
commit 31a62cc0417faaf0a8fd7fa72418fbcf67e58092 Author: alexandrusoare <[email protected]> AuthorDate: Tue Nov 17 17:27:25 2026 +0200 feat(canvas): correlate MCP canvas tool calls to the canvas they act on MCP already records a rich audit row per tool call -- call id, tool, agent, sanitized params, success, error type, duration -- and counts outcomes per tool. It just had no notion of a canvas: `grep -c canvas middleware.py` returned zero, so the eleven canvas tools were indistinguishable from any other call once logged. Resolve the canvas from two places. Tools that take a `canvas_id` argument are read from params, but only when the value already is an integer: a canvas is addressable by uuid or slug too, and resolving those would mean a database round trip on the event loop for every call. The response covers the rest, and for the draft tools it is the only possible source rather than a refinement. `apply_canvas_draft_ops`, `commit_canvas_draft`, `get_canvas_draft` and `delete_canvas_draft` take an opaque token and nothing else, and that token is redacted before logging -- correctly -- so without reading the response their calls could never be attributed at all. `create_canvas` needs it for the usual reason: the id does not exist until the call succeeds. Reading the response is gated on the tool being one that returns a canvas. The gate is load-bearing twice over. `GetCanvasResponse` and `CanvasWriteResponse` expose the id as a bare `id`, which would collide with every other tool's `id`; and the widget tools, though permissioned on Canvas, answer about widgets, so their bare `id` is a widget's. Only the integer is read, never `url` -- a draft response's url ends in `#draft=<token>`. Metrics stay keyed by tool name. Adding a canvas dimension would multiply the series by the number of canvases, which is the unbounded-cardinality failure `_resolve_metric_tool_name` already exists to prevent; per-canvas analysis is what the `logs.canvas_id` column is for. Also add `mcp_call_id` to the `mcp_tool_error` row. It reached the error hook but not the audit row, so a failure could not be joined back to the call that produced it -- which would have left the new column null on exactly the rows most worth querying. --- superset/mcp_service/canvas/telemetry.py | 99 ++++++++++++++++++ superset/mcp_service/middleware.py | 64 ++++++++++-- .../mcp_service/canvas/test_telemetry.py | 114 +++++++++++++++++++++ 3 files changed, 271 insertions(+), 6 deletions(-) diff --git a/superset/mcp_service/canvas/telemetry.py b/superset/mcp_service/canvas/telemetry.py new file mode 100644 index 00000000000..d195d9a78b5 --- /dev/null +++ b/superset/mcp_service/canvas/telemetry.py @@ -0,0 +1,99 @@ +# 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. +"""Resolving the canvas an MCP tool call acted on, for the audit log. + +A leaf module on purpose: ``middleware.py`` must not import +``canvas.tool.__init__``, which would pull every canvas tool into the +middleware's import graph. The names are therefore repeated here and held in +step by a test rather than by an import. +""" + +from __future__ import annotations + +from typing import Any + +# The tools whose *response* describes a canvas. +# +# Deliberately not the same as "the tools permissioned on Canvas": the widget +# tools (``list_widget_types``, ``get_widget_control_schema``, +# ``get_widget_info``, ``list_widgets``) carry ``class_permission_name="Canvas"`` +# but answer about widgets, and their responses can hold a bare ``id`` that is a +# widget's. Reading that as a canvas id would attribute a call to a canvas that +# does not exist. +CANVAS_TOOL_NAMES: frozenset[str] = frozenset( + { + "apply_canvas_draft_ops", + "commit_canvas_draft", + "create_canvas", + "create_canvas_draft", + "delete_canvas_draft", + "get_canvas", + "get_canvas_data", + "get_canvas_draft", + "list_canvases", + "preview_widget", + "update_canvas", + } +) + + +def _as_int(value: Any) -> int | None: + """An id only when it already is one. + + A canvas is addressable by id, uuid or slug, and the tools type it + ``int | str``. Resolving a uuid or slug would mean a database round trip on + the event loop for every call, so a non-integer reference is left to the + response, which always carries the integer id. + """ + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, str) and value.isdigit(): + return int(value) + return None + + +def is_canvas_tool(tool_name: str | None) -> bool: + """Whether a tool's response may be read for a canvas id.""" + return tool_name in CANVAS_TOOL_NAMES + + +def canvas_id_from_params(params: Any) -> int | None: + """The canvas a tool was asked to act on, when it was named as an id.""" + if not isinstance(params, dict): + return None + return _as_int(params.get("canvas_id")) + + +def canvas_id_from_result(data: Any) -> int | None: + """The canvas a tool acted on, read from its response. + + This is the only source for the draft tools. ``apply_canvas_draft_ops``, + ``commit_canvas_draft``, ``get_canvas_draft`` and ``delete_canvas_draft`` + take nothing but an opaque draft token -- which is redacted before it is + logged, as it should be -- so without the response their calls cannot be + attributed at all. ``create_canvas`` needs it for the usual reason: the id + does not exist until the call succeeds. + + Only the integer id is read. A draft response's ``url`` ends in + ``#draft=<token>``, so reading any more of the body would move a live token + into the ``logs`` table. + """ + if not isinstance(data, dict): + return None + return _as_int(data.get("canvas_id")) or _as_int(data.get("id")) diff --git a/superset/mcp_service/middleware.py b/superset/mcp_service/middleware.py index 2310374b3b2..9eaf8930156 100644 --- a/superset/mcp_service/middleware.py +++ b/superset/mcp_service/middleware.py @@ -56,6 +56,11 @@ from superset.mcp_service.auth import ( MCPNoAuthSourceError, MCPPermissionDeniedError, ) +from superset.mcp_service.canvas.telemetry import ( + canvas_id_from_params, + canvas_id_from_result, + is_canvas_tool, +) from superset.mcp_service.constants import ( CONNECTION_ERROR_TYPES, DEFAULT_MAX_LIST_ITEMS, @@ -704,28 +709,50 @@ class LoggingMiddleware(Middleware): return params["name"] return None + def _extract_output_canvas_id( + self, tool_name: str | None, result: ToolResult + ) -> int | None: + """The canvas id in a canvas tool's response, if it carries one.""" + from superset.utils.json import loads as json_loads + + if not is_canvas_tool(tool_name): + return None + try: + data = json_loads(result.content[0].text) + except (AttributeError, IndexError, ValueError, TypeError): + return None + return canvas_id_from_result(data) + def _backfill_output_ids( self, success: bool, result: Any, dashboard_id: int | None, slice_id: int | None, - ) -> tuple[int | None, int | None]: + canvas_id: int | None = None, + tool_name: str | None = None, + ) -> tuple[int | None, int | None, int | None]: """Fill in missing ids from a create tool's response on success. Create-style tools (generate_chart, generate_dashboard) don't take the new object's ID as input, so it's missing from params. On a successful call, pull it from the response instead so retried creates are distinguishable. + + For canvases this is load-bearing rather than a refinement: the draft + tools take an opaque token and nothing else, so the response is the + only place their canvas is named. """ if not success or not isinstance(result, ToolResult): - return dashboard_id, slice_id + return dashboard_id, slice_id, canvas_id output_dashboard_id, output_slice_id = self._extract_output_ids(result) if dashboard_id is None: dashboard_id = output_dashboard_id if slice_id is None: slice_id = output_slice_id - return dashboard_id, slice_id + if canvas_id is None: + canvas_id = self._extract_output_canvas_id(tool_name, result) + return dashboard_id, slice_id, canvas_id @staticmethod def _build_call_tool_payload( @@ -738,6 +765,7 @@ class LoggingMiddleware(Middleware): dashboard_id: int | None, slice_id: int | None, dataset_id: int | None, + canvas_id: int | None, success: bool, mcp_tool: str | None, error_type: str | None, @@ -751,6 +779,7 @@ class LoggingMiddleware(Middleware): "dashboard_id": dashboard_id, "slice_id": slice_id, "dataset_id": dataset_id, + "canvas_id": canvas_id, "success": success, } if mcp_tool is not None: @@ -771,6 +800,7 @@ class LoggingMiddleware(Middleware): dashboard_id: int | None, slice_id: int | None, dataset_id: int | None, + canvas_id: int | None, params: Any, success: bool, error_type: str | None, @@ -778,8 +808,13 @@ class LoggingMiddleware(Middleware): start_time: float, ) -> None: duration_ms = int((time.time() - start_time) * 1000) - dashboard_id, slice_id = self._backfill_output_ids( - success, result, dashboard_id, slice_id + dashboard_id, slice_id, canvas_id = self._backfill_output_ids( + success, + result, + dashboard_id, + slice_id, + canvas_id, + mcp_tool or tool_name, ) payload = self._build_call_tool_payload( mcp_call_id=mcp_call_id, @@ -790,6 +825,7 @@ class LoggingMiddleware(Middleware): dashboard_id=dashboard_id, slice_id=slice_id, dataset_id=dataset_id, + canvas_id=canvas_id, success=success, mcp_tool=mcp_tool, error_type=error_type, @@ -802,6 +838,7 @@ class LoggingMiddleware(Middleware): dashboard_id=dashboard_id, duration_ms=duration_ms, slice_id=slice_id, + canvas_id=canvas_id, referrer=None, curated_payload=payload, ) @@ -921,6 +958,10 @@ class LoggingMiddleware(Middleware): ) tool_name = getattr(context.message, "name", None) mcp_tool = self._resolve_tool_name(tool_name, params) + # Only the tools that take a canvas id as an argument are covered here; + # the draft tools are named by a token alone and are resolved from the + # response instead (see _backfill_output_ids). + canvas_id = canvas_id_from_params(params) mcp_call_id = secrets.token_hex(16) _mcp_call_id_var.set(mcp_call_id) @@ -994,6 +1035,7 @@ class LoggingMiddleware(Middleware): dashboard_id=dashboard_id, slice_id=slice_id, dataset_id=dataset_id, + canvas_id=canvas_id, params=params, success=success, error_type=error_type, @@ -1385,7 +1427,13 @@ class GlobalErrorHandlerMiddleware(Middleware): exc_info=not is_user, ) - # Log to Superset's event system + # Log to Superset's event system. ``mcp_call_id`` is what ties this row + # to the ``mcp_tool_call`` row for the same call; without it a failure + # cannot be joined back to the call that produced it. + failed_call_id = _mcp_call_id_var.get(None) + failed_canvas_id = canvas_id_from_params( + getattr(context.message, "arguments", None) + ) try: await run_in_metadata_thread( event_logger.log, @@ -1394,9 +1442,12 @@ class GlobalErrorHandlerMiddleware(Middleware): dashboard_id=None, duration_ms=duration_ms, slice_id=None, + canvas_id=failed_canvas_id, referrer=None, curated_payload={ + "mcp_call_id": failed_call_id, "tool": tool_name, + "canvas_id": failed_canvas_id, "error_type": type(error).__name__, "error_message": sanitized_error, "method": context.method, @@ -1422,6 +1473,7 @@ class GlobalErrorHandlerMiddleware(Middleware): "tool_name": tool_name, "mcp_call_id": mcp_call_id, "user_id": user_id, + "canvas_id": failed_canvas_id, "error_type": type(error).__name__, "sanitized_message": sanitized_error, "duration_ms": duration_ms, diff --git a/tests/unit_tests/mcp_service/canvas/test_telemetry.py b/tests/unit_tests/mcp_service/canvas/test_telemetry.py new file mode 100644 index 00000000000..dc92fcb28fc --- /dev/null +++ b/tests/unit_tests/mcp_service/canvas/test_telemetry.py @@ -0,0 +1,114 @@ +# 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. +"""Resolving the canvas an MCP tool call acted on.""" + +from __future__ import annotations + +import pytest + +from superset.mcp_service.canvas.telemetry import ( + canvas_id_from_params, + canvas_id_from_result, + CANVAS_TOOL_NAMES, + is_canvas_tool, +) + + +def test_the_tool_names_match_the_registered_canvas_tools() -> None: + """``middleware.py`` cannot import the tool package without pulling every + canvas tool into its import graph, so the names are repeated. This is what + keeps the copy honest when a tool is added or renamed. + """ + from superset.mcp_service.canvas import tool + + assert CANVAS_TOOL_NAMES == set(tool.__all__) + + +def test_widget_tools_are_not_canvas_tools() -> None: + """They are permissioned on Canvas but answer about widgets, and their + responses can carry a bare ``id`` that is a widget's. Reading it as a + canvas id would attribute a call to a canvas that does not exist. + """ + for name in ( + "list_widget_types", + "get_widget_control_schema", + "get_widget_info", + "list_widgets", + ): + assert not is_canvas_tool(name) + + [email protected]( + "params,expected", + [ + ({"canvas_id": 7}, 7), + ({"canvas_id": "7"}, 7), + # A canvas is addressable by uuid or slug too; resolving those would + # mean a database round trip on the event loop, so the response is + # left to supply the id. + ({"canvas_id": "9f1c7e30-0000-0000-0000-000000000000"}, None), + ({"canvas_id": "exec-overview"}, None), + ({"canvas_id": None}, None), + ({}, None), + ({"canvas_id": True}, None), + ("not a mapping", None), + (None, None), + ], +) +def test_a_canvas_id_is_read_from_params_only_when_it_is_one( + params: object, expected: int | None +) -> None: + assert canvas_id_from_params(params) == expected + + [email protected]( + "data,expected", + [ + # The draft tools name their canvas only here. + ({"canvas_id": 42, "revision": 3}, 42), + # get_canvas / create_canvas / update_canvas expose it as ``id``. + ({"id": 42, "title": "Exec overview"}, 42), + ({"canvas_id": 42, "id": 99}, 42), + ({"id": None}, None), + ({}, None), + ([], None), + (None, None), + ], +) +def test_a_canvas_id_is_read_from_the_response( + data: object, expected: int | None +) -> None: + assert canvas_id_from_result(data) == expected + + +def test_only_an_integer_is_read_from_a_draft_response() -> None: + """A draft response's ``url`` ends in ``#draft=<token>``. Returning any + more of the body than the integer id would move a live token into ``logs``, + so the reader's return type is itself the guarantee: widening it to pass + through the body, the url, or the token fails here. + """ + data = { + "canvas_id": 42, + "url": "/canvas/42/#draft=s3cret-token", + "token": "s3cret-token", + } + + result = canvas_id_from_result(data) + + assert result == 42 + assert isinstance(result, int) + assert "s3cret-token" not in str(result)
