Skip to content

Commit 74fef29

Browse files
authored
fix(mcp): return safe get_table error codes (#46598)
1 parent 315896e commit 74fef29

8 files changed

Lines changed: 859 additions & 35 deletions

File tree

‎UPDATING.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,26 @@ assists people when migrating to a new version.
2424

2525
## Next
2626

27+
- MCP `get_table` query failures now populate `error_code`. Untyped dataset
28+
engine failures use `GENERIC_DB_ENGINE_ERROR`; signed-in users retain the
29+
specific `SupersetErrorType` code for typed errors, while guests receive
30+
`GENERIC_BACKEND_ERROR` for unsafe typed errors. Semantic provider faults
31+
and transport outages use `GENERIC_BACKEND_ERROR`. Rejected semantic
32+
queries use one of
33+
`UNSUPPORTED_QUERY`, `UNSUPPORTED_OFFSET`,
34+
`UNSUPPORTED_GROUP_OTHERS_METRIC`, `INVALID_FILTER`, or `INVALID_QUERY`.
35+
Malformed query results use `INVALID_QUERY_RESULT`; host-authored access and
36+
OAuth errors retain their Superset error codes, except a provider-raised
37+
OAuth error on a semantic view, which uses `GENERIC_BACKEND_ERROR`. These
38+
codes are intended to remain stable for MCP clients. Semantic rejections
39+
previously reported `error_type="QueryError"` and now report
40+
`"QueryValidationError"`; host query validation reports `"ValidationError"`.
41+
Transport outages remain `"QueryError"`. Raw `SQLAlchemyError` failures
42+
previously reported `"DatabaseError"` and now report `"QueryError"`.
43+
The old `"Query execution failed:"` and `"Database error:"` message prefixes
44+
are removed. Clients matching error types or message prefixes should handle
45+
these changes.
46+
2747
- Provider tests inheriting `SemanticProviderConformance` must supply four
2848
additional `semantic_query_cases`: `or_not_in`, `or_not_equals`, `or_not_like`,
2949
and `or_not_ilike`. These check the existing normalized exclusion-filter

‎superset/mcp_service/semantic_layer/schemas.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,10 @@ class SemanticLayerError(MCPBaseError):
4646
success: Literal[False] = False
4747

4848
@classmethod
49-
def create(cls, *, error: str, error_type: str) -> "SemanticLayerError":
50-
return cls(error=error, error_type=error_type)
49+
def create(
50+
cls, *, error: str, error_type: str, error_code: str | None = None
51+
) -> "SemanticLayerError":
52+
return cls(error=error, error_type=error_type, error_code=error_code)
5153

5254

5355
class ListSemanticViewsRequest(BaseModel):

‎superset/mcp_service/semantic_layer/tool/get_table.py‎

Lines changed: 96 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,14 @@
2828
from typing import Any, TYPE_CHECKING
2929

3030
from fastmcp import Context
31+
from flask_babel import gettext as _
3132
from sqlalchemy.exc import SQLAlchemyError
3233
from superset_core.mcp.decorators import tool, ToolAnnotations
34+
from superset_core.semantic_layers.errors import SemanticQueryErrorCode
3335
from superset_core.semantic_layers.types import Dimension
3436
from superset_core.semantic_layers.view import SemanticView as SemanticViewABC
3537

38+
from superset.commands.chart.exceptions import ChartDataQueryFailedError
3639
from superset.commands.exceptions import CommandException
3740
from superset.common.tabular_query import (
3841
build_query_dict,
@@ -58,13 +61,21 @@
5861
SemanticLayerError,
5962
)
6063
from superset.mcp_service.utils.cache_utils import get_cache_status_from_result
64+
from superset.mcp_service.utils.error_sanitization import sanitize_for_log
6165
from superset.mcp_service.utils.oauth2_utils import build_oauth2_redirect_message
6266
from superset.mcp_service.utils.response_utils import format_data_columns
67+
from superset.mcp_service.utils.tool_errors import (
68+
contains_provider_fault,
69+
public_query_error,
70+
)
6371
from superset.semantic_layers.access import (
6472
is_semantic_layers_enabled,
6573
SemanticLayersDisabledError,
6674
)
67-
from superset.semantic_layers.exceptions import normalize_provider_request_errors
75+
from superset.semantic_layers.exceptions import (
76+
normalize_provider_request_errors,
77+
provider_code,
78+
)
6879
from superset.utils import json
6980

7081
if TYPE_CHECKING:
@@ -207,11 +218,20 @@ def _resolve_external_view(
207218
error_type="ConfigurationError",
208219
)
209220
try:
210-
implementation.validate_selection_version(request.semantic_selection_version)
211-
except ValueError as ex:
221+
with provider_code():
222+
implementation.validate_selection_version(
223+
request.semantic_selection_version
224+
)
225+
except ValueError:
212226
return SemanticLayerError.create(
213-
error=str(ex),
227+
error=_(
228+
"Saved semantic selections use a different identity format. "
229+
"Reset the chart selections, explicitly reselect its metrics "
230+
"and dimensions, and save the chart. Display titles cannot be "
231+
"automatically mapped to member IDs."
232+
),
214233
error_type="ValidationError",
234+
error_code=SemanticQueryErrorCode.INVALID_QUERY.value,
215235
)
216236

217237
return _resolve_external_view_metadata(request, view)
@@ -247,9 +267,10 @@ def _resolve_external_view_metadata(
247267
error_type="ValidationError",
248268
)
249269

250-
valid_grains: dict[str, dict[str, str]] = _grains_by_column(
251-
view.implementation.get_dimensions()
252-
)
270+
implementation: SemanticViewABC = view.implementation
271+
with provider_code():
272+
dimensions: set[Dimension] = implementation.get_dimensions()
273+
valid_grains: dict[str, dict[str, str]] = _grains_by_column(dimensions)
253274
grain_column: str | None = request.time_column
254275
if request.time_grain:
255276
selected: list[str] = sorted(set(request.dimensions) & valid_dttm_columns)
@@ -525,9 +546,36 @@ async def _run_get_table_query(
525546
query_duration_ms = int((time.time() - start_time) * 1000)
526547

527548
if result_error := validate_query_result_envelope(result):
549+
if result_error.error_type == "InvalidQueryResult":
550+
logger.warning(
551+
"get_table query failed error_code=%s exc=%s",
552+
"INVALID_QUERY_RESULT",
553+
"InvalidQueryResult",
554+
)
555+
return SemanticLayerError.create(
556+
error=result_error.error,
557+
error_type="InvalidQueryResult",
558+
error_code="INVALID_QUERY_RESULT",
559+
)
560+
error: ChartDataQueryFailedError = ChartDataQueryFailedError(result_error.error)
561+
error_code, public_message, error_type = public_query_error(
562+
error, semantic=not is_builtin
563+
)
564+
logger.warning(
565+
"get_table query failed error_code=%s exc=%s",
566+
error_code,
567+
type(error).__name__,
568+
)
569+
if is_builtin:
570+
logger.debug(
571+
"get_table query detail: %s", sanitize_for_log(result_error.error)
572+
)
573+
else:
574+
logger.debug("get_table semantic query detail: %s", type(error).__name__)
528575
return SemanticLayerError.create(
529-
error=result_error.error,
530-
error_type=result_error.error_type,
576+
error=public_message,
577+
error_type=error_type,
578+
error_code=error_code,
531579
)
532580

533581
await ctx.report_progress(5, 5, "Formatting results")
@@ -665,34 +713,57 @@ async def _get_table(
665713

666714
except OAuth2RedirectError as exc:
667715
redirect_msg = build_oauth2_redirect_message(exc)
668-
await ctx.error("OAuth2 redirect required: %s" % redirect_msg)
716+
error_code: str = exc.error.error_type.value
717+
logger.warning(
718+
"get_table query failed error_code=%s exc=%s",
719+
error_code,
720+
type(exc).__name__,
721+
)
722+
await ctx.error("OAuth2 redirect required")
669723
return SemanticLayerError.create(
670724
error=redirect_msg,
671725
error_type="OAuth2Redirect",
726+
error_code=error_code,
672727
)
673728

674729
except OAuth2Error as exc:
675-
error_text = bounded_exception_message(exc)
676-
await ctx.error("OAuth2 error: %s" % error_text)
730+
error_code, error_text, _error_type = public_query_error(
731+
exc, semantic=not is_builtin
732+
)
733+
logger.warning(
734+
"get_table query failed error_code=%s exc=%s",
735+
error_code,
736+
type(exc).__name__,
737+
)
738+
logger.debug("get_table query detail: %s", sanitize_for_log(error_text))
739+
await ctx.error("OAuth2 error: %s" % error_code)
677740
return SemanticLayerError.create(
678741
error=f"OAuth2 authentication error: {error_text}",
679742
error_type="OAuth2Error",
743+
error_code=error_code,
680744
)
681745

682-
except (CommandException, SupersetException) as exc:
683-
error_text = bounded_exception_message(exc)
684-
await ctx.error("Query failed: %s" % error_text)
685-
return SemanticLayerError.create(
686-
error=f"Query execution failed: {error_text}",
687-
error_type="QueryError",
746+
except (CommandException, SupersetException, SQLAlchemyError) as exc:
747+
error_code, public_message, error_type = public_query_error(
748+
exc, semantic=not is_builtin
688749
)
689-
690-
except SQLAlchemyError as exc:
691-
error_text = bounded_exception_message(exc)
692-
await ctx.error("Database error: %s" % error_text)
750+
logger.warning(
751+
"get_table query failed error_code=%s exc=%s",
752+
error_code,
753+
type(exc).__name__,
754+
)
755+
if contains_provider_fault(exc):
756+
logger.debug("get_table provider failure: %s", type(exc).__name__)
757+
else:
758+
logger.debug(
759+
"get_table query detail: %s",
760+
sanitize_for_log(bounded_exception_message(exc)),
761+
)
762+
await ctx.error("Query failed: %s" % error_code)
693763
return SemanticLayerError.create(
694-
error=f"Database error: {error_text}",
695-
error_type="DatabaseError",
764+
error=public_message,
765+
error_type=error_type,
766+
error_code=error_code,
696767
)
697768

698769

@@ -701,6 +772,7 @@ def _semantic_table_internal_error() -> SemanticLayerError:
701772
return SemanticLayerError.create(
702773
error="An internal error occurred while querying the semantic table.",
703774
error_type="InternalError",
775+
error_code="GENERIC_BACKEND_ERROR",
704776
)
705777

706778

0 commit comments

Comments
 (0)