Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
576ade7
feat(mcp): add sort_by schema and SortByConfig to XYChartConfig
FrancescoCastaldi Sep 26, 2026
342e3fd
fix(mcp): reject multi-column sort lists in XYChartConfig validation
FrancescoCastaldi Sep 26, 2026
75830ec
test(mcp): add unit tests for XYChartConfig sort_by schema and multi-…
FrancescoCastaldi Sep 26, 2026
2d8474d
feat(mcp): implement add_xy_sort_config for non-temporal x-axis sorti…
FrancescoCastaldi Sep 26, 2026
c5d8d20
test(mcp): add unit tests for map_xy_config sort_by handling and temp…
FrancescoCastaldi Sep 26, 2026
00cf542
feat(mcp): enhance XYChartPlugin with sort_by column and metric norma…
FrancescoCastaldi Sep 26, 2026
5ee2ebc
test(mcp): add unit tests for XY chart sort_by column normalization a…
FrancescoCastaldi Sep 26, 2026
c22ccc3
fix(mcp): exclude covered metrics and labels from XYChartPlugin colum…
FrancescoCastaldi Sep 26, 2026
1ce4027
test(mcp): add unit tests for independent sort column extraction in X…
FrancescoCastaldi Sep 26, 2026
7cee031
test(mcp): add dataset validator tests for xy chart sort_by column re…
FrancescoCastaldi Sep 26, 2026
c3df883
feat(mcp): propagate x_axis_sort to query dictionary orderby in chart…
FrancescoCastaldi Sep 26, 2026
91d10c4
test(mcp): add unit tests for query dictionary orderby mapping from x…
FrancescoCastaldi Sep 26, 2026
2495731
feat(mcp): support saved metric and sql expression resolution in xy s…
FrancescoCastaldi Sep 26, 2026
2b8c015
test(mcp): add unit tests for sort_by pair format and saved_metric sc…
FrancescoCastaldi Sep 26, 2026
cc590bb
fix(mcp): support case-insensitive x-axis matching and sql expression…
FrancescoCastaldi Sep 26, 2026
804d291
test(mcp): add unit tests for case-insensitive x-axis and sql express…
FrancescoCastaldi Sep 26, 2026
02dbf36
fix(mcp): enhance query dictionary orderby resolution with case-insen…
FrancescoCastaldi Sep 26, 2026
55c19e3
test(mcp): add unit tests for case-insensitive and sqlExpression orde…
FrancescoCastaldi Sep 26, 2026
ff3dc4e
test(mcp): add dataset validator tests for saved metrics not in y and…
FrancescoCastaldi Sep 26, 2026
fdb3ea5
test(mcp): add validation pipeline integration tests for xy chart sor…
FrancescoCastaldi Sep 26, 2026
81af1e5
refactor(mcp): address review feedback on schema coercion, temporal g…
FrancescoCastaldi Sep 27, 2026
a8ab8a7
fix(mcp): validate x_axis_sort orderby target and avoid dropping sort…
FrancescoCastaldi Sep 27, 2026
bc6d9ff
Merge branch 'master' of https://github.com/apache/superset into fix/…
FrancescoCastaldi Sep 27, 2026
4f996ea
fix(mcp): resolve pre-commit mypy union, walrus formatting, and eof t…
FrancescoCastaldi Sep 27, 2026
916ffe2
style(mcp): apply auto-walrus to matched_y in xy plugin
FrancescoCastaldi Sep 27, 2026
81a94cc
fix(mcp): trim xy sort_by schema description to satisfy tool inventor…
FrancescoCastaldi Sep 27, 2026
db5e1b4
fix(mcp): address aminghadersohi review: sort_by validation, y-metric…
Sep 29, 2026
251ef2c
revert(mcp): restore confirmed sort_by handling (revert db5e1b4e)
Sep 29, 2026
9df716b
Merge branch 'master' of https://github.com/apache/superset into fix/…
FrancescoCastaldi Oct 2, 2026
fca3591
fix(mcp): align XYChartConfig sort_by schema annotation with pair format
FrancescoCastaldi Oct 3, 2026
65886f3
Merge remote-tracking branch 'upstream/master' into fix/mcp-xy-chart-…
FrancescoCastaldi Oct 3, 2026
ee9a0b4
fix(mcp): inherit OmittedMeansUnchanged in SortByConfig (#44573)
FrancescoCastaldi Oct 3, 2026
0f4150b
Merge remote-tracking branch 'upstream/master' into fix/mcp-xy-chart-…
FrancescoCastaldi Oct 9, 2026
d8a08f6
test(mcp): align xy bar explore test with post-processing sort and fi…
FrancescoCastaldi Oct 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions superset/mcp_service/chart/chart_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,28 @@ def extract_x_axis_col(form_data: dict[str, Any]) -> str | None:
return None


def _resolve_x_axis_sort_target(sort_col: str, metrics: list[Any]) -> Any:
"""Resolve x_axis_sort string against metrics to preserve metric dict/label."""
sort_lower = sort_col.lower()
for m in metrics:
if isinstance(m, str) and m.lower() == sort_lower:
return m
if isinstance(m, dict):
col_info = m.get("column")
col_name = (
col_info.get("column_name") if isinstance(col_info, dict) else None
)
label = m.get("label")
sql_expr = m.get("sqlExpression")
if (
(label and label.lower() == sort_lower)
or (col_name and col_name.lower() == sort_lower)
or (sql_expr and sql_expr.lower() == sort_lower)
):
return m
return sort_col


# Viz types whose buildQuery reads a single "Sort query by" metric from
# form_data['orderby'] (the dndSortByControl) rather than a sort flag.
_SORT_METRIC_VIZ_TYPES: frozenset[str] = frozenset({"bubble", "bubble_v2"})
Expand Down Expand Up @@ -1058,6 +1080,7 @@ def build_single_query_dict(
metrics: list[Any],
row_limit: int | None = None,
order_desc: bool | None = None,
is_timeseries: bool = False,
) -> dict[str, Any]:
"""Build one query entry for QueryContextFactory from form_data fields."""
qd: dict[str, Any] = {"columns": columns, "metrics": metrics}
Expand All @@ -1075,6 +1098,7 @@ def build_single_query_dict(
# metric descending. buildQuery derives this on the frontend; translate
# the flag here when there is no explicit ordering or a row_limit truncates
# an unordered result (dropping the heaviest rows rather than the top-N).
is_temporal = is_timeseries or bool(form_data.get("granularity_sqla"))
if form_data.get("sort_by_metric") and metrics and not qd.get("orderby"):
qd["orderby"] = [(metrics[0], False)]
elif sort_metric := resolve_sort_metric(form_data):
Expand All @@ -1086,6 +1110,22 @@ def build_single_query_dict(
order_desc if order_desc is not None else form_data.get("order_desc", True)
)
qd["orderby"] = [(sort_metric, not descending)]
elif (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unreachable since #43771: XY charts no longer call build_single_query_dict, and its four plugin callers never set x_axis_sort or is_timeseries. Consider dropping this branch, _resolve_x_axis_sort_target and the new param.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, please drop it, together with its build_single_query_dict x_axis_sort tests; XY sort is already covered through build_query_dicts_from_form_data.

not is_temporal
and form_data.get("x_axis_sort")
and not form_data.get("groupby")
and not qd.get("orderby")
):
sort_col = form_data["x_axis_sort"]
sort_asc = bool(form_data.get("x_axis_sort_asc", False))
sort_target = _resolve_x_axis_sort_target(sort_col, metrics)
col_labels = [
c if isinstance(c, str) else (c.get("label") or c.get("column_name"))
for c in columns
if isinstance(c, (str, dict))
]
if sort_target in metrics or sort_target in col_labels:
qd["orderby"] = [(sort_target, sort_asc)]
apply_form_data_filters_to_query(qd, form_data)
granularity = form_data.get("granularity", form_data.get("granularity_sqla"))
if granularity is not None:
Expand Down
106 changes: 106 additions & 0 deletions superset/mcp_service/chart/chart_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1291,6 +1291,111 @@ def add_orientation_config(form_data: Dict[str, Any], config: XYChartConfig) ->
form_data["orientation"] = config.orientation


def _match_y_metric_label(y_cols: list[ColumnRef], sort_lower: str) -> str | None:
"""Find matching metric label for sort_by among Y-axis metrics."""
aggregate_aliases = {"STDDEV": "STDDEV_SAMP", "VAR": "VAR_SAMP"}
for y_col in y_cols:
metric_obj = create_metric_object(y_col)
metric_label = (
metric_obj
if isinstance(metric_obj, str)
else (metric_obj.get("label") or "")
)
agg = y_col.aggregate or ""
norm_agg = aggregate_aliases.get(agg.upper(), agg.upper())
col_name = (y_col.name or "").lower()
col_label = (y_col.label or "").lower()
sql_expr = (y_col.sql_expression or "").lower()
metric_label_lower = metric_label.lower()

agg_matches: set[str] = set()
if agg and y_col.name:
agg_matches.add(f"{agg}({y_col.name})".lower())
if norm_agg and y_col.name:
agg_matches.add(f"{norm_agg}({y_col.name})".lower())

if (
sort_lower == col_name
or sort_lower == metric_label_lower
or (col_label and sort_lower == col_label)
or (sort_lower in agg_matches)
or (sql_expr and sort_lower == sql_expr)
):
return metric_label
return None


def add_xy_sort_config(
form_data: Dict[str, Any], config: XYChartConfig, x_is_temporal: bool
) -> None:
"""Apply sort configuration to form_data for XY charts.

When ``config.sort_by`` is present:
- If ``x_is_temporal``: records a warning in ``form_data["_mcp_warnings"]``
and does not override temporal sorting.
- If ``group_by`` is set: records a warning and ignores ``sort_by`` because
x-axis sort applies only to single-series charts in Superset.
- If the sort target does not match the x-axis column or a y-axis metric:
records a warning and does not apply ``x_axis_sort``.
- If valid and non-temporal: resolves the sort target to the corresponding
metric label (or dimension column name) and sets ``form_data["x_axis_sort"]``
and ``form_data["x_axis_sort_asc"]``.
When ``config.sort_by`` is not specified, maintains existing default behavior.
"""
if not config.sort_by:
return

sort_entry = config.sort_by
if not isinstance(sort_entry, SortByConfig):
from superset.mcp_service.chart.schemas import _coerce_sort_item

coerced = _coerce_sort_item(sort_entry)
if not isinstance(coerced, SortByConfig):
return
sort_entry = coerced

if x_is_temporal:
x_name = config.x.name if config.x else "x"
form_data.setdefault("_mcp_warnings", []).append(
f"sort_by='{sort_entry.column}' was ignored because the x-axis "
f"column '{x_name}' is temporal. Temporal charts sort "
f"chronologically by the time axis."
)
return

Comment thread
aminghadersohi marked this conversation as resolved.
Resolved
if form_data.get("groupby"):
form_data.setdefault("_mcp_warnings", []).append(
f"sort_by='{sort_entry.column}' was ignored because group_by is "
"set; the x-axis sort applies only to single-series charts."
)
return

sort_lower = sort_entry.column.lower()
x_name = (config.x.name or "").lower() if config.x else None
x_label = (config.x.label or "").lower() if config.x else None

# If sorting by the x-axis dimension itself (case-insensitive check)
if config.x and (
(x_name and sort_lower == x_name) or (x_label and sort_lower == x_label)
):
sort_target = config.x.name or config.x.label
else:
# Match against y metrics (by column name, metric label, agg expr, or sql)
matched_label = _match_y_metric_label(config.y, sort_lower)
if not matched_label:
form_data.setdefault("_mcp_warnings", []).append(
f"sort_by='{sort_entry.column}' was ignored: XY charts can "
"only sort by the x-axis or a y-axis metric."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth knowing rather than a change request: these three warnings only reach the caller from generate_chart, which pops _mcp_warnings into the response at superset/mcp_service/chart/tool/generate_chart.py:333. update_chart and update_chart_preview discard them instead (update_chart.py:376 and update_chart_preview.py:241), so update_chart on a chart that already has a group_by accepts sort_by, applies nothing and says nothing.

The discard predates this PR, but these are the first _mcp_warnings a user would actually act on, so it may be worth carrying them through on the update path as well.

)
return
sort_target = matched_label

form_data["x_axis_sort"] = sort_target
form_data["x_axis_sort_asc"] = sort_entry.ascending
form_data.pop("x_axis_sort_series_type", None)
form_data.pop("x_axis_sort_series_ascending", None)


def configure_temporal_handling(
form_data: Dict[str, Any],
x_is_temporal: bool,
Expand Down Expand Up @@ -1617,6 +1722,7 @@ def map_xy_config( # noqa: C901
add_color_scheme(form_data, config.color_scheme)
add_currency_format(form_data, config.currency_format)
add_xy_data_label_options(form_data, config, x_is_temporal)
add_xy_sort_config(form_data, config, x_is_temporal)

return form_data

Expand Down
155 changes: 155 additions & 0 deletions superset/mcp_service/chart/plugins/xy.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@
from superset.mcp_service.chart.chart_utils import (
_xy_chart_context,
_xy_chart_what,
create_metric_object,
map_xy_config,
)
from superset.mcp_service.chart.plugin import BaseChartPlugin
from superset.mcp_service.chart.schemas import (
ChartError,
ColumnRef,
SortByConfig,
VegaLitePreview,
XYChartConfig,
)
Expand All @@ -47,6 +49,149 @@
logger = logging.getLogger(__name__)


def _match_y_metric_name(raw_lower: str, y_configs: list[dict[str, Any]]) -> str | None:
for y_col in y_configs:
if y_col.get("label") and y_col["label"].lower() == raw_lower:
return y_col["label"]
if y_col.get("name") and y_col["name"].lower() == raw_lower:
return y_col.get("label") or y_col["name"]
if y_col.get("sql_expression") and y_col["sql_expression"].lower() == raw_lower:
return y_col.get("label") or y_col["sql_expression"]
agg = y_col.get("aggregate")
name = y_col.get("name")
if agg and name and f"{agg}({name})".lower() == raw_lower:
return y_col.get("label") or f"{agg.upper()}({name})"
return None


def _resolve_xy_sort_name_and_metric_status(
raw_name: str, config_dict: dict[str, Any], dataset_context: Any
) -> tuple[str, bool]:
raw_lower = raw_name.lower()
if matched_y := _match_y_metric_name(raw_lower, config_dict.get("y") or []):
return matched_y, False

x_col = config_dict.get("x")
if isinstance(x_col, dict):
if x_col.get("label") and x_col["label"].lower() == raw_lower:
return x_col["label"], False
if x_col.get("name") and x_col["name"].lower() == raw_lower:
return (
DatasetValidator.get_canonical_column_name(
x_col["name"], dataset_context
),
False,
)

if dataset_context and getattr(dataset_context, "available_metrics", None):
for m in dataset_context.available_metrics:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a blocker, but I do not think this branch can reach a working sort.

Probing generate_chart against a dataset whose saved metric total_sales is not in y: sort_by: "total_sales" is rejected at dataset validation with saved_metric_not_marked, because extract_column_refs reads the flag off the incoming config (saved_metric is still None there) while _normalize_xy_sort_by only sets it in the normalization layer, which runs after validation. Taking the error's advice and sending sort_by: {"column": "total_sales", "saved_metric": true} does pass validation, and then add_xy_sort_config drops it with sort_by='total_sales' was ignored: XY charts can only sort by the x-axis or a y-axis metric. So both spellings end with no sort, and the error message points at the one that warns.

The contract itself looks right to me, since sortOperator can only sort by the x-axis label or a label that is in the query's metrics. But that means this available_metrics lookup and the saved_metric=True ref it produces only ever buy a warning. Would it be simpler to drop them and have the validator say the target must be the x column or a y metric? Or is there a path where an independent saved metric does sort that I am missing?

if m.get("name") and m["name"].lower() == raw_lower:
return (
DatasetValidator.get_canonical_metric_name(
raw_name, dataset_context
),
True,
)

return DatasetValidator.get_canonical_column_name(raw_name, dataset_context), False


def _update_sort_by_column(
sort_item: Any,
config_dict: dict[str, Any],
dataset_context: Any,
) -> Any:
if isinstance(sort_item, dict) and "column" in sort_item:
canonical_name, is_saved = _resolve_xy_sort_name_and_metric_status(
sort_item["column"], config_dict, dataset_context
)
sort_item["column"] = canonical_name
if is_saved:
sort_item["saved_metric"] = True
return sort_item
if isinstance(sort_item, str):
canonical_name, is_saved = _resolve_xy_sort_name_and_metric_status(
sort_item, config_dict, dataset_context
)
return {
"column": canonical_name,
"ascending": False,
"saved_metric": is_saved or None,
}
if isinstance(sort_item, SortByConfig):
canonical_name, is_saved = _resolve_xy_sort_name_and_metric_status(
sort_item.column, config_dict, dataset_context
)
return SortByConfig(
column=canonical_name,
ascending=sort_item.ascending,
saved_metric=sort_item.saved_metric or (True if is_saved else None),
)
return sort_item


def _normalize_xy_sort_by(config_dict: dict[str, Any], dataset_context: Any) -> None:
"""Resolve canonical column or metric name for sort_by in XY charts."""
if not (sort_by := config_dict.get("sort_by")):
return

if isinstance(sort_by, list):
if sort_by:
sort_by[0] = _update_sort_by_column(
sort_by[0], config_dict, dataset_context
)
else:
config_dict["sort_by"] = _update_sort_by_column(
sort_by, config_dict, dataset_context
)


def _extract_sort_col_info(sort_entry: Any) -> tuple[str | None, bool]:
if isinstance(sort_entry, (list, tuple)) and sort_entry:
sort_entry = sort_entry[0]
if isinstance(sort_entry, SortByConfig):
return sort_entry.column, bool(sort_entry.saved_metric)
if isinstance(sort_entry, str):
return sort_entry, False
if isinstance(sort_entry, dict):
return sort_entry.get("column"), bool(sort_entry.get("saved_metric"))
return None, False


def _add_column_ref_names(ref: ColumnRef | None, names: set[str]) -> None:
"""Add lowercase name, label, and sql_expression of a column ref to names."""
if not ref:
return
if ref.name:
names.add(ref.name.lower())
if ref.label:
names.add(ref.label.lower())
if ref.sql_expression:
names.add(ref.sql_expression.lower())


def _collect_y_metric_names(y_cols: list[ColumnRef] | None) -> set[str]:
names: set[str] = set()
for y_col in y_cols or []:
_add_column_ref_names(y_col, names)
if y_col.aggregate and y_col.name:
names.add(f"{y_col.aggregate}({y_col.name})".lower())
metric_obj = create_metric_object(y_col)
label = metric_obj if isinstance(metric_obj, str) else metric_obj.get("label")
if label:
names.add(label.lower())
return names


def _get_covered_xy_names(config: XYChartConfig) -> set[str]:
"""Collect lowercase names and labels already covered in x, y, and group_by."""
covered = _collect_y_metric_names(config.y)
_add_column_ref_names(config.x, covered)
for gb in config.group_by or []:
_add_column_ref_names(gb, covered)
return covered


class XYChartPlugin(BaseChartPlugin):
"""Plugin for xy chart type (line, bar, area, scatter)."""

Expand Down Expand Up @@ -123,6 +268,14 @@ def extract_column_refs(self, config: Any) -> list[ColumnRef]:
if config.filters:
for f in config.filters:
refs.append(ColumnRef(name=f.column))
if config.sort_by:
sort_col, is_saved = _extract_sort_col_info(config.sort_by)
# Do not emit a separate column ref if sort_col refers to a
# column or metric already represented in x, y, or group_by.
# In particular, metric labels (e.g. "SUM(sales)") or custom labels
# are not physical dataset columns and would fail validation.
if sort_col and sort_col.lower() not in _get_covered_xy_names(config):
refs.append(ColumnRef(name=sort_col, saved_metric=is_saved))
return refs

def to_form_data(
Expand Down Expand Up @@ -155,6 +308,8 @@ def normalize_column_refs(self, config: Any, dataset_context: Any) -> Any:
for gb_col in config_dict.get("group_by") or []:
gb_col["name"] = get_canonical(gb_col["name"], dataset_context)

_normalize_xy_sort_by(config_dict, dataset_context)

DatasetValidator.normalize_filters(config_dict, dataset_context)
return XYChartConfig.model_validate(config_dict)

Expand Down
Loading
Loading