You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by mi...@apache.org on 2026/08/18 18:50:44 UTC

(superset) 01/01: fix(mcp): match permalinks by uuid and keep identifier not-found errors

This is an automated email from the ASF dual-hosted git repository.

aminghadersohi pushed a commit to branch aminghadersohi/resolve-dashboard-permalinks
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 8a01ea6fdc04125cfcb96c7306f7963d9a0b556e
Author: Amin Ghadersohi <am...@gmail.com>
AuthorDate: Tue Aug 18 18:50:32 2026 +0000

    fix(mcp): match permalinks by uuid and keep identifier not-found errors
    
    CreateDashboardPermalinkCommand stores dashboardId as str(dashboard.uuid),
    so the int() comparison dropped shared state for virtually every real
    permalink. The permalink-only path now records that it selected the
    dashboard itself and skips re-verification, while the explicit
    identifier + permalink_key combination compares the reference against the
    dashboard id, uuid, and slug.
    
    A plain identifier that simply does not exist also no longer reports the
    permalink wording; its own not-found error is preserved and the permalink
    message is reserved for requests that had to resolve through a permalink.
    
    Co-Authored-By: Claude <no...@anthropic.com>
---
 superset/mcp_service/dashboard/permalink.py        | 36 ++++++----
 .../dashboard/tool/get_dashboard_info.py           | 11 +--
 .../dashboard/tool/get_dashboard_layout.py         | 11 ++-
 .../mcp_service/dashboard/test_permalink.py        | 52 ++++++++++++++
 .../dashboard/tool/test_dashboard_tools.py         | 82 ++++++++++++++++++++++
 .../dashboard/tool/test_get_dashboard_layout.py    | 56 +++++++++++++++
 6 files changed, 224 insertions(+), 24 deletions(-)

diff --git a/superset/mcp_service/dashboard/permalink.py b/superset/mcp_service/dashboard/permalink.py
index 429c8eb353e..c0b6a1b4546 100644
--- a/superset/mcp_service/dashboard/permalink.py
+++ b/superset/mcp_service/dashboard/permalink.py
@@ -47,7 +47,8 @@ class DashboardLookupResult(Generic[LookupResultT]):
     result: LookupResultT | None
     permalink_key: str | None = None
     permalink_value: DashboardPermalinkValue | None = None
-    permalink_error: bool = False
+    resolved_from_permalink: bool = False
+    """True when the dashboard itself was selected from the permalink."""
 
 
 @dataclass(frozen=True)
@@ -139,34 +140,43 @@ def lookup_dashboard_reference(
     reference = key or (identifier if isinstance(identifier, str) else None)
     resolved = get_dashboard_permalink(reference) if reference else None
     if resolved is None:
-        return DashboardLookupResult(
-            result=result,
-            permalink_key=reference,
-            permalink_error=True,
-        )
+        return DashboardLookupResult(result=result, permalink_key=reference)
     key, value = resolved
     return DashboardLookupResult(
         result=lookup(value["dashboardId"]),
         permalink_key=key,
         permalink_value=value,
+        resolved_from_permalink=True,
     )
 
 
 def get_matching_dashboard_permalink_state(
     lookup_result: DashboardLookupResult[LookupResultT],
     dashboard_id: int | None,
+    dashboard_uuid: str | None = None,
+    dashboard_slug: str | None = None,
 ) -> DashboardPermalinkState | None:
-    """Return sanitized permalink state when it belongs to ``dashboard_id``."""
+    """Return sanitized permalink state when it belongs to the dashboard.
+
+    ``CreateDashboardPermalinkCommand`` stores ``dashboardId`` as the dashboard
+    UUID string, while older permalinks may hold a numeric ID or a slug, so the
+    reference is compared against every identifier the dashboard answers to.
+    """
     value = lookup_result.permalink_value
     key = lookup_result.permalink_key
     if value is None or key is None:
         return None
-    try:
-        permalink_dashboard_id = int(value["dashboardId"])
-    except (KeyError, TypeError, ValueError):
-        return None
-    if permalink_dashboard_id != dashboard_id:
-        return None
+    if not lookup_result.resolved_from_permalink:
+        # The identifier selected the dashboard, so the permalink only
+        # contributes state when it points at that same dashboard.
+        reference = value.get("dashboardId")
+        known_identifiers = {
+            str(candidate)
+            for candidate in (dashboard_id, dashboard_uuid, dashboard_slug)
+            if candidate is not None
+        }
+        if reference is None or str(reference) not in known_identifiers:
+            return None
 
     raw_state = value.get("state")
     state: dict[str, object] = dict(raw_state) if isinstance(raw_state, dict) else {}
diff --git a/superset/mcp_service/dashboard/tool/get_dashboard_info.py b/superset/mcp_service/dashboard/tool/get_dashboard_info.py
index d29bcfba36f..9375bfd39ae 100644
--- a/superset/mcp_service/dashboard/tool/get_dashboard_info.py
+++ b/superset/mcp_service/dashboard/tool/get_dashboard_info.py
@@ -76,14 +76,13 @@ def _lookup_dashboard(
         is_found=lambda result: isinstance(result, DashboardInfo),
     )
     result = lookup_result.result
-    if result is None or lookup_result.permalink_error:
-        error_type = (
-            "permalink_not_found" if request.identifier is None else "not_found"
-        )
+    if result is None:
+        # Only reachable when the dashboard had to come from a permalink, so the
+        # identifier's own "not found" error (when there is one) is preserved.
         result = DashboardError.create(
             "Dashboard permalink could not be resolved. It may be invalid or "
             "expired; ask for a fresh shared dashboard link.",
-            error_type,
+            "permalink_not_found",
         )
     return result, lookup_result
 
@@ -183,6 +182,8 @@ async def get_dashboard_info(
                     permalink_state = get_matching_dashboard_permalink_state(
                         lookup_result,
                         result.id,
+                        result.uuid,
+                        result.slug,
                     )
                     if permalink_state is None:
                         await ctx.warning(
diff --git a/superset/mcp_service/dashboard/tool/get_dashboard_layout.py b/superset/mcp_service/dashboard/tool/get_dashboard_layout.py
index 1e8ac681eb6..60b855500f2 100644
--- a/superset/mcp_service/dashboard/tool/get_dashboard_layout.py
+++ b/superset/mcp_service/dashboard/tool/get_dashboard_layout.py
@@ -101,20 +101,19 @@ async def get_dashboard_layout(
                 is_found=lambda value: isinstance(value, DashboardLayout),
             )
             result = lookup_result.result
-            if result is None or lookup_result.permalink_error:
-                error_type = (
-                    "permalink_not_found" if request.identifier is None else "not_found"
-                )
+            if result is None:
+                # Only reachable when the dashboard had to come from a permalink,
+                # so an identifier's own "not found" error is preserved below.
                 return DashboardError.create(
                     "Dashboard permalink could not be resolved. It may be invalid "
                     "or expired; ask for a fresh shared dashboard link.",
-                    error_type,
+                    "permalink_not_found",
                 )
 
         if isinstance(result, DashboardLayout):
             if lookup_result.permalink_value:
                 permalink_state = get_matching_dashboard_permalink_state(
-                    lookup_result, result.id
+                    lookup_result, result.id, result.uuid
                 )
                 if permalink_state:
                     payload = result.model_dump(mode="python")
diff --git a/tests/unit_tests/mcp_service/dashboard/test_permalink.py b/tests/unit_tests/mcp_service/dashboard/test_permalink.py
index 6974ea00eeb..7d300fc3c74 100644
--- a/tests/unit_tests/mcp_service/dashboard/test_permalink.py
+++ b/tests/unit_tests/mcp_service/dashboard/test_permalink.py
@@ -24,8 +24,10 @@ from flask import g
 
 from superset.commands.dashboard.exceptions import DashboardAccessDeniedError
 from superset.mcp_service.dashboard.permalink import (
+    DashboardLookupResult,
     extract_dashboard_permalink_key,
     get_dashboard_permalink,
+    get_matching_dashboard_permalink_state,
     refresh_request_user_for_permalink_access,
 )
 
@@ -115,3 +117,53 @@ def test_refresh_request_user_for_permalink_access_skips_unresolvable_user(
         assert g.user is current_user
 
     mock_load.assert_not_called()
+
+
+@pytest.mark.parametrize(
+    ("reference", "expected_match"),
+    [
+        # CreateDashboardPermalinkCommand stores str(dashboard.uuid).
+        ("3f1a2b6c-9d4e-4f80-9c2a-7b1d5e6f8a90", True),
+        # Legacy permalinks may hold the numeric id or the slug.
+        ("42", True),
+        ("sales-dashboard", True),
+        ("99", False),
+        ("00000000-0000-0000-0000-000000000000", False),
+    ],
+)
+def test_get_matching_dashboard_permalink_state_accepts_every_identifier(
+    app, reference: str, expected_match: bool
+) -> None:
+    lookup_result = DashboardLookupResult(
+        result=object(),
+        permalink_key="key-1",
+        permalink_value={"dashboardId": reference, "state": {"activeTabs": ["TAB-A"]}},
+    )
+    with app.test_request_context("/mcp"):
+        state = get_matching_dashboard_permalink_state(
+            lookup_result,
+            42,
+            "3f1a2b6c-9d4e-4f80-9c2a-7b1d5e6f8a90",
+            "sales-dashboard",
+        )
+
+    assert (state is not None) is expected_match
+
+
+def test_get_matching_dashboard_permalink_state_skips_check_when_permalink_resolved(
+    app,
+) -> None:
+    """The permalink-only path already selected the dashboard from the permalink,
+    so its state is never re-verified against the resolved identifiers.
+    """
+    lookup_result = DashboardLookupResult(
+        result=object(),
+        permalink_key="key-1",
+        permalink_value={"dashboardId": "whatever", "state": {"activeTabs": ["TAB-A"]}},
+        resolved_from_permalink=True,
+    )
+    with app.test_request_context("/mcp"):
+        state = get_matching_dashboard_permalink_state(lookup_result, 42)
+
+    assert state is not None
+    assert state.key == "key-1"
diff --git a/tests/unit_tests/mcp_service/dashboard/tool/test_dashboard_tools.py b/tests/unit_tests/mcp_service/dashboard/tool/test_dashboard_tools.py
index 005ebb2b5cb..e7e2c14238d 100644
--- a/tests/unit_tests/mcp_service/dashboard/tool/test_dashboard_tools.py
+++ b/tests/unit_tests/mcp_service/dashboard/tool/test_dashboard_tools.py
@@ -29,6 +29,7 @@ from fastmcp.exceptions import ToolError
 
 from superset.mcp_service.app import mcp
 from superset.mcp_service.dashboard.schemas import (
+    DashboardError,
     DashboardInfo,
     ListDashboardsRequest,
 )
@@ -640,6 +641,87 @@ async def test_get_dashboard_info_identifier_takes_precedence_over_permalink(
     mock_run_tool.assert_called_once_with(10)
 
 
+@patch("superset.mcp_service.mcp_core.ModelGetInfoCore.run_tool")
+@patch("superset.mcp_service.dashboard.permalink.get_dashboard_permalink")
+@pytest.mark.asyncio
+async def test_get_dashboard_info_permalink_with_uuid_dashboard_id(
+    mock_permalink, mock_run_tool, mcp_server
+):
+    """CreateDashboardPermalinkCommand stores dashboardId as the dashboard UUID,
+    so an explicit identifier plus that permalink must still yield filter state.
+    """
+    dashboard_uuid = "3f1a2b6c-9d4e-4f80-9c2a-7b1d5e6f8a90"
+    mock_permalink.return_value = (
+        "uuid-key",
+        {"dashboardId": dashboard_uuid, "state": {"activeTabs": ["TAB-A"]}},
+    )
+    mock_run_tool.return_value = DashboardInfo(
+        id=42, dashboard_title="Sales Dashboard", uuid=dashboard_uuid
+    )
+
+    async with Client(mcp_server) as client:
+        result = await client.call_tool(
+            "get_dashboard_info",
+            {"request": {"identifier": 42, "permalink_key": "uuid-key"}},
+        )
+
+    assert result.data["id"] == 42
+    assert result.data["is_permalink_state"] is True
+    assert result.data["permalink_key"] == "uuid-key"
+    assert result.data["filter_state"]["activeTabs"] == [_wrapped("TAB-A")]
+
+
+@patch("superset.mcp_service.mcp_core.ModelGetInfoCore.run_tool")
+@patch("superset.mcp_service.dashboard.permalink.get_dashboard_permalink")
+@pytest.mark.asyncio
+async def test_get_dashboard_info_permalink_with_slug_dashboard_id(
+    mock_permalink, mock_run_tool, mcp_server
+):
+    """Pre-3.1 permalinks can carry a slug in dashboardId."""
+    mock_permalink.return_value = (
+        "slug-key",
+        {"dashboardId": "sales-dashboard", "state": {"activeTabs": ["TAB-A"]}},
+    )
+    mock_run_tool.return_value = DashboardInfo(
+        id=42, dashboard_title="Sales Dashboard", slug="sales-dashboard"
+    )
+
+    async with Client(mcp_server) as client:
+        result = await client.call_tool(
+            "get_dashboard_info",
+            {"request": {"identifier": 42, "permalink_key": "slug-key"}},
+        )
+
+    assert result.data["is_permalink_state"] is True
+    assert result.data["filter_state"]["activeTabs"] == [_wrapped("TAB-A")]
+
+
+@patch("superset.mcp_service.mcp_core.ModelGetInfoCore.run_tool")
+@patch(
+    "superset.mcp_service.dashboard.permalink.get_dashboard_permalink",
+    return_value=None,
+)
+@pytest.mark.asyncio
+async def test_get_dashboard_info_unknown_slug_keeps_not_found_error(
+    mock_permalink, mock_run_tool, mcp_server
+):
+    """A plain slug typo keeps its own not-found error instead of asking the
+    user for a shared link they never mentioned.
+    """
+    mock_run_tool.return_value = DashboardError.create(
+        "DashboardInfo with identifier 'sales-dashbord' not found", "not_found"
+    )
+
+    async with Client(mcp_server) as client:
+        result = await client.call_tool(
+            "get_dashboard_info", {"request": {"identifier": "sales-dashbord"}}
+        )
+
+    assert result.data["error_type"] == "not_found"
+    assert "sales-dashbord" in result.data["error"]
+    assert "fresh shared dashboard link" not in result.data["error"]
+
+
 @patch("superset.daos.dashboard.DashboardDAO.find_by_id")
 @pytest.mark.asyncio
 async def test_get_dashboard_info_not_found(mock_info, mcp_server):
diff --git a/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_layout.py b/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_layout.py
index b2c1bd7faac..3bb48be645e 100644
--- a/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_layout.py
+++ b/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_layout.py
@@ -344,6 +344,62 @@ async def test_get_dashboard_layout_identifier_takes_precedence_over_permalink(
     mock_find.assert_called_once_with(10, query_options=None)
 
 
+@patch("superset.daos.dashboard.DashboardDAO.find_by_id")
+@patch("superset.mcp_service.dashboard.permalink.get_dashboard_permalink")
+@pytest.mark.asyncio
+async def test_get_dashboard_layout_permalink_with_uuid_dashboard_id(
+    mock_permalink, mock_find, mcp_server
+):
+    """CreateDashboardPermalinkCommand stores dashboardId as the dashboard UUID,
+    so an explicit identifier plus that permalink must still yield filter state.
+    """
+    dashboard_uuid = "3f1a2b6c-9d4e-4f80-9c2a-7b1d5e6f8a90"
+    mock_permalink.return_value = (
+        "uuid-key",
+        {"dashboardId": dashboard_uuid, "state": {"activeTabs": ["TAB-2"]}},
+    )
+    mock_find.return_value = _build_dashboard_mock(
+        dashboard_id=42, uuid=dashboard_uuid, position_json=_tabbed_layout()
+    )
+
+    async with Client(mcp_server) as client:
+        result = await client.call_tool(
+            "get_dashboard_layout",
+            {"request": {"identifier": 42, "permalink_key": "uuid-key"}},
+        )
+        data = json.loads(result.content[0].text)
+
+    assert data["id"] == 42
+    assert data["is_permalink_state"] is True
+    assert data["permalink_key"] == "uuid-key"
+    assert data["filter_state"]["activeTabs"] == [_wrapped("TAB-2")]
+
+
+@patch("superset.daos.dashboard.DashboardDAO.find_by_id")
+@patch(
+    "superset.mcp_service.dashboard.permalink.get_dashboard_permalink",
+    return_value=None,
+)
+@pytest.mark.asyncio
+async def test_get_dashboard_layout_unknown_slug_keeps_not_found_error(
+    mock_permalink, mock_find, mcp_server
+):
+    """A plain slug typo keeps its own not-found error instead of asking the
+    user for a shared link they never mentioned.
+    """
+    mock_find.return_value = None
+
+    async with Client(mcp_server) as client:
+        result = await client.call_tool(
+            "get_dashboard_layout", {"request": {"identifier": "sales-dashbord"}}
+        )
+        data = json.loads(result.content[0].text)
+
+    assert data["error_type"] == "not_found"
+    assert "sales-dashbord" in data["error"]
+    assert "fresh shared dashboard link" not in data["error"]
+
+
 def test_extract_layout_handles_invalid_json():
     tabs, charts = _extract_layout_from_position("{ not json")
     assert tabs == []