You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ms...@apache.org on 2026/04/20 10:18:58 UTC

(superset) branch msyavuz/fix/mcp-generate-chart-structured-errors created (now 5eb029d8854)

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

msyavuz pushed a change to branch msyavuz/fix/mcp-generate-chart-structured-errors
in repository https://gitbox.apache.org/repos/asf/superset.git


      at 5eb029d8854 fix(mcp): surface structured errors for generate_chart validation failures

This branch includes the following new commits:

     new 5eb029d8854 fix(mcp): surface structured errors for generate_chart validation failures

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(superset) 01/01: fix(mcp): surface structured errors for generate_chart validation failures

Posted by ms...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

msyavuz pushed a commit to branch msyavuz/fix/mcp-generate-chart-structured-errors
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 5eb029d8854e717e801c8e57f5473ee2a8b9d5af
Author: Mehmet Salih Yavuz <sa...@proton.me>
AuthorDate: Mon Apr 20 13:18:42 2026 +0300

    fix(mcp): surface structured errors for generate_chart validation failures
    
    Config-level failures in generate_chart (compare_lag without show_trendline,
    unknown fields, etc.) previously surfaced as VALIDATION_PIPELINE_ERROR with
    an empty message/details/suggestions because parse_chart_config wrapped the
    PydanticValidationError in a bare ValueError caught by the pipeline's
    except-all, and the "validation_error" template referenced by that fallback
    didn't exist in ChartErrorBuilder.TEMPLATES.
    
    - Unwrap the PydanticValidationError from parse_chart_config via __cause__
      and build a CHART_CONFIG_VALIDATION_ERROR with field paths, real
      messages, and chart-type-specific suggestions.
    - Add the missing validation_error template so the outer catch-all always
      produces a populated message/details body.
    - Return a structured error shape (error_type/message/details/suggestions)
      from get_chart_type_schema when an unknown chart_type is requested.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <no...@anthropic.com>
---
 .../chart/tool/get_chart_type_schema.py            |  25 ++++-
 superset/mcp_service/chart/validation/pipeline.py  |  93 ++++++++++++++-
 superset/mcp_service/utils/error_builder.py        |  13 +++
 .../chart/tool/test_get_chart_type_schema.py       |  18 +++
 .../validation/test_pipeline_structured_errors.py  | 125 +++++++++++++++++++++
 5 files changed, 266 insertions(+), 8 deletions(-)

diff --git a/superset/mcp_service/chart/tool/get_chart_type_schema.py b/superset/mcp_service/chart/tool/get_chart_type_schema.py
index dc21f3c6203..896d54d3099 100644
--- a/superset/mcp_service/chart/tool/get_chart_type_schema.py
+++ b/superset/mcp_service/chart/tool/get_chart_type_schema.py
@@ -126,14 +126,27 @@ def _get_chart_type_schema_impl(
     """Pure logic for chart type schema lookup — no auth, no decorators."""
     adapter = _CHART_TYPE_ADAPTERS.get(chart_type)
     if adapter is None:
+        # Return a structured error matching ChartGenerationError's shape so
+        # MCP clients consuming the response see a populated error_type,
+        # message, details, and suggestions rather than a bare dict.
+        valid_types_str = ", ".join(VALID_CHART_TYPES)
         return {
-            "error": f"Unknown chart_type: {chart_type!r}",
+            "error": {
+                "error_type": "invalid_chart_type",
+                "message": f"Unknown chart_type: {chart_type!r}",
+                "details": (
+                    f"Chart type {chart_type!r} is not supported. "
+                    f"Must be one of: {valid_types_str}."
+                ),
+                "suggestions": [
+                    f"Use one of: {valid_types_str}",
+                    "Check spelling and ensure lowercase",
+                    "Call this tool again with a valid chart_type to see "
+                    "its schema and examples",
+                ],
+                "error_code": "INVALID_CHART_TYPE",
+            },
             "valid_chart_types": VALID_CHART_TYPES,
-            "hint": (
-                "Use one of the valid chart_type values listed above. "
-                "Call this tool again with a valid chart_type to see "
-                "its schema and examples."
-            ),
         }
 
     schema = adapter.json_schema()
diff --git a/superset/mcp_service/chart/validation/pipeline.py b/superset/mcp_service/chart/validation/pipeline.py
index 6923de0bd0b..b7ddff84164 100644
--- a/superset/mcp_service/chart/validation/pipeline.py
+++ b/superset/mcp_service/chart/validation/pipeline.py
@@ -23,6 +23,8 @@ Orchestrates schema, dataset, and runtime validations.
 import logging
 from typing import Any, Dict, List, Tuple
 
+from pydantic import ValidationError as PydanticValidationError
+
 from superset.mcp_service.chart.schemas import (
     ChartConfig,
     GenerateChartRequest,
@@ -73,6 +75,79 @@ def _get_generic_error_message(error_str: str) -> str | None:
     return None
 
 
+def _unwrap_pydantic_error(error: Exception) -> PydanticValidationError | None:
+    """Return the underlying PydanticValidationError, walking the cause chain.
+
+    parse_chart_config() re-raises Pydantic failures as ValueError with a hint
+    appended, so the structured error sits in ``__cause__``.
+    """
+    cur: BaseException | None = error
+    while cur is not None:
+        if isinstance(cur, PydanticValidationError):
+            return cur
+        cur = cur.__cause__
+    return None
+
+
+def _build_chart_config_validation_error(
+    pydantic_error: PydanticValidationError,
+    chart_type: str | None,
+) -> ChartGenerationError:
+    """Translate a Pydantic config-level failure into a structured error.
+
+    Surfaces the real field path, message, and (when possible) the offending
+    value so callers can self-correct instead of seeing an opaque
+    VALIDATION_PIPELINE_ERROR.
+    """
+    errors = pydantic_error.errors()
+    messages: list[str] = []
+    validation_errors_list = []
+    from superset.mcp_service.common.error_schemas import ValidationError
+
+    for err in errors[:5]:
+        # Strip the discriminator tag ('big_number', 'xy', etc.) from loc — it
+        # is part of the tagged-union machinery, not a user-facing field path.
+        loc_parts = [p for p in err.get("loc", ()) if p != chart_type]
+        loc = " -> ".join(str(p) for p in loc_parts) or "config"
+        msg = err.get("msg", "Validation failed")
+        # Pydantic prefixes value errors with "Value error, " — drop it.
+        if msg.startswith("Value error, "):
+            msg = msg[len("Value error, ") :]
+        messages.append(f"{loc}: {msg}" if loc != "config" else msg)
+        validation_errors_list.append(
+            ValidationError(
+                field=loc,
+                provided_value=err.get("input", None),
+                error_type=err.get("type", "value_error"),
+                message=msg,
+            )
+        )
+
+    details = " | ".join(messages) if messages else str(pydantic_error)
+    first_msg = messages[0] if messages else "Chart configuration validation failed"
+
+    suggestions = [
+        "Review the error message above — it identifies the offending field",
+        "Call get_chart_type_schema with your chart_type to see valid fields",
+        "Check that field names match exactly (case-sensitive)",
+    ]
+    if chart_type:
+        suggestions.insert(
+            0,
+            f"Inspect the '{chart_type}' schema with "
+            f"get_chart_type_schema(chart_type='{chart_type}')",
+        )
+
+    return ChartGenerationError(
+        error_type="chart_config_validation_error",
+        message=first_msg,
+        details=details,
+        suggestions=suggestions,
+        validation_errors=validation_errors_list,
+        error_code="CHART_CONFIG_VALIDATION_ERROR",
+    )
+
+
 def _sanitize_validation_error(error: Exception) -> str:
     """SECURITY FIX: Sanitize validation errors to prevent disclosure."""
     error_str = str(error)
@@ -173,8 +248,22 @@ class ValidationPipeline:
                 return ValidationResult(is_valid=False, error=error)
 
             # Parse the raw config dict into a typed ChartConfig for
-            # downstream validators that need typed access.
-            typed_config = parse_chart_config(request.config)
+            # downstream validators that need typed access.  Handle the
+            # Pydantic failure explicitly so field-level errors surface as
+            # structured responses instead of opaque VALIDATION_PIPELINE_ERROR.
+            try:
+                typed_config = parse_chart_config(request.config)
+            except ValueError as config_exc:
+                pydantic_err = _unwrap_pydantic_error(config_exc)
+                if pydantic_err is None:
+                    raise
+                chart_type = (
+                    request.config.get("chart_type")
+                    if isinstance(request.config, dict)
+                    else None
+                )
+                error = _build_chart_config_validation_error(pydantic_err, chart_type)
+                return ValidationResult(is_valid=False, error=error)
 
             # Fetch dataset context once and reuse across validation layers
             dataset_context = ValidationPipeline._get_dataset_context(
diff --git a/superset/mcp_service/utils/error_builder.py b/superset/mcp_service/utils/error_builder.py
index 61df3eb9108..215b0dc6c7c 100644
--- a/superset/mcp_service/utils/error_builder.py
+++ b/superset/mcp_service/utils/error_builder.py
@@ -174,6 +174,19 @@ class ChartErrorBuilder:
                 "Modify your data selection or aggregation",
             ],
         },
+        # Validation system fallback — used by the pipeline catch-all.
+        # Keeping {reason} in the template lets the sanitized message flow
+        # through so callers never receive an empty error body.
+        "validation_error": {
+            "message": "Chart validation failed: {reason}",
+            "details": "{reason}",
+            "suggestions": [
+                "Check the reported field names, types, and required values",
+                "Call get_chart_type_schema with your chart_type to see the "
+                "full schema",
+                "Refer to the chart://configs resource for config examples",
+            ],
+        },
         # Chart generation errors
         "generation_failed": {
             "message": "Chart generation failed: {reason}",
diff --git a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_type_schema.py b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_type_schema.py
index f7f2d166a5a..1da1b587b01 100644
--- a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_type_schema.py
+++ b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_type_schema.py
@@ -70,6 +70,24 @@ class TestGetChartTypeSchema:
         assert "valid_chart_types" in result
         assert result["valid_chart_types"] == VALID_CHART_TYPES
 
+    def test_invalid_chart_type_returns_structured_error(self) -> None:
+        """Invalid chart_type must return a populated, structured error body.
+
+        Without this guarantee, MCP clients see an empty/unstructured payload
+        and cannot self-correct (Eval 26 Test 26.5).
+        """
+        result = _call_schema("nonexistent")
+        err = result["error"]
+        assert isinstance(err, dict)
+        assert err["error_type"] == "invalid_chart_type"
+        assert err["error_code"] == "INVALID_CHART_TYPE"
+        assert "nonexistent" in err["message"]
+        assert err["details"]
+        assert err["suggestions"]
+        # Suggestions must name at least one valid chart type so callers know
+        # what to try next.
+        assert any(vt in " ".join(err["suggestions"]) for vt in VALID_CHART_TYPES)
+
     def test_examples_match_chart_type(self) -> None:
         result = _call_schema("pie")
         for example in result["examples"]:
diff --git a/tests/unit_tests/mcp_service/chart/validation/test_pipeline_structured_errors.py b/tests/unit_tests/mcp_service/chart/validation/test_pipeline_structured_errors.py
new file mode 100644
index 00000000000..4c4b1657e31
--- /dev/null
+++ b/tests/unit_tests/mcp_service/chart/validation/test_pipeline_structured_errors.py
@@ -0,0 +1,125 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Structured-error guarantees for the chart validation pipeline.
+
+Regression tests for scenarios where ``generate_chart`` previously returned
+a generic ``VALIDATION_PIPELINE_ERROR`` with empty message / details /
+suggestions (Eval 21.4/21.7/21.9, Eval 23.6).
+"""
+
+from unittest.mock import patch
+
+from superset.mcp_service.chart.validation.pipeline import ValidationPipeline
+
+
+def test_compare_lag_without_trendline_returns_structured_error() -> None:
+    """compare_lag set without show_trendline must surface a specific error.
+
+    Without the fix, parse_chart_config raised a generic ValueError caught by
+    the pipeline's except-all, producing an empty VALIDATION_PIPELINE_ERROR.
+    """
+    result = ValidationPipeline.validate_request_with_warnings(
+        {
+            "dataset_id": 1,
+            "config": {
+                "chart_type": "big_number",
+                "metric": {"name": "revenue", "aggregate": "SUM"},
+                "compare_lag": 1,
+            },
+        }
+    )
+    assert result.is_valid is False
+    assert result.error is not None
+    assert result.error.error_code == "CHART_CONFIG_VALIDATION_ERROR"
+    assert result.error.error_type == "chart_config_validation_error"
+    assert "compare_lag" in result.error.message
+    assert "show_trendline" in result.error.message
+    assert result.error.suggestions
+    # Suggestions must nudge the caller toward get_chart_type_schema for the
+    # specific chart type they were attempting.
+    assert any("big_number" in s for s in result.error.suggestions)
+
+
+def test_unknown_field_returns_structured_error() -> None:
+    """Unknown config fields must list valid alternatives, not fail silently."""
+    result = ValidationPipeline.validate_request_with_warnings(
+        {
+            "dataset_id": 1,
+            "config": {
+                "chart_type": "big_number",
+                "metric": {"name": "revenue", "aggregate": "SUM"},
+                "bogus_field": "whatever",
+            },
+        }
+    )
+    assert result.is_valid is False
+    assert result.error is not None
+    assert result.error.error_code == "CHART_CONFIG_VALIDATION_ERROR"
+    assert "bogus_field" in result.error.message
+    assert result.error.suggestions
+    assert result.error.validation_errors
+
+
+def test_outer_fallback_populates_message_and_suggestions() -> None:
+    """Unexpected exceptions must still yield a non-empty structured error.
+
+    Even when an unrelated exception bubbles up, the generic fallback must
+    include the sanitized reason plus actionable suggestions.
+    """
+    with patch(
+        "superset.mcp_service.chart.validation.schema_validator."
+        "SchemaValidator.validate_request",
+        side_effect=RuntimeError("boom"),
+    ):
+        result = ValidationPipeline.validate_request_with_warnings(
+            {"dataset_id": 1, "config": {"chart_type": "xy"}}
+        )
+    assert result.is_valid is False
+    assert result.error is not None
+    assert result.error.error_code == "VALIDATION_PIPELINE_ERROR"
+    assert result.error.message
+    assert result.error.message != "An error occurred"
+    assert "boom" in result.error.message or "boom" in result.error.details
+    assert result.error.suggestions
+
+
+def test_show_trendline_without_temporal_column_still_structured() -> None:
+    """Pre-validate's structured error path must remain intact."""
+    result = ValidationPipeline.validate_request_with_warnings(
+        {
+            "dataset_id": 1,
+            "config": {
+                "chart_type": "big_number",
+                "metric": {"name": "revenue", "aggregate": "SUM"},
+                "show_trendline": True,
+            },
+        }
+    )
+    assert result.is_valid is False
+    assert result.error is not None
+    assert result.error.error_code == "MISSING_TEMPORAL_COLUMN"
+
+
+def test_invalid_chart_type_still_structured() -> None:
+    """Pre-validate's invalid_chart_type path must remain intact."""
+    result = ValidationPipeline.validate_request_with_warnings(
+        {"dataset_id": 1, "config": {"chart_type": "not_a_real_type"}}
+    )
+    assert result.is_valid is False
+    assert result.error is not None
+    assert result.error.error_code == "INVALID_CHART_TYPE"