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/06/12 14:43:01 UTC
(superset) branch master updated: fix(mcp): add dataset_id to update_chart to support rebinding chart datasource (#40853)
This is an automated email from the ASF dual-hosted git repository.
aminghadersohi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 2f008afca93 fix(mcp): add dataset_id to update_chart to support rebinding chart datasource (#40853)
2f008afca93 is described below
commit 2f008afca930ae92c1d5ffdd596b4ca8ec39b350
Author: Amin Ghadersohi <am...@gmail.com>
AuthorDate: Fri Jun 12 10:42:53 2026 -0400
fix(mcp): add dataset_id to update_chart to support rebinding chart datasource (#40853)
Co-authored-by: Claude Sonnet 4.6 <no...@anthropic.com>
---
superset/mcp_service/chart/schemas.py | 9 +
superset/mcp_service/chart/tool/update_chart.py | 142 ++++++++--
.../mcp_service/chart/tool/test_update_chart.py | 293 ++++++++++++++++++++-
3 files changed, 414 insertions(+), 30 deletions(-)
diff --git a/superset/mcp_service/chart/schemas.py b/superset/mcp_service/chart/schemas.py
index eae34a78875..801c225a153 100644
--- a/superset/mcp_service/chart/schemas.py
+++ b/superset/mcp_service/chart/schemas.py
@@ -1956,6 +1956,15 @@ class UpdateChartRequest(QueryCacheControl):
max_length=255,
validation_alias=AliasChoices("chart_name", "name", "title", "slice_name"),
)
+ dataset_id: int | None = Field(
+ None,
+ description=(
+ "Target dataset ID to rebind the chart to a different dataset. "
+ "When omitted, the chart retains its existing dataset. "
+ "Can be combined with config to simultaneously change the dataset "
+ "and visualization, or used alone to rebind without altering the config."
+ ),
+ )
generate_preview: bool = Field(
default=True,
description=(
diff --git a/superset/mcp_service/chart/tool/update_chart.py b/superset/mcp_service/chart/tool/update_chart.py
index 6bc91e58c8e..6b704506ba9 100644
--- a/superset/mcp_service/chart/tool/update_chart.py
+++ b/superset/mcp_service/chart/tool/update_chart.py
@@ -77,10 +77,11 @@ def _validation_error_response(message: str, details: str) -> GenerateChartRespo
def _missing_config_or_name_error() -> GenerateChartResponse:
return _validation_error_response(
- message="Either 'config' or 'chart_name' must be provided.",
+ message="Either 'config', 'chart_name', or 'dataset_id' must be provided.",
details=(
- "Either 'config' or 'chart_name' must be provided. "
- "Use config for visualization changes, chart_name for renaming."
+ "Either 'config', 'chart_name', or 'dataset_id' must be provided. "
+ "Use config for visualization changes, chart_name for renaming, "
+ "dataset_id to rebind the chart to a different dataset."
),
)
@@ -102,12 +103,19 @@ def _build_update_payload(
"""Build the update payload for a chart update.
Returns a dict payload on success, or a GenerateChartResponse error
- when neither config nor chart_name is provided.
+ when neither config nor chart_name nor dataset_id is provided.
``parsed_config`` is the pre-parsed chart config from the caller.
"""
+ effective_dataset_id = (
+ request.dataset_id
+ if request.dataset_id is not None
+ else (chart.datasource_id if chart.datasource_id else None)
+ )
+
if parsed_config is not None:
- dataset_id = chart.datasource_id if chart.datasource_id else None
- new_form_data = map_config_to_form_data(parsed_config, dataset_id=dataset_id)
+ new_form_data = map_config_to_form_data(
+ parsed_config, dataset_id=effective_dataset_id
+ )
new_form_data.pop("_mcp_warnings", None)
chart_name = (
@@ -116,13 +124,27 @@ def _build_update_payload(
else chart.slice_name or generate_chart_name(parsed_config)
)
- return {
+ payload: dict[str, Any] = {
"slice_name": chart_name,
"viz_type": new_form_data["viz_type"],
"params": json.dumps(new_form_data),
# Clear stale query_context so get_chart_data uses the updated params.
"query_context": None,
}
+ if request.dataset_id is not None:
+ payload["datasource_id"] = request.dataset_id
+ payload["datasource_type"] = "table"
+ return payload
+
+ # Dataset-only update: rebind chart to a different dataset without changing viz
+ if request.dataset_id is not None:
+ payload = {
+ "datasource_id": request.dataset_id,
+ "datasource_type": "table",
+ }
+ if request.chart_name:
+ payload["slice_name"] = request.chart_name
+ return payload
# Name-only update: keep existing visualization, just rename
if not request.chart_name:
@@ -152,13 +174,20 @@ def _build_preview_form_data(
)
existing_form_data = {}
+ effective_dataset_id = (
+ request.dataset_id
+ if request.dataset_id is not None
+ else (chart.datasource_id if chart.datasource_id else None)
+ )
+
if parsed_config is not None:
- dataset_id = chart.datasource_id if chart.datasource_id else None
- new_form_data = map_config_to_form_data(parsed_config, dataset_id=dataset_id)
+ new_form_data = map_config_to_form_data(
+ parsed_config, dataset_id=effective_dataset_id
+ )
new_form_data.pop("_mcp_warnings", None)
merged = {**existing_form_data, **new_form_data}
else:
- if not request.chart_name:
+ if not request.chart_name and request.dataset_id is None:
return _missing_config_or_name_error()
merged = dict(existing_form_data)
@@ -168,8 +197,8 @@ def _build_preview_form_data(
merged["slice_name"] = chart.slice_name
merged["slice_id"] = chart.id
- if chart.datasource_id:
- merged["datasource"] = f"{chart.datasource_id}__table"
+ if effective_dataset_id:
+ merged["datasource"] = f"{effective_dataset_id}__table"
return merged
@@ -178,27 +207,39 @@ def _validate_update_against_dataset(
parsed_config: Any,
form_data: dict[str, Any],
chart: Any,
+ dataset_id: int | None = None,
+ run_compile_check: bool = True,
) -> GenerateChartResponse | None:
"""Run Tier 1 (schema) + Tier 2 (compile) validation against the chart's
dataset. Returns ``None`` on success, or a :class:`GenerateChartResponse`
error envelope on failure that callers should return as-is.
+
+ When ``dataset_id`` is provided, validates against that dataset instead of
+ the chart's existing datasource (used when rebinding to a new dataset).
+ Pass ``run_compile_check=False`` to skip the Tier 2 live-query check (used
+ for dataset-only rebinds where no new chart config is provided).
"""
from superset.daos.dataset import DatasetDAO
- dataset = getattr(chart, "datasource", None)
- if dataset is None and getattr(chart, "datasource_id", None) is not None:
- dataset = DatasetDAO.find_by_id(chart.datasource_id)
+ if dataset_id is not None:
+ dataset = DatasetDAO.find_by_id(dataset_id)
+ else:
+ dataset = getattr(chart, "datasource", None)
+ if dataset is None and getattr(chart, "datasource_id", None) is not None:
+ dataset = DatasetDAO.find_by_id(chart.datasource_id)
if dataset is None:
+ missing_id = (
+ dataset_id
+ if dataset_id is not None
+ else getattr(chart, "datasource_id", None)
+ )
return GenerateChartResponse.model_validate(
{
"chart": None,
"error": {
"error_type": "DatasetNotAccessible",
- "message": "Chart's dataset is not accessible",
- "details": (
- f"Dataset {getattr(chart, 'datasource_id', None)} "
- "is missing or inaccessible."
- ),
+ "message": "Dataset is not accessible",
+ "details": (f"Dataset {missing_id} is missing or inaccessible."),
},
"success": False,
"schema_version": "2.0",
@@ -207,7 +248,7 @@ def _validate_update_against_dataset(
)
compile_result = validate_and_compile(
- parsed_config, form_data, dataset, run_compile_check=True
+ parsed_config, form_data, dataset, run_compile_check=run_compile_check
)
if compile_result.success:
return None
@@ -239,12 +280,18 @@ def _validate_update_against_dataset(
def _create_preview_url(
- chart: Any, form_data: dict[str, Any]
+ chart: Any,
+ form_data: dict[str, Any],
+ datasource_id: int | None = None,
) -> tuple[str, str | None, list[str]]:
"""Cache form_data and return (explore_url, form_data_key, warnings).
The URL includes both ``slice_id`` and ``form_data_key`` so that when the
user clicks Save in Explore, the edits overwrite the original chart.
+
+ When ``datasource_id`` is provided, uses that datasource for the form_data
+ cache instead of the chart's existing datasource (used when rebinding to a
+ new dataset).
"""
from superset.commands.explore.form_data.parameters import CommandParameters
from superset.mcp_service.commands.create_form_data import MCPCreateFormDataCommand
@@ -252,7 +299,11 @@ def _create_preview_url(
base_url = get_superset_base_url()
- if not chart.datasource_id:
+ effective_datasource_id = (
+ datasource_id if datasource_id is not None else chart.datasource_id
+ )
+
+ if not effective_datasource_id:
warning = (
"Chart has no datasource; the preview URL shows the saved chart "
"state, not the pending changes. Open the URL and apply the "
@@ -267,7 +318,7 @@ def _create_preview_url(
cmd_params = CommandParameters(
datasource_type=DatasourceType.TABLE,
- datasource_id=chart.datasource_id,
+ datasource_id=effective_datasource_id,
chart_id=chart.id,
tab_id=None,
form_data=json.dumps(form_data),
@@ -433,12 +484,29 @@ async def update_chart( # noqa: C901
# Validate before persisting — catches bad column refs and runtime
# SQL errors so we don't commit a chart that can't be queried.
- # Renames (no parsed_config) skip validation since form_data is
- # untouched.
+ # Renames (no parsed_config and no dataset_id) skip validation since
+ # form_data is untouched and no rebind is requested.
if parsed_config is not None and new_form_data is not None:
with event_logger.log_context(action="mcp.update_chart.validation"):
validation_error = _validate_update_against_dataset(
- parsed_config, new_form_data, chart
+ parsed_config,
+ new_form_data,
+ chart,
+ dataset_id=request.dataset_id,
+ )
+ if validation_error is not None:
+ return validation_error
+ elif request.dataset_id is not None:
+ # Dataset-only rebind: verify the target dataset exists before
+ # writing. Skip compile check — there is no new chart config to
+ # execute against the new dataset.
+ with event_logger.log_context(action="mcp.update_chart.validation"):
+ validation_error = _validate_update_against_dataset(
+ None,
+ {},
+ chart,
+ dataset_id=request.dataset_id,
+ run_compile_check=False,
)
if validation_error is not None:
return validation_error
@@ -459,14 +527,30 @@ async def update_chart( # noqa: C901
if parsed_config is not None:
with event_logger.log_context(action="mcp.update_chart.validation"):
validation_error = _validate_update_against_dataset(
- parsed_config, preview_or_error, chart
+ parsed_config,
+ preview_or_error,
+ chart,
+ dataset_id=request.dataset_id,
+ )
+ if validation_error is not None:
+ return validation_error
+ elif request.dataset_id is not None:
+ # Dataset-only rebind: verify the target dataset exists before
+ # caching. Skip compile check — no new config to execute.
+ with event_logger.log_context(action="mcp.update_chart.validation"):
+ validation_error = _validate_update_against_dataset(
+ None,
+ {},
+ chart,
+ dataset_id=request.dataset_id,
+ run_compile_check=False,
)
if validation_error is not None:
return validation_error
with event_logger.log_context(action="mcp.update_chart.preview_link"):
explore_url, form_data_key, warnings = _create_preview_url(
- chart, preview_or_error
+ chart, preview_or_error, datasource_id=request.dataset_id
)
chart_for_analysis = updated_chart if saved else chart
diff --git a/tests/unit_tests/mcp_service/chart/tool/test_update_chart.py b/tests/unit_tests/mcp_service/chart/tool/test_update_chart.py
index 4a8918173f0..bc0cfab43eb 100644
--- a/tests/unit_tests/mcp_service/chart/tool/test_update_chart.py
+++ b/tests/unit_tests/mcp_service/chart/tool/test_update_chart.py
@@ -20,6 +20,7 @@ Unit tests for update_chart MCP tool
"""
import importlib
+from typing import Any
from unittest.mock import Mock, patch
import pytest
@@ -582,7 +583,7 @@ class TestBuildUpdatePayload:
assert result == {"slice_name": "New Name"}
def test_error_when_no_config_and_no_name(self):
- """Returns GenerateChartResponse error when neither config nor chart_name."""
+ """Returns error when neither config, chart_name, nor dataset_id is provided."""
request = UpdateChartRequest(identifier=1)
chart = Mock()
@@ -594,6 +595,7 @@ class TestBuildUpdatePayload:
assert result.error.error_type == "ValidationError"
assert "config" in result.error.message.lower()
assert "chart_name" in result.error.message.lower()
+ assert "dataset_id" in result.error.message.lower()
def test_config_update_uses_request_chart_name(self):
"""When config and chart_name are both provided, uses chart_name."""
@@ -1344,3 +1346,292 @@ class TestUpdateChartSqlMetric:
assert "<UNTRUSTED-CONTENT>" in m["sqlExpression"]
assert "<UNTRUSTED-CONTENT>" in m["label"]
assert "<UNTRUSTED-CONTENT>" not in m["optionName"]
+
+
+class TestBuildUpdatePayloadDatasetId:
+ """Tests for dataset_id support in _build_update_payload."""
+
+ def test_dataset_only_update_returns_datasource_fields(self) -> None:
+ """dataset_id alone produces a payload with datasource_id + datasource_type."""
+ request = UpdateChartRequest(identifier=1, dataset_id=42)
+ chart = Mock()
+ chart.datasource_id = 10
+
+ result = _build_update_payload(request, chart)
+
+ assert isinstance(result, dict)
+ assert result == {"datasource_id": 42, "datasource_type": "table"}
+
+ def test_dataset_and_name_update(self) -> None:
+ """dataset_id + chart_name: payload includes datasource fields
+ and slice_name."""
+ request = UpdateChartRequest(identifier=1, dataset_id=42, chart_name="Renamed")
+ chart = Mock()
+ chart.datasource_id = 10
+
+ result = _build_update_payload(request, chart)
+
+ assert isinstance(result, dict)
+ assert result == {
+ "datasource_id": 42,
+ "datasource_type": "table",
+ "slice_name": "Renamed",
+ }
+
+ def test_dataset_and_config_update_includes_datasource(self):
+ """dataset_id + config: payload includes datasource_id and datasource_type."""
+ config = TableChartConfig(
+ chart_type="table",
+ columns=[ColumnRef(name="col1")],
+ )
+ request = UpdateChartRequest(identifier=1, config=config, dataset_id=99)
+ chart = Mock()
+ chart.datasource_id = 10
+ chart.slice_name = "Old Name"
+
+ result = _build_update_payload(request, chart, parsed_config=config)
+
+ assert isinstance(result, dict)
+ assert result["datasource_id"] == 99
+ assert result["datasource_type"] == "table"
+ assert "params" in result
+ assert "viz_type" in result
+
+ def test_config_without_dataset_does_not_include_datasource(self):
+ """When dataset_id is None, payload must NOT include datasource_id."""
+ config = TableChartConfig(
+ chart_type="table",
+ columns=[ColumnRef(name="col1")],
+ )
+ request = UpdateChartRequest(identifier=1, config=config)
+ chart = Mock()
+ chart.datasource_id = 10
+ chart.slice_name = "Old Name"
+
+ result = _build_update_payload(request, chart, parsed_config=config)
+
+ assert isinstance(result, dict)
+ assert "datasource_id" not in result
+ assert "datasource_type" not in result
+
+
+class TestBuildPreviewFormDataDatasetId:
+ """Tests for dataset_id support in _build_preview_form_data."""
+
+ def test_dataset_only_update_sets_datasource_field(self):
+ """dataset_id alone updates the datasource field in merged form_data."""
+ request = UpdateChartRequest(identifier=1, dataset_id=55)
+ chart = Mock()
+ chart.datasource_id = 10
+ chart.slice_name = "Chart"
+ chart.id = 1
+ chart.params = None
+
+ result = _build_preview_form_data(request, chart)
+
+ assert isinstance(result, dict)
+ assert result["datasource"] == "55__table"
+
+ def test_config_and_dataset_uses_new_dataset(self):
+ """config + dataset_id: datasource field reflects the new dataset."""
+ config = TableChartConfig(
+ chart_type="table",
+ columns=[ColumnRef(name="col1")],
+ )
+ request = UpdateChartRequest(identifier=1, config=config, dataset_id=77)
+ chart = Mock()
+ chart.datasource_id = 10
+ chart.slice_name = "Chart"
+ chart.id = 1
+ chart.params = None
+
+ result = _build_preview_form_data(request, chart, parsed_config=config)
+
+ assert isinstance(result, dict)
+ assert result["datasource"] == "77__table"
+
+ def test_no_dataset_keeps_existing_datasource(self):
+ """When dataset_id is None, datasource reflects the existing chart dataset."""
+ config = TableChartConfig(
+ chart_type="table",
+ columns=[ColumnRef(name="col1")],
+ )
+ request = UpdateChartRequest(identifier=1, config=config)
+ chart = Mock()
+ chart.datasource_id = 10
+ chart.slice_name = "Chart"
+ chart.id = 1
+ chart.params = None
+
+ result = _build_preview_form_data(request, chart, parsed_config=config)
+
+ assert isinstance(result, dict)
+ assert result["datasource"] == "10__table"
+
+
+class TestUpdateChartDatasetIdIntegration:
+ """Integration test verifying dataset_id is plumbed into UpdateChartCommand."""
+
+ @patch(
+ "superset.mcp_service.auth.check_chart_data_access",
+ new_callable=Mock,
+ )
+ @patch(
+ "superset.commands.chart.update.UpdateChartCommand",
+ new_callable=Mock,
+ )
+ @patch(
+ "superset.mcp_service.chart.tool.update_chart._validate_update_against_dataset",
+ return_value=None,
+ )
+ @patch("superset.daos.chart.ChartDAO.find_by_id", new_callable=Mock)
+ @patch("superset.db.session")
+ @pytest.mark.asyncio
+ async def test_dataset_id_passed_to_update_command(
+ self,
+ mock_db_session: Any,
+ mock_find_by_id: Mock,
+ mock_validate: Mock,
+ mock_update_cmd_cls: Mock,
+ mock_check_access: Mock,
+ mcp_server: Any,
+ ) -> None:
+ """dataset_id in request is forwarded to UpdateChartCommand payload."""
+ mock_chart = Mock()
+ mock_chart.id = 55
+ mock_chart.datasource_id = 10
+ mock_chart.slice_name = "Old Chart"
+ mock_chart.viz_type = "table"
+ mock_chart.uuid = "uuid-55"
+ mock_find_by_id.return_value = mock_chart
+
+ mock_check_access.return_value = DatasetValidationResult(
+ is_valid=True,
+ dataset_id=10,
+ dataset_name="old_dataset",
+ warnings=[],
+ )
+
+ updated_chart = Mock()
+ updated_chart.id = 55
+ updated_chart.slice_name = "Old Chart"
+ updated_chart.viz_type = "table"
+ updated_chart.uuid = "uuid-55"
+ mock_update_cmd_cls.return_value.run.return_value = updated_chart
+
+ request = {
+ "identifier": 55,
+ "dataset_id": 1041,
+ "generate_preview": False,
+ }
+
+ async with Client(mcp) as client:
+ result = await client.call_tool("update_chart", {"request": request})
+
+ assert result.structured_content["success"] is True
+
+ call_args = mock_update_cmd_cls.call_args
+ payload = call_args[0][1]
+ assert payload.get("datasource_id") == 1041
+ assert payload.get("datasource_type") == "table"
+
+ @patch(
+ "superset.mcp_service.auth.check_chart_data_access",
+ new_callable=Mock,
+ )
+ @patch("superset.daos.dataset.DatasetDAO.find_by_id", new_callable=Mock)
+ @patch("superset.daos.chart.ChartDAO.find_by_id", new_callable=Mock)
+ @patch("superset.db.session")
+ @pytest.mark.asyncio
+ async def test_dataset_only_rebind_invalid_dataset_returns_error(
+ self,
+ mock_db_session: Any,
+ mock_chart_find: Mock,
+ mock_dataset_find: Mock,
+ mock_check_access: Mock,
+ mcp_server: Any,
+ ) -> None:
+ """dataset_id pointing to a non-existent dataset returns
+ DatasetNotAccessible."""
+ mock_chart = Mock()
+ mock_chart.id = 55
+ mock_chart.datasource_id = 10
+ mock_chart.slice_name = "Old Chart"
+ mock_chart.viz_type = "table"
+ mock_chart.uuid = "uuid-55"
+ mock_chart_find.return_value = mock_chart
+
+ mock_check_access.return_value = DatasetValidationResult(
+ is_valid=True,
+ dataset_id=10,
+ dataset_name="old_dataset",
+ warnings=[],
+ )
+
+ # Target dataset does not exist
+ mock_dataset_find.return_value = None
+
+ request = {
+ "identifier": 55,
+ "dataset_id": 9999,
+ "generate_preview": False,
+ }
+
+ async with Client(mcp) as client:
+ result = await client.call_tool("update_chart", {"request": request})
+
+ assert result.structured_content["success"] is False
+ error_type = result.structured_content["error"]["error_type"]
+ assert error_type == "DatasetNotAccessible"
+ assert "9999" in result.structured_content["error"]["details"]
+
+ @patch(
+ "superset.mcp_service.auth.check_chart_data_access",
+ new_callable=Mock,
+ )
+ @patch("superset.daos.dataset.DatasetDAO.find_by_id", new_callable=Mock)
+ @patch("superset.daos.chart.ChartDAO.find_by_id", new_callable=Mock)
+ @patch("superset.db.session")
+ @pytest.mark.asyncio
+ async def test_dataset_only_rebind_invalid_dataset_preview_returns_error(
+ self,
+ mock_db_session: Any,
+ mock_chart_find: Mock,
+ mock_dataset_find: Mock,
+ mock_check_access: Mock,
+ mcp_server: Any,
+ ) -> None:
+ """dataset_id pointing to a non-existent dataset returns error in
+ preview path."""
+ mock_chart = Mock()
+ mock_chart.id = 55
+ mock_chart.datasource_id = 10
+ mock_chart.slice_name = "Old Chart"
+ mock_chart.viz_type = "table"
+ mock_chart.uuid = "uuid-55"
+ mock_chart.params = None
+ mock_chart_find.return_value = mock_chart
+
+ mock_check_access.return_value = DatasetValidationResult(
+ is_valid=True,
+ dataset_id=10,
+ dataset_name="old_dataset",
+ warnings=[],
+ )
+
+ # Target dataset does not exist
+ mock_dataset_find.return_value = None
+
+ request = {
+ "identifier": 55,
+ "dataset_id": 9999,
+ "generate_preview": True,
+ }
+
+ async with Client(mcp) as client:
+ result = await client.call_tool("update_chart", {"request": request})
+
+ assert result.structured_content["success"] is False
+ error_type = result.structured_content["error"]["error_type"]
+ assert error_type == "DatasetNotAccessible"
+ assert "9999" in result.structured_content["error"]["details"]