You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "aminghadersohi (via GitHub)" <gi...@apache.org> on 2026/09/29 13:01:19 UTC

[PR] feat(mcp): support tab-scoped dashboard layouts [superset]

aminghadersohi opened a new pull request, #44797:
URL: https://github.com/apache/superset/pull/44797

   ### SUMMARY
   
   Add opt-in scoping to `get_dashboard_layout` so large tabbed dashboards can be explored without exceeding the response-size guard:
   
   - `tabs_only=true` returns a compact tab tree with IDs, names, parents, zero-based depths, and distinct descendant chart counts, without chart IDs or positions.
   - `tab="<ID or exact title>"` returns one tab and its descendants with chart positions. IDs take precedence; ambiguous titles produce an actionable error. Both options can be combined.
   - Oversized-layout errors suggest these options through the existing tool-specific hint mechanism.
   
   Requests using only `identifier` or `permalink_key` retain their existing output. Permalink active-tab/filter state and full-dashboard ancestry remain unchanged. No response-size limits are increased.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   
   Not applicable (MCP response only). Previously, an oversized full layout was rejected without layout-specific recovery instructions. Callers can discover the tab tree and then retrieve a smaller subtree:
   
   ```json
   {"request": {"identifier": 123, "tabs_only": true}}
   ```
   
   ```json
   {"request": {"identifier": 123, "tab": "Overview"}}
   ```
   
   ### TESTING INSTRUCTIONS
   
   - Call `get_dashboard_layout` on a tabbed dashboard without new options and verify the existing full response.
   - Repeat with `tabs_only=true`; verify every tab appears with parent, depth, and chart count, and `charts` is empty.
   - Pass a tab ID or exact title; verify only that subtree's tabs and chart positions appear. Duplicate titles require an ID.
   - Repeat using a dashboard permalink and verify active-tab state is preserved, even when explicitly selecting a different tab.
   - Use a layout exceeding the configured response-size limit; verify the error suggests both new options.
   
   Automated validation:
   - Regression tests were run before implementation and failed for the new modes and oversized hint.
   - Generated fixture: 114 tabs and 404 charts; compact output stays below 25,000 serialized bytes and below one-third of a 20,000-token legacy bytes/4 estimate. The guard on master measures exact UTF-8 bytes.
   - Layout tests: 33 passed.
   - Full MCP unit suite (`pytest -q -n 4 tests/unit_tests/mcp_service`): 5,630 passed, 4 skipped.
   - Changed-file pre-commit checks, including mypy and pylint: passed.
   
   ### ADDITIONAL INFORMATION
   
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [x] Introduces new feature or API
   - [ ] Removes existing feature or API
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #44797:
URL: https://github.com/apache/superset/pull/44797#discussion_r4139068642


##########
superset/mcp_service/dashboard/tool/get_dashboard_layout.py:
##########
@@ -39,13 +39,135 @@
     dashboard_layout_serializer,
     DashboardError,
     DashboardLayout,
+    DashboardLayoutScope,
+    DashboardTab,
+    DashboardTabSummary,
     GetDashboardLayoutRequest,
 )
 from superset.mcp_service.mcp_core import ModelGetInfoCore
 
 logger = logging.getLogger(__name__)
 
 
+def _resolve_tab(
+    tabs: list[DashboardTab], selector: str
+) -> DashboardTab | DashboardError:
+    """Match a tab by ID first, then by exact title."""
+    if not tabs:
+        return DashboardError.create(
+            "This dashboard has no tabs. Omit tab to get the full layout.",
+            "tab_not_found",
+        )
+    matches = [tab for tab in tabs if tab.id == selector] or [
+        tab for tab in tabs if tab.name == selector
+    ]
+    if not matches:
+        return DashboardError.create(
+            "Tab not found. Use tabs_only=true to discover tab IDs and titles.",
+            "tab_not_found",
+        )
+    if len(matches) > 1:
+        return DashboardError.create(
+            "Multiple tabs have that title. Use tabs_only=true to discover "
+            "their IDs, then pass a unique tab ID.",
+            "ambiguous_tab",
+        )
+    return matches[0]
+
+
+def _subtree_ids(tab_id: str, children: dict[str | None, list[str]]) -> set[str]:
+    """Return a tab ID and the IDs of every tab nested under it."""
+    selected_ids: set[str] = set()
+    pending = [tab_id]
+    while pending:
+        current = pending.pop()
+        if current not in selected_ids:
+            selected_ids.add(current)
+            pending.extend(children.get(current, []))
+    return selected_ids
+
+
+def _tab_summaries(
+    tabs: list[DashboardTab], children: dict[str | None, list[str]]
+) -> list[DashboardTabSummary]:
+    """Summarize tabs with absolute depths from the full dashboard tree."""
+    # The parser only emits reachable tabs and assigns each tab a single
+    # enclosing parent, so walking from the top-level tabs reaches every tab.
+    depths: dict[str, int] = {}
+    stack = [(tab_id, 0) for tab_id in children.get(None, [])]
+    while stack:
+        tab_id, depth = stack.pop()
+        depths[tab_id] = depth
+        stack.extend((child, depth + 1) for child in children.get(tab_id, []))
+    return [
+        DashboardTabSummary(
+            id=tab.id,
+            name=tab.name,
+            parent_tab_id=tab.parent_tab_id,
+            depth=depths[tab.id],
+            chart_count=len(tab.chart_ids),
+        )
+        for tab in tabs
+    ]
+
+
+def _scope_layout(
+    layout: DashboardLayout, request: GetDashboardLayoutRequest
+) -> DashboardLayout | DashboardError:
+    """Project the parsed layout without changing permalink or ancestry context.
+
+    Scoping only ever removes tabs and chart placements from the parsed layout,
+    so a scoped response never contains a chart the full layout would not.
+    """
+    if not request.tabs_only and request.tab is None and not request.untabbed_only:
+        return layout
+
+    if request.untabbed_only:
+        return layout.model_copy(
+            update={
+                "tabs": [],
+                "charts": [chart for chart in layout.charts if chart.tab_id is None],
+                "scope": DashboardLayoutScope(untabbed_only=True),
+            }
+        )
+
+    tabs = layout.tabs
+    children: dict[str | None, list[str]] = {}
+    for tab in tabs:
+        children.setdefault(tab.parent_tab_id, []).append(tab.id)
+
+    selected_tab_id: str | None = None
+    selected_ids = {tab.id for tab in tabs}

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Dead selected_ids initializer</b></div>
   <div id="fix">
   
   `selected_ids` initialized here is never read: the only read, `chart.tab_id in selected_ids` (line 164), is reachable only when `request.tab is not None`, which rebinds it via `_subtree_ids` (line 146); the `tabs_only` path returns at line 151 without reading it. Dropping the initializer removes a misleading default.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #0086c7</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi merged PR #44797:
URL: https://github.com/apache/superset/pull/44797


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #44797:
URL: https://github.com/apache/superset/pull/44797#issuecomment-5890863125

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | c5f9f6ce174c90086c7b27fa5f1de8633b21944d |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6abbb6a167d6f300080e0031 |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-44797--superset-docs-preview.netlify.app](https://deploy-preview-44797--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQ0Nzk3LS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.i0xqJ2K2-aoeqd_8qo7yvOZiAnLAinfvSGrsniPykyQ)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   |<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#DcoxCoAwDADAv2S2GBGi-AOfkTStFdSG2kXEv9vthnvBSj6twgLQgRS-fGqOgWt_enPKd5LMRV1lcbfPtl9bmxrsyM-q7RKLCPFAk1IcEXHGgDgO8P0) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-44797--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44797:
URL: https://github.com/apache/superset/pull/44797#issuecomment-5900269261

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #44797:
URL: https://github.com/apache/superset/pull/44797#discussion_r4139227175


##########
superset/mcp_service/dashboard/tool/get_dashboard_layout.py:
##########
@@ -39,13 +39,135 @@
     dashboard_layout_serializer,
     DashboardError,
     DashboardLayout,
+    DashboardLayoutScope,
+    DashboardTab,
+    DashboardTabSummary,
     GetDashboardLayoutRequest,
 )
 from superset.mcp_service.mcp_core import ModelGetInfoCore
 
 logger = logging.getLogger(__name__)
 
 
+def _resolve_tab(
+    tabs: list[DashboardTab], selector: str
+) -> DashboardTab | DashboardError:
+    """Match a tab by ID first, then by exact title."""
+    if not tabs:
+        return DashboardError.create(
+            "This dashboard has no tabs. Omit tab to get the full layout.",
+            "tab_not_found",
+        )
+    matches = [tab for tab in tabs if tab.id == selector] or [
+        tab for tab in tabs if tab.name == selector
+    ]
+    if not matches:
+        return DashboardError.create(
+            "Tab not found. Use tabs_only=true to discover tab IDs and titles.",
+            "tab_not_found",
+        )
+    if len(matches) > 1:
+        return DashboardError.create(
+            "Multiple tabs have that title. Use tabs_only=true to discover "
+            "their IDs, then pass a unique tab ID.",
+            "ambiguous_tab",
+        )
+    return matches[0]
+
+
+def _subtree_ids(tab_id: str, children: dict[str | None, list[str]]) -> set[str]:
+    """Return a tab ID and the IDs of every tab nested under it."""
+    selected_ids: set[str] = set()
+    pending = [tab_id]
+    while pending:
+        current = pending.pop()
+        if current not in selected_ids:
+            selected_ids.add(current)
+            pending.extend(children.get(current, []))
+    return selected_ids
+
+
+def _tab_summaries(
+    tabs: list[DashboardTab], children: dict[str | None, list[str]]
+) -> list[DashboardTabSummary]:
+    """Summarize tabs with absolute depths from the full dashboard tree."""
+    # The parser only emits reachable tabs and assigns each tab a single
+    # enclosing parent, so walking from the top-level tabs reaches every tab.
+    depths: dict[str, int] = {}
+    stack = [(tab_id, 0) for tab_id in children.get(None, [])]
+    while stack:
+        tab_id, depth = stack.pop()
+        depths[tab_id] = depth
+        stack.extend((child, depth + 1) for child in children.get(tab_id, []))
+    return [
+        DashboardTabSummary(
+            id=tab.id,
+            name=tab.name,
+            parent_tab_id=tab.parent_tab_id,
+            depth=depths[tab.id],
+            chart_count=len(tab.chart_ids),
+        )
+        for tab in tabs
+    ]
+
+
+def _scope_layout(
+    layout: DashboardLayout, request: GetDashboardLayoutRequest
+) -> DashboardLayout | DashboardError:
+    """Project the parsed layout without changing permalink or ancestry context.
+
+    Scoping only ever removes tabs and chart placements from the parsed layout,
+    so a scoped response never contains a chart the full layout would not.
+    """
+    if not request.tabs_only and request.tab is None and not request.untabbed_only:
+        return layout
+
+    if request.untabbed_only:
+        return layout.model_copy(
+            update={
+                "tabs": [],
+                "charts": [chart for chart in layout.charts if chart.tab_id is None],
+                "scope": DashboardLayoutScope(untabbed_only=True),
+            }
+        )
+
+    tabs = layout.tabs
+    children: dict[str | None, list[str]] = {}
+    for tab in tabs:
+        children.setdefault(tab.parent_tab_id, []).append(tab.id)
+
+    selected_tab_id: str | None = None
+    selected_ids = {tab.id for tab in tabs}

Review Comment:
   Fixed in 6bff49560c2bbada483371a1bd8637eb38fd440b: removed the dead selected_ids initializer. The unscoped and untabbed-only paths return early, tabs-only returns before the chart filter, and selecting a tab assigns the subtree IDs before either use. Behavior and the response contract are unchanged.
   
   I also checked the additional DFS suggestion in review run #0086c7. It does not apply to this call path: _extract_layout_from_position starts at ROOT_ID, skips already-visited component IDs, and emits only reachable tabs. _record_tab derives parent_tab_id from the traversal ancestry, rather than reading a supplied parent_tab_id. Each emitted tab therefore has a single acyclic ancestry reaching a top-level tab, including when the raw component graph has cycles or detached nodes. _tab_summaries receives that parsed tree (with the full children mapping even for a scoped tab list), so the suggested cycle and missing-depth cases cannot arise here. No additional behavior change was made.
   
   Validation: 692 dashboard unit tests passed; all 11 applicable pre-commit hooks passed, including mypy, Ruff, and pylint.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44797:
URL: https://github.com/apache/superset/pull/44797#issuecomment-5943722830

   **Bito Automatic Review Skipped – PR Already Merged**<br/><br/>Bito scheduled an automatic review for this pull request, but the review was skipped because this PR was merged before the review could be run.<br/>No action is needed if you didn't intend to review it. To get a review, you can type `/review` in a comment and save it


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44797:
URL: https://github.com/apache/superset/pull/44797#issuecomment-5902725146

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #44797:
URL: https://github.com/apache/superset/pull/44797#issuecomment-5891798897

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/44797?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `25.00000%` with `39 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 57.28%. Comparing base ([`ce86ac9`](https://app.codecov.io/gh/apache/superset/commit/ce86ac9aefcbf4fa4448909f9c9fa818206bdf4a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`c5f9f6c`](https://app.codecov.io/gh/apache/superset/commit/c5f9f6ce174c90086c7b27fa5f1de8633b21944d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/44797?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...mcp\_service/dashboard/tool/get\_dashboard\_layout.py](https://app.codecov.io/gh/apache/superset/pull/44797?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fdashboard%2Ftool%2Fget_dashboard_layout.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvZGFzaGJvYXJkL3Rvb2wvZ2V0X2Rhc2hib2FyZF9sYXlvdXQucHk=) | 2.94% | [33 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/44797?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/mcp\_service/dashboard/schemas.py](https://app.codecov.io/gh/apache/superset/pull/44797?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fdashboard%2Fschemas.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvZGFzaGJvYXJkL3NjaGVtYXMucHk=) | 80.00% | [3 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/44797?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/mcp\_service/utils/response\_size\_utils.py](https://app.codecov.io/gh/apache/superset/pull/44797?src=pr&el=tree&filepath=superset%2Fmcp_service%2Futils%2Fresponse_size_utils.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvdXRpbHMvcmVzcG9uc2Vfc2l6ZV91dGlscy5weQ==) | 0.00% | [3 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/44797?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff             @@
   ##           master   #44797       +/-   ##
   ===========================================
   - Coverage   81.52%   57.28%   -24.25%     
   ===========================================
     Files        2974     2974               
     Lines      180288   180338       +50     
     Branches    41741    41752       +11     
   ===========================================
   - Hits       146980   103301    -43679     
   - Misses      30585    76030    +45445     
   + Partials     2723     1007     -1716     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/44797/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [hive](https://app.codecov.io/gh/apache/superset/pull/44797/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `36.69% <25.00%> (-0.01%)` | :arrow_down: |
   | [mysql](https://app.codecov.io/gh/apache/superset/pull/44797/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [postgres](https://app.codecov.io/gh/apache/superset/pull/44797/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/44797/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `38.62% <25.00%> (-0.01%)` | :arrow_down: |
   | [python](https://app.codecov.io/gh/apache/superset/pull/44797/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `38.66% <25.00%> (-46.99%)` | :arrow_down: |
   | [sqlite](https://app.codecov.io/gh/apache/superset/pull/44797/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [unit](https://app.codecov.io/gh/apache/superset/pull/44797/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/44797?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #44797:
URL: https://github.com/apache/superset/pull/44797#issuecomment-5902705143

   ### Acceptance at 892fc24aad
   
   **1. 100+ tabs / 400 charts: `tabs_only` fits under the guard, and `tab` returns that tab's charts: PASS**
   Test setup: a real SQLite metadata DB with a 114-tab dashboard (3 nesting levels) and 404 charts, 44 of them in rows above the tabs. The tool was called through the FastMCP client with `ResponseSizeGuardMiddleware` set to `max_bytes=40000`.
   - Full layout: 71,797 bytes, rejected by the guard (as expected).
   - `tabs_only=true`: 10,713 bytes (about 2.7k tokens at bytes/4). `tab_tree` has 114 entries at depths 0–2, and each top-level tab has `chart_count=60`. `tabs` and `charts` are empty.
   - `tab="TAB-t2m1"` (nested ID): 3,548 bytes, 6 tabs, 20 charts, all inside that subtree.
   - `tab="Top 3"` (title): 10,330 bytes, 19 tabs, 60 charts, `scope.tab_id="TAB-t3"`.
   - `tab="TAB-t1", tabs_only=true`: 2,042 bytes, 19-entry `tab_tree`.
   - `untabbed_only=true`: 44 charts, all with `tab_id=null`.
   - A duplicated title returns `ambiguous_tab`.
   
   **2. Callers passing only `identifier` get the same output as before: PASS (additive only)**
   I ran the same fixture at the merge-base and at head, with the guard disabled, using both an ID and a slug. Every field from the merge-base output is identical at head: 114 tabs and 404 charts. Head adds three fields: `tab_tree: []`, `untabbed_chart_count: 44` and `scope: null`. No fields were removed. The guarded full-layout error at the merge-base gave no recovery steps. At head it lists `tabs_only`, then `tab` (nested ID), then `untabbed_only` (44 distinct charts).
   
   **3. Unit tests cover both modes and the oversized-full-layout hint: PASS**
   - `pytest tests/unit_tests/mcp_service/dashboard/`: 692 passed. This includes `test_layout_tabs_only_large_tree`, `test_layout_tab_filter_large_tree`, `test_layout_default_response_unchanged`, `test_layout_oversized_hint_follows_scope`, `test_layout_oversized_hint_without_payload` and `test_layout_oversized_guard_hint`.
   - `pytest -n 4 tests/unit_tests/mcp_service`: 5,649 passed, 3 skipped.
   
   **Access check (same fixture): PASS**
   - A Gamma user who can see the dashboard through dashboard RBAC but has no datasource access to its charts gets the same scoped payloads as Admin. Every scoped `chart_id` also appears in the full layout.
   - A Gamma user without access to the dashboard gets `not_found` for every scope option.
   
   **Review thread "Dead selected_ids initializer": closed.** The initializer was removed in 6bff49560c, and there is already a reply on that thread.
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #44797:
URL: https://github.com/apache/superset/pull/44797#discussion_r4139228733


##########
superset/mcp_service/dashboard/tool/get_dashboard_layout.py:
##########
@@ -39,13 +39,135 @@
     dashboard_layout_serializer,
     DashboardError,
     DashboardLayout,
+    DashboardLayoutScope,
+    DashboardTab,
+    DashboardTabSummary,
     GetDashboardLayoutRequest,
 )
 from superset.mcp_service.mcp_core import ModelGetInfoCore
 
 logger = logging.getLogger(__name__)
 
 
+def _resolve_tab(
+    tabs: list[DashboardTab], selector: str
+) -> DashboardTab | DashboardError:
+    """Match a tab by ID first, then by exact title."""
+    if not tabs:
+        return DashboardError.create(
+            "This dashboard has no tabs. Omit tab to get the full layout.",
+            "tab_not_found",
+        )
+    matches = [tab for tab in tabs if tab.id == selector] or [
+        tab for tab in tabs if tab.name == selector
+    ]
+    if not matches:
+        return DashboardError.create(
+            "Tab not found. Use tabs_only=true to discover tab IDs and titles.",
+            "tab_not_found",
+        )
+    if len(matches) > 1:
+        return DashboardError.create(
+            "Multiple tabs have that title. Use tabs_only=true to discover "
+            "their IDs, then pass a unique tab ID.",
+            "ambiguous_tab",
+        )
+    return matches[0]
+
+
+def _subtree_ids(tab_id: str, children: dict[str | None, list[str]]) -> set[str]:
+    """Return a tab ID and the IDs of every tab nested under it."""
+    selected_ids: set[str] = set()
+    pending = [tab_id]
+    while pending:
+        current = pending.pop()
+        if current not in selected_ids:
+            selected_ids.add(current)
+            pending.extend(children.get(current, []))
+    return selected_ids
+
+
+def _tab_summaries(
+    tabs: list[DashboardTab], children: dict[str | None, list[str]]
+) -> list[DashboardTabSummary]:
+    """Summarize tabs with absolute depths from the full dashboard tree."""
+    # The parser only emits reachable tabs and assigns each tab a single
+    # enclosing parent, so walking from the top-level tabs reaches every tab.
+    depths: dict[str, int] = {}
+    stack = [(tab_id, 0) for tab_id in children.get(None, [])]
+    while stack:
+        tab_id, depth = stack.pop()
+        depths[tab_id] = depth
+        stack.extend((child, depth + 1) for child in children.get(tab_id, []))
+    return [
+        DashboardTabSummary(
+            id=tab.id,
+            name=tab.name,
+            parent_tab_id=tab.parent_tab_id,
+            depth=depths[tab.id],
+            chart_count=len(tab.chart_ids),
+        )
+        for tab in tabs
+    ]
+
+
+def _scope_layout(
+    layout: DashboardLayout, request: GetDashboardLayoutRequest
+) -> DashboardLayout | DashboardError:
+    """Project the parsed layout without changing permalink or ancestry context.
+
+    Scoping only ever removes tabs and chart placements from the parsed layout,
+    so a scoped response never contains a chart the full layout would not.
+    """
+    if not request.tabs_only and request.tab is None and not request.untabbed_only:
+        return layout
+
+    if request.untabbed_only:
+        return layout.model_copy(
+            update={
+                "tabs": [],
+                "charts": [chart for chart in layout.charts if chart.tab_id is None],
+                "scope": DashboardLayoutScope(untabbed_only=True),
+            }
+        )
+
+    tabs = layout.tabs
+    children: dict[str | None, list[str]] = {}
+    for tab in tabs:
+        children.setdefault(tab.parent_tab_id, []).append(tab.id)
+
+    selected_tab_id: str | None = None
+    selected_ids = {tab.id for tab in tabs}

Review Comment:
   <!-- Bito Reply -->
   The removal of the `selected_ids` initializer is correct, as the variable was unused in the execution paths where it was previously defined. Your assessment that the DFS traversal in `_extract_layout_from_position` and the subsequent tree parsing in `_tab_summaries` prevent the cycle and missing-depth issues suggested by the reviewer is accurate. The logic remains robust for the current call path, and the changes are safe to proceed with.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44797:
URL: https://github.com/apache/superset/pull/44797#issuecomment-5890832732

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #44797:
URL: https://github.com/apache/superset/pull/44797#issuecomment-5902051017

   Review pass at 892fc24aad, covering correctness, access scoping, and tests.
   
   **Findings and dispositions**
   - Bito run #0086c7, "Dead selected_ids initializer": valid. Fixed in 6bff49560c and replied on the thread, which is now resolved. Every path that reads `selected_ids` first binds it through `_subtree_ids`: an explicit `tab` does that, and the unscoped, `untabbed_only` and `tabs_only`-without-`tab` paths all return before reaching it.
   - Bito additional suggestion, "Unbounded DFS on tab tree": does not apply. `_extract_layout_from_position` walks from `ROOT_ID` with a visited set. `parent_tab_id` comes from the traversal ancestry, not from `position_json`. So the parsed tabs form an acyclic tree rooted at the top-level tabs, and `_tab_summaries` cannot loop or miss a depth.
   - Test coverage gap (from this review): the shared-permalink test already ran with `tabs_only` and with `tab` set to a tab other than the permalink's active tab. It only checked that the permalink state survived, never that the scope was applied. Fixed in 892fc24aad: the test now also asserts `scope`, `tab_tree`, `tabs` and chart placements. I checked it by disabling `_scope_layout`, which makes the test fail.
   
   **No issues found**
   - Access: scoping only filters the already-authorized parsed layout, and the dashboard is still fetched through `DashboardDAO` under the `Dashboard` permission. The suggestions on the oversized-response error reuse that caller's own blocked payload, with tab IDs capped at 5 and truncated to 64 characters. The `list_charts` hint goes through that tool's normal access filtering.
   - Tab resolution (ID before title, ambiguous titles, blank selector), distinct `untabbed_chart_count`, and `untabbed_only` exclusivity all behave as described and have tests.
   
   **Validation:** `tests/unit_tests/mcp_service/dashboard`, `utils` and the middleware tests: 1357 passed. The layout tool file alone: 55 passed. Pre-commit on the changed file passed (mypy, ruff, ruff-format).
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz commented on code in PR #44797:
URL: https://github.com/apache/superset/pull/44797#discussion_r4160578385


##########
superset/mcp_service/dashboard/schemas.py:
##########
@@ -371,6 +389,8 @@ def _require_identifier_or_permalink(self) -> "GetDashboardLayoutRequest":
         )
         if identifier_is_blank and permalink_is_blank:
             raise ValueError("Provide identifier or permalink_key")
+        if self.untabbed_only and (self.tabs_only or self.tab is not None):
+            raise ValueError("untabbed_only cannot be combined with tab or tabs_only")

Review Comment:
   Not a blocker, and not something this PR broke, but worth knowing before this ships as an agent recovery feature: this message never reaches the caller. `validation_message` maps Pydantic error types through a fixed `_REASONS` vocabulary (`superset/mcp_service/utils/validation.py:204`) that deliberately does not echo validator text, and `value_error` is not in that map. Against the running server, `{"identifier": 1, "untabbed_only": true, "tabs_only": true}` comes back as `Validation error in get_dashboard_layout: request: Invalid value; check the field schema`, and `tab: "   "` as `request.tab: Invalid value; check the field schema` rather than `tab must not be blank`. The pre-existing `Provide identifier or permalink_key` behaves exactly the same way, and `test_layout_rejects_untabbed_only_with_tab_options` asserts on the `ValidationError` directly rather than through `Client`, which is why it passes while the caller-visible text stays generic.
   
   Since `_resolve_tab` already returns an actionable `DashboardError` for `tab_not_found` and `ambiguous_tab`, would you rather do the exclusivity check in `_scope_layout` and return a `DashboardError` that names the flag to drop? Or do you read the field descriptions as carrying enough for this one?



##########
superset/mcp_service/dashboard/tool/get_dashboard_layout.py:
##########
@@ -39,13 +39,134 @@
     dashboard_layout_serializer,
     DashboardError,
     DashboardLayout,
+    DashboardLayoutScope,
+    DashboardTab,
+    DashboardTabSummary,
     GetDashboardLayoutRequest,
 )
 from superset.mcp_service.mcp_core import ModelGetInfoCore
 
 logger = logging.getLogger(__name__)
 
 
+def _resolve_tab(
+    tabs: list[DashboardTab], selector: str
+) -> DashboardTab | DashboardError:
+    """Match a tab by ID first, then by exact title."""
+    if not tabs:
+        return DashboardError.create(
+            "This dashboard has no tabs. Omit tab to get the full layout.",
+            "tab_not_found",
+        )
+    matches = [tab for tab in tabs if tab.id == selector] or [
+        tab for tab in tabs if tab.name == selector
+    ]
+    if not matches:
+        return DashboardError.create(
+            "Tab not found. Use tabs_only=true to discover tab IDs and titles.",
+            "tab_not_found",
+        )
+    if len(matches) > 1:
+        return DashboardError.create(
+            "Multiple tabs have that title. Use tabs_only=true to discover "
+            "their IDs, then pass a unique tab ID.",
+            "ambiguous_tab",
+        )
+    return matches[0]
+
+
+def _subtree_ids(tab_id: str, children: dict[str | None, list[str]]) -> set[str]:
+    """Return a tab ID and the IDs of every tab nested under it."""
+    selected_ids: set[str] = set()
+    pending = [tab_id]
+    while pending:
+        current = pending.pop()
+        if current not in selected_ids:
+            selected_ids.add(current)
+            pending.extend(children.get(current, []))
+    return selected_ids
+
+
+def _tab_summaries(
+    tabs: list[DashboardTab], children: dict[str | None, list[str]]
+) -> list[DashboardTabSummary]:
+    """Summarize tabs with absolute depths from the full dashboard tree."""
+    # The parser only emits reachable tabs and assigns each tab a single
+    # enclosing parent, so walking from the top-level tabs reaches every tab.
+    depths: dict[str, int] = {}
+    stack = [(tab_id, 0) for tab_id in children.get(None, [])]
+    while stack:
+        tab_id, depth = stack.pop()
+        depths[tab_id] = depth
+        stack.extend((child, depth + 1) for child in children.get(tab_id, []))
+    return [
+        DashboardTabSummary(
+            id=tab.id,
+            name=tab.name,
+            parent_tab_id=tab.parent_tab_id,
+            depth=depths[tab.id],
+            chart_count=len(tab.chart_ids),
+        )
+        for tab in tabs
+    ]
+
+
+def _scope_layout(
+    layout: DashboardLayout, request: GetDashboardLayoutRequest
+) -> DashboardLayout | DashboardError:
+    """Project the parsed layout without changing permalink or ancestry context.
+
+    Scoping only ever removes tabs and chart placements from the parsed layout,
+    so a scoped response never contains a chart the full layout would not.
+    """
+    if not request.tabs_only and request.tab is None and not request.untabbed_only:
+        return layout
+
+    if request.untabbed_only:
+        return layout.model_copy(
+            update={
+                "tabs": [],
+                "charts": [chart for chart in layout.charts if chart.tab_id is None],
+                "scope": DashboardLayoutScope(untabbed_only=True),
+            }
+        )
+
+    tabs = layout.tabs
+    children: dict[str | None, list[str]] = {}
+    for tab in tabs:
+        children.setdefault(tab.parent_tab_id, []).append(tab.id)
+
+    selected_tab_id: str | None = None
+    if request.tab is not None:
+        selected = _resolve_tab(tabs, request.tab)
+        if isinstance(selected, DashboardError):
+            return selected
+        selected_tab_id = selected.id
+        selected_ids = _subtree_ids(selected.id, children)
+        tabs = [tab for tab in tabs if tab.id in selected_ids]
+
+    scope = DashboardLayoutScope(tabs_only=request.tabs_only, tab_id=selected_tab_id)
+    if request.tabs_only:

Review Comment:
   Small asymmetry I noticed while walking the edge inputs. On a dashboard with no tabs, `tab="Anything"` returns the very helpful `tab_not_found` with `This dashboard has no tabs. Omit tab to get the full layout.`, but `tabs_only=true` on that same dashboard returns a success payload with `tabs: []`, `tab_tree: []` and `charts: []`, so the only thing separating "this dashboard has no tabs" from "this dashboard is empty" is `untabbed_chart_count`. I confirmed both against a flat dashboard on the running server.
   
   Not a blocker, the field descriptions do say `tabs_only` empties `tabs` and `charts` by request. Would the same `DashboardError` shape, pointing at `untabbed_only`, be friendlier than an all empty payload here?



##########
superset/mcp_service/dashboard/tool/get_dashboard_layout.py:
##########
@@ -39,13 +39,134 @@
     dashboard_layout_serializer,
     DashboardError,
     DashboardLayout,
+    DashboardLayoutScope,
+    DashboardTab,
+    DashboardTabSummary,
     GetDashboardLayoutRequest,
 )
 from superset.mcp_service.mcp_core import ModelGetInfoCore
 
 logger = logging.getLogger(__name__)
 
 
+def _resolve_tab(
+    tabs: list[DashboardTab], selector: str
+) -> DashboardTab | DashboardError:
+    """Match a tab by ID first, then by exact title."""
+    if not tabs:
+        return DashboardError.create(
+            "This dashboard has no tabs. Omit tab to get the full layout.",
+            "tab_not_found",
+        )
+    matches = [tab for tab in tabs if tab.id == selector] or [
+        tab for tab in tabs if tab.name == selector
+    ]
+    if not matches:
+        return DashboardError.create(
+            "Tab not found. Use tabs_only=true to discover tab IDs and titles.",
+            "tab_not_found",
+        )
+    if len(matches) > 1:
+        return DashboardError.create(
+            "Multiple tabs have that title. Use tabs_only=true to discover "
+            "their IDs, then pass a unique tab ID.",
+            "ambiguous_tab",
+        )
+    return matches[0]
+
+
+def _subtree_ids(tab_id: str, children: dict[str | None, list[str]]) -> set[str]:
+    """Return a tab ID and the IDs of every tab nested under it."""
+    selected_ids: set[str] = set()
+    pending = [tab_id]
+    while pending:
+        current = pending.pop()
+        if current not in selected_ids:
+            selected_ids.add(current)
+            pending.extend(children.get(current, []))
+    return selected_ids
+
+
+def _tab_summaries(
+    tabs: list[DashboardTab], children: dict[str | None, list[str]]
+) -> list[DashboardTabSummary]:
+    """Summarize tabs with absolute depths from the full dashboard tree."""
+    # The parser only emits reachable tabs and assigns each tab a single
+    # enclosing parent, so walking from the top-level tabs reaches every tab.
+    depths: dict[str, int] = {}
+    stack = [(tab_id, 0) for tab_id in children.get(None, [])]
+    while stack:
+        tab_id, depth = stack.pop()
+        depths[tab_id] = depth
+        stack.extend((child, depth + 1) for child in children.get(tab_id, []))
+    return [
+        DashboardTabSummary(
+            id=tab.id,
+            name=tab.name,
+            parent_tab_id=tab.parent_tab_id,
+            depth=depths[tab.id],
+            chart_count=len(tab.chart_ids),
+        )
+        for tab in tabs
+    ]
+
+
+def _scope_layout(
+    layout: DashboardLayout, request: GetDashboardLayoutRequest
+) -> DashboardLayout | DashboardError:
+    """Project the parsed layout without changing permalink or ancestry context.
+
+    Scoping only ever removes tabs and chart placements from the parsed layout,
+    so a scoped response never contains a chart the full layout would not.
+    """
+    if not request.tabs_only and request.tab is None and not request.untabbed_only:
+        return layout
+
+    if request.untabbed_only:
+        return layout.model_copy(
+            update={
+                "tabs": [],
+                "charts": [chart for chart in layout.charts if chart.tab_id is None],
+                "scope": DashboardLayoutScope(untabbed_only=True),
+            }
+        )
+
+    tabs = layout.tabs
+    children: dict[str | None, list[str]] = {}
+    for tab in tabs:
+        children.setdefault(tab.parent_tab_id, []).append(tab.id)
+
+    selected_tab_id: str | None = None
+    if request.tab is not None:
+        selected = _resolve_tab(tabs, request.tab)
+        if isinstance(selected, DashboardError):
+            return selected
+        selected_tab_id = selected.id
+        selected_ids = _subtree_ids(selected.id, children)
+        tabs = [tab for tab in tabs if tab.id in selected_ids]
+
+    scope = DashboardLayoutScope(tabs_only=request.tabs_only, tab_id=selected_tab_id)
+    if request.tabs_only:
+        return layout.model_copy(
+            update={
+                "tabs": [],
+                "tab_tree": _tab_summaries(tabs, children),
+                "charts": [],
+                "scope": scope,
+            }
+        )
+
+    return layout.model_copy(
+        update={
+            "tabs": tabs,
+            "charts": [
+                chart for chart in layout.charts if chart.tab_id in selected_ids

Review Comment:
   Just a small NIT, and I know Bito asked for the opposite on the thread above. `selected_ids` is now bound only inside `if request.tab is not None`, so this line is correct only because the `tabs_only` branch returns above it and the no-scope case returns at the top of the function. The empty set default Bito objected to was misleading, but a meaningful one is not:
   
   ```python
       selected_ids: set[str] = {tab.id for tab in tabs}
       if request.tab is not None:
           ...
   ```
   
   That keeps the "all tabs" reading if a future branch ever reaches this return with `tab` unset, instead of an `UnboundLocalError`. Entirely your call.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(mcp): support tab-scoped dashboard layouts [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #44797:
URL: https://github.com/apache/superset/pull/44797#discussion_r4161011809


##########
superset/mcp_service/dashboard/schemas.py:
##########
@@ -371,6 +389,8 @@ def _require_identifier_or_permalink(self) -> "GetDashboardLayoutRequest":
         )
         if identifier_is_blank and permalink_is_blank:
             raise ValueError("Provide identifier or permalink_key")
+        if self.untabbed_only and (self.tabs_only or self.tab is not None):
+            raise ValueError("untabbed_only cannot be combined with tab or tabs_only")

Review Comment:
   Fixed in 6d14e75dd12c6e6446047bb12f28384e0f9e2c33: scope exclusivity is checked in `_scope_layout` and blank selectors in `_resolve_tab`, returning actionable `DashboardError` payloads rather than generic Pydantic validation text. Client-level regression tests cover both cases.



##########
superset/mcp_service/dashboard/tool/get_dashboard_layout.py:
##########
@@ -39,13 +39,134 @@
     dashboard_layout_serializer,
     DashboardError,
     DashboardLayout,
+    DashboardLayoutScope,
+    DashboardTab,
+    DashboardTabSummary,
     GetDashboardLayoutRequest,
 )
 from superset.mcp_service.mcp_core import ModelGetInfoCore
 
 logger = logging.getLogger(__name__)
 
 
+def _resolve_tab(
+    tabs: list[DashboardTab], selector: str
+) -> DashboardTab | DashboardError:
+    """Match a tab by ID first, then by exact title."""
+    if not tabs:
+        return DashboardError.create(
+            "This dashboard has no tabs. Omit tab to get the full layout.",
+            "tab_not_found",
+        )
+    matches = [tab for tab in tabs if tab.id == selector] or [
+        tab for tab in tabs if tab.name == selector
+    ]
+    if not matches:
+        return DashboardError.create(
+            "Tab not found. Use tabs_only=true to discover tab IDs and titles.",
+            "tab_not_found",
+        )
+    if len(matches) > 1:
+        return DashboardError.create(
+            "Multiple tabs have that title. Use tabs_only=true to discover "
+            "their IDs, then pass a unique tab ID.",
+            "ambiguous_tab",
+        )
+    return matches[0]
+
+
+def _subtree_ids(tab_id: str, children: dict[str | None, list[str]]) -> set[str]:
+    """Return a tab ID and the IDs of every tab nested under it."""
+    selected_ids: set[str] = set()
+    pending = [tab_id]
+    while pending:
+        current = pending.pop()
+        if current not in selected_ids:
+            selected_ids.add(current)
+            pending.extend(children.get(current, []))
+    return selected_ids
+
+
+def _tab_summaries(
+    tabs: list[DashboardTab], children: dict[str | None, list[str]]
+) -> list[DashboardTabSummary]:
+    """Summarize tabs with absolute depths from the full dashboard tree."""
+    # The parser only emits reachable tabs and assigns each tab a single
+    # enclosing parent, so walking from the top-level tabs reaches every tab.
+    depths: dict[str, int] = {}
+    stack = [(tab_id, 0) for tab_id in children.get(None, [])]
+    while stack:
+        tab_id, depth = stack.pop()
+        depths[tab_id] = depth
+        stack.extend((child, depth + 1) for child in children.get(tab_id, []))
+    return [
+        DashboardTabSummary(
+            id=tab.id,
+            name=tab.name,
+            parent_tab_id=tab.parent_tab_id,
+            depth=depths[tab.id],
+            chart_count=len(tab.chart_ids),
+        )
+        for tab in tabs
+    ]
+
+
+def _scope_layout(
+    layout: DashboardLayout, request: GetDashboardLayoutRequest
+) -> DashboardLayout | DashboardError:
+    """Project the parsed layout without changing permalink or ancestry context.
+
+    Scoping only ever removes tabs and chart placements from the parsed layout,
+    so a scoped response never contains a chart the full layout would not.
+    """
+    if not request.tabs_only and request.tab is None and not request.untabbed_only:
+        return layout
+
+    if request.untabbed_only:
+        return layout.model_copy(
+            update={
+                "tabs": [],
+                "charts": [chart for chart in layout.charts if chart.tab_id is None],
+                "scope": DashboardLayoutScope(untabbed_only=True),
+            }
+        )
+
+    tabs = layout.tabs
+    children: dict[str | None, list[str]] = {}
+    for tab in tabs:
+        children.setdefault(tab.parent_tab_id, []).append(tab.id)
+
+    selected_tab_id: str | None = None
+    if request.tab is not None:
+        selected = _resolve_tab(tabs, request.tab)
+        if isinstance(selected, DashboardError):
+            return selected
+        selected_tab_id = selected.id
+        selected_ids = _subtree_ids(selected.id, children)
+        tabs = [tab for tab in tabs if tab.id in selected_ids]
+
+    scope = DashboardLayoutScope(tabs_only=request.tabs_only, tab_id=selected_tab_id)
+    if request.tabs_only:

Review Comment:
   Fixed in 6d14e75dd12c6e6446047bb12f28384e0f9e2c33: `tabs_only=true` on a dashboard without tabs returns `tab_not_found` with guidance to use `untabbed_only=true` or request the full layout. Client tests cover flat, missing, and malformed layouts.



##########
superset/mcp_service/dashboard/tool/get_dashboard_layout.py:
##########
@@ -39,13 +39,134 @@
     dashboard_layout_serializer,
     DashboardError,
     DashboardLayout,
+    DashboardLayoutScope,
+    DashboardTab,
+    DashboardTabSummary,
     GetDashboardLayoutRequest,
 )
 from superset.mcp_service.mcp_core import ModelGetInfoCore
 
 logger = logging.getLogger(__name__)
 
 
+def _resolve_tab(
+    tabs: list[DashboardTab], selector: str
+) -> DashboardTab | DashboardError:
+    """Match a tab by ID first, then by exact title."""
+    if not tabs:
+        return DashboardError.create(
+            "This dashboard has no tabs. Omit tab to get the full layout.",
+            "tab_not_found",
+        )
+    matches = [tab for tab in tabs if tab.id == selector] or [
+        tab for tab in tabs if tab.name == selector
+    ]
+    if not matches:
+        return DashboardError.create(
+            "Tab not found. Use tabs_only=true to discover tab IDs and titles.",
+            "tab_not_found",
+        )
+    if len(matches) > 1:
+        return DashboardError.create(
+            "Multiple tabs have that title. Use tabs_only=true to discover "
+            "their IDs, then pass a unique tab ID.",
+            "ambiguous_tab",
+        )
+    return matches[0]
+
+
+def _subtree_ids(tab_id: str, children: dict[str | None, list[str]]) -> set[str]:
+    """Return a tab ID and the IDs of every tab nested under it."""
+    selected_ids: set[str] = set()
+    pending = [tab_id]
+    while pending:
+        current = pending.pop()
+        if current not in selected_ids:
+            selected_ids.add(current)
+            pending.extend(children.get(current, []))
+    return selected_ids
+
+
+def _tab_summaries(
+    tabs: list[DashboardTab], children: dict[str | None, list[str]]
+) -> list[DashboardTabSummary]:
+    """Summarize tabs with absolute depths from the full dashboard tree."""
+    # The parser only emits reachable tabs and assigns each tab a single
+    # enclosing parent, so walking from the top-level tabs reaches every tab.
+    depths: dict[str, int] = {}
+    stack = [(tab_id, 0) for tab_id in children.get(None, [])]
+    while stack:
+        tab_id, depth = stack.pop()
+        depths[tab_id] = depth
+        stack.extend((child, depth + 1) for child in children.get(tab_id, []))
+    return [
+        DashboardTabSummary(
+            id=tab.id,
+            name=tab.name,
+            parent_tab_id=tab.parent_tab_id,
+            depth=depths[tab.id],
+            chart_count=len(tab.chart_ids),
+        )
+        for tab in tabs
+    ]
+
+
+def _scope_layout(
+    layout: DashboardLayout, request: GetDashboardLayoutRequest
+) -> DashboardLayout | DashboardError:
+    """Project the parsed layout without changing permalink or ancestry context.
+
+    Scoping only ever removes tabs and chart placements from the parsed layout,
+    so a scoped response never contains a chart the full layout would not.
+    """
+    if not request.tabs_only and request.tab is None and not request.untabbed_only:
+        return layout
+
+    if request.untabbed_only:
+        return layout.model_copy(
+            update={
+                "tabs": [],
+                "charts": [chart for chart in layout.charts if chart.tab_id is None],
+                "scope": DashboardLayoutScope(untabbed_only=True),
+            }
+        )
+
+    tabs = layout.tabs
+    children: dict[str | None, list[str]] = {}
+    for tab in tabs:
+        children.setdefault(tab.parent_tab_id, []).append(tab.id)
+
+    selected_tab_id: str | None = None
+    if request.tab is not None:
+        selected = _resolve_tab(tabs, request.tab)
+        if isinstance(selected, DashboardError):
+            return selected
+        selected_tab_id = selected.id
+        selected_ids = _subtree_ids(selected.id, children)
+        tabs = [tab for tab in tabs if tab.id in selected_ids]
+
+    scope = DashboardLayoutScope(tabs_only=request.tabs_only, tab_id=selected_tab_id)
+    if request.tabs_only:
+        return layout.model_copy(
+            update={
+                "tabs": [],
+                "tab_tree": _tab_summaries(tabs, children),
+                "charts": [],
+                "scope": scope,
+            }
+        )
+
+    return layout.model_copy(
+        update={
+            "tabs": tabs,
+            "charts": [
+                chart for chart in layout.charts if chart.tab_id in selected_ids

Review Comment:
   Fixed in 6d14e75dd12c6e6446047bb12f28384e0f9e2c33: `selected_ids` is derived unconditionally from the final tab list immediately before the chart projection, while subtree filtering uses a separate `subtree_ids` variable. This removes the implicit binding dependency without reintroducing the dead initializer from the resolved earlier thread.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org