Skip to content

fix(mcp): stop sending raw exception text to MCP clients - #46611

Draft
aminghadersohi wants to merge 17 commits into
masterfrom
mcp-sanitize-tool-errors
Draft

aminghadersohi wants to merge 17 commits into
masterfrom
mcp-sanitize-tool-errors

Conversation

@aminghadersohi

@aminghadersohi aminghadersohi commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

SUMMARY

MCP tools put raw exception text into tool responses and into ctx.error / ctx.warning notifications, which FastMCP sends to the client. That text can come from SQLAlchemy, a database driver, the warehouse or a semantic-layer provider, so it can include SQL, bound parameters, hostnames or connection details. get_chart_data is on the embedded guest allow-list (MCP_GUEST_ALLOWED_TOOLS), and it returned warehouse error text to embedded guests. For the same failure, /api/v1/chart/data passes the message through sanitize_error_message.

This PR makes every MCP tool report errors with the rule the HTTP API already uses:

  • A failed data query (get_chart_data saved and unsaved paths, get_chart_preview, the unsaved preview path, query_dataset, the chart compile check) is classified by public_query_error, the same rule as /api/v1/chart/data. Signed-in users get the engine text, which they need to correct the query. Embedded guests get the generic message unless the error type is in SAFE_ERROR_TYPES, including for semantic-view queries, which pass semantic=True.
  • An exception raised inside a semantic provider call (is_provider_fault) is classified with semantic=True on every tool path, whatever the caller passes, so provider text never reaches the client.
  • Any other exception Superset raised (SupersetException, CommandException) keeps its message and SupersetErrorType. Embedded guests only see it when the type is in SAFE_ERROR_TYPES.
  • A ValueError raised by one of Superset's validators of the caller's own arguments (superset.utils.date_parser, the MCP time_range validator, the MCP chart mapper and query builder in chart_utils / chart_helpers, the chart plugins) keeps its text, for example "From date cannot be larger than to date" or "Table chart must have at least one column". The caller needs that text to correct the request. Embedded guests still get the generic message. The innermost traceback frame decides where the error was raised.
  • Anything else (SQLAlchemy, drivers, libraries) gets a fixed message. The full exception is logged server-side only.

Shared helper. The helper lives in superset/mcp_service/utils/tool_errors.py. This module is shared with #46598, which adds it for get_table. The first 141 lines of the file are byte-identical to that PR's version, and so are its is_provider_fault rename hunks in superset/semantic_layers/exceptions.py. This PR only appends new functions below public_query_error: safe_error, tool_error_message, log_tool_exception, internal_error_response and report_tool_error. Whichever PR merges second gets a git add/add conflict in that file. The conflict is limited to the appended block: keep both sides. I checked this with a local merge of both PR heads. The only conflict was the appended block of tool_errors.py, and after resolving it the scan, get_table and helper tests pass (312 passed). get_table itself is not changed here.

Call sites changed (paths under superset/mcp_service):

  • annotation_layer: get_annotation_layer_info, get_layer_annotation_info, list_annotation_layers, list_layer_annotations
  • chart: chart_utils, compile, plugins/geographic, preview_utils, delete_chart, generate_chart, get_chart_data, get_chart_info, get_chart_preview, get_chart_sql, list_charts, restore_chart, update_chart, update_chart_preview, validation/pipeline
  • dashboard: add_chart_to_existing_dashboard, apply_dashboard_filters, delete_dashboard, duplicate_dashboard, generate_dashboard, get_dashboard_data, get_dashboard_datasets, get_dashboard_info, get_dashboard_layout, manage_native_filters, remove_chart_from_dashboard, restore_dashboard
  • database: get_database_info, list_databases
  • dataset: create_dataset, create_dataset_column, create_dataset_metric, create_virtual_dataset, delete_dataset, delete_dataset_column, delete_dataset_metric, get_dataset_info, list_datasets, query_dataset, restore_dataset, update_dataset, update_dataset_column, update_dataset_metric
  • explore: generate_explore_link
  • query: get_query_info, list_queries
  • report: get_report_info, list_reports
  • rls: get_rls_filter_info, list_rls_filters
  • role: get_role_info, list_roles
  • saved_query: get_saved_query_info, list_saved_queries
  • sql_lab: execute_sql, open_sql_lab_with_context, save_sql_query
  • system: get_instance_info
  • tag: get_tag_info, list_tags
  • task: get_task_info, list_tasks
  • theme: create_theme, get_theme_info, list_themes
  • user: get_user_info, list_users
  • shared: mcp_core, utils/schema_utils

Not changed, by design:

  • The get_table handlers are converted by fix(mcp): return safe get_table error codes #46598. They are listed in PENDING_HANDLERS, which the stale-entry check does not report, so either PR can merge first.
  • middleware.py (the last-resort handler) and jwt_verifier.py already keep exception text server-side.
  • Handlers whose text Superset writes about the caller's own input (pydantic validation, date-range parsing, JSON argument parsing) are listed in HOST_MESSAGE_HANDLERS, each with a reason.

Guard against regressions. tests/unit_tests/mcp_service/test_tool_error_text.py parses every module under superset/mcp_service. It fails when an except handler, or a function that takes an exception, turns the exception into text (str(e), f"{e}", "%s" % e, e.message, bounded_exception_message(e), ...) that goes to a tool response or a ctx notification without going through these helpers.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A (backend only).

Before, an embedded guest calling get_chart_data on a chart whose query fails receives Error retrieving chart data: Error: relation "<schema>.<table>" does not exist. After, the guest receives Error retrieving chart data: An error occurred while fetching the data., and a signed-in user still gets the engine text.

TESTING INSTRUCTIONS

pytest tests/unit_tests/mcp_service tests/unit_tests/semantic_layers -m "not manual and not llm_compliance"

Regression tests that fail on master and pass on this branch:

  • tests/unit_tests/mcp_service/test_tool_error_text.py::test_mcp_service_sends_no_exception_text_to_clients: the static scan. On master it lists the raw-text call sites.

  • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py::test_chart_data_engine_error_is_redacted_for_guests: covers saved and unsaved charts, failed and invalid queries. Guest cases fail on master; signed-in cases keep the engine text and pass on both.

  • tests/unit_tests/mcp_service/dataset/tool/test_query_dataset.py::test_query_dataset_superset_error_text_for_principal (guest cases) and ::test_query_dataset_failure_text_not_sent (SQLAlchemy and other ValueError cases).

  • tests/unit_tests/mcp_service/utils/test_tool_errors.py: the helper rules, including query=True against public_query_error, semantic provider faults, and validator ValueErrors versus library ValueErrors.

  • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py::test_semantic_chart_validation_text_is_redacted_for_guests.

  • tests/unit_tests/mcp_service/chart/test_preview_utils.py::test_generate_preview_hides_semantic_provider_text and tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py::TestCompileChart::test_compile_chart_hides_semantic_provider_text.

Tests that keep caller guidance (they pass on master, which returned str(e), and they pin that this change keeps the text):

  • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py::test_chart_data_time_range_error_keeps_date_parser_guidance
  • tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py::test_generate_chart_failure_keeps_chart_config_guidance
  • tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py::TestCompileChart::test_compile_chart_time_range_error_keeps_guidance
  • tests/unit_tests/mcp_service/chart/tool/test_generate_chart.py::TestCompileChart::test_compile_chart_chart_config_error_keeps_guidance

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

MCP tools put exception text into tool responses and ctx log notifications
at about 35 call sites. get_chart_data and query_dataset are reachable by
embedded guests and returned warehouse error text to them, while
/api/v1/chart/data passes the same message through sanitize_error_message.
Other catch-all handlers sent str(exc) from SQLAlchemy and drivers to every
caller.

Add one helper, safe_error, that maps an exception to a SupersetErrorType
and a client-safe message with the HTTP rule: Superset's own message (the
engine error of a failed query) for signed-in users, the generic message for
embedded guests unless the error type is one Superset writes itself, and a
fixed message for exceptions Superset did not raise. internal_error_response
and report_tool_error build tool responses and ctx notifications on it, and
log the full exception server-side.

A static test scans the MCP service for exception text formatted into
client output outside these helpers.
Build the tool error helpers on the query-error classification in
superset/mcp_service/utils/tool_errors.py, whose public_query_error maps a
failed data query to an error code and a safe message with the rule of
/api/v1/chart/data. get_chart_data, query_dataset and the chart compile check
pass query=True (and semantic=True for a semantic view) so their responses
and ctx notifications use that rule. Superset exceptions it does not classify
keep the general rule, and raw SQLAlchemy errors keep a fixed message.
The tool error helpers read is_sanitization_required through superset.utils.error_sanitization, like sanitize_error_message, so one patch covers the general and the query rule.
PENDING_HANDLERS covers get_table handlers that a separate change moves to public_query_error. The stale-entry test no longer reports those entries, so the test passes whichever change lands first.
A ValueError raised by superset.utils.date_parser, the MCP chart mapper or a chart plugin describes the caller's time range or chart config, and the caller needs it to fix the request. safe_error reports it like a Superset message (the generic text for embedded guests); a ValueError raised anywhere else still gets the fixed message.
safe_error classifies an exception raised inside a semantic provider call with public_query_error(semantic=True) whatever the caller passes, so provider text never reaches the client. Validator ValueErrors about the caller's arguments are checked first and keep their text on semantic queries too. The chart compile check, the unsaved preview path and the get_chart_preview strategies report query failures with query=True and the semantic flag of their datasource, like get_chart_data.
public_query_error returns a semantic query's validation or rejection text without sanitize_error_message. On the query path safe_error gives an embedded guest the generic message unless the error type is one Superset writes itself, as /api/v1/chart/data does for the same exceptions; signed-in users keep the text.
ValueErrors raised by chart_helpers (for example a missing Deck.gl spatial setting) and by the time_range validator describe the caller's own chart config or time range. Add both modules to HOST_VALUE_ERROR_MODULES so the compile check and get_chart_sql return that text again.
@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 28.28947% with 327 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.79%. Comparing base (e017ab8) to head (8128f79).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
superset/mcp_service/utils/tool_errors.py 34.31% 66 Missing and 1 partial ⚠️
superset/mcp_service/middleware.py 0.00% 24 Missing ⚠️
superset/mcp_service/dataset/tool/query_dataset.py 21.73% 18 Missing ⚠️
superset/mcp_service/chart/tool/get_chart_data.py 13.33% 13 Missing ⚠️
superset/mcp_service/chart/compile.py 25.00% 12 Missing ⚠️
superset/mcp_service/chart/tool/get_chart_sql.py 7.69% 12 Missing ⚠️
..._service/dashboard/tool/apply_dashboard_filters.py 21.42% 11 Missing ⚠️
superset/mcp_service/auth.py 23.07% 10 Missing ⚠️
...perset/mcp_service/chart/tool/get_chart_preview.py 16.66% 10 Missing ⚠️
...set/mcp_service/chart/tool/update_chart_preview.py 12.50% 7 Missing ⚠️
... and 69 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #46611      +/-   ##
==========================================
- Coverage   65.80%   65.79%   -0.01%     
==========================================
  Files        3146     3146              
  Lines      220020   220292     +272     
  Branches    52111    52157      +46     
==========================================
+ Hits       144781   144950     +169     
- Misses      71807    71909     +102     
- Partials     3432     3433       +1     
Flag Coverage Δ
hive 33.68% <28.28%> (+0.04%) ⬆️
mysql 51.84% <28.28%> (+0.01%) ⬆️
postgres 51.86% <28.28%> (+<0.01%) ⬆️
presto 35.36% <28.28%> (+0.03%) ⬆️
python 52.16% <28.28%> (+<0.01%) ⬆️
sqlite 51.56% <28.28%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

A tool that reports an error and re-raises left the response text to the
middleware, which echoed the exception text for guests and for exceptions
Superset did not write. The error handler and the compatibility boundary now
render client text through the shared classification, and a provider-marked
ValueError from a host validator gets the generic message.
The tool runs under its own app context, so the error middleware could not
see that the call resolved to an embedded guest and rendered Superset text for
it. The resolved principal now survives the context pop, as the user id does,
and the response redaction uses it.
@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Nov 27, 2026
@netlify

netlify Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 8128f79
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6b0a1b804d52b5a1c06c1234
😎 Deploy Preview https://deploy-preview-46611--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

Auth failures, ambiguous column references, an unsupported chart source
family and a late plugin preview refusal raised plain ValueErrors from
modules outside the host-validation list, so the response boundary
replaced their Superset-written text with the generic error. They now
raise MCPValidationError (MCPNoAuthSourceError, MCPAuthConfigError and
AmbiguousDatasetReferenceError subclass it), which signed-in callers see
and embedded guests still get sanitized.
Exercise shared and distinct host/singleton apps so credential guidance tests do not depend on collection order. Keep the signed-in guidance and embedded-guest redaction assertions. Cover both unsupported-source guards for preview and persistence updates.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

doc Namespace | Anything related to documentation review:draft size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants