Skip to content

fix(mcp): advertise typed tool outputs - #43828

Merged
aminghadersohi merged 8 commits into
apache:masterfrom
preset-io:fix/mcp-tool-metadata
Sep 16, 2026
Merged

aminghadersohi merged 8 commits into
apache:masterfrom
preset-io:fix/mcp-tool-metadata

Conversation

@aminghadersohi

@aminghadersohi aminghadersohi commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

SUMMARY

Superset's native MCP tools have typed return annotations, but their discovery metadata did not expose useful machine-readable result contracts. This change derives concrete validation-mode output schemas for native tools so custom Pydantic serializers do not collapse the schemas to unconstrained objects.

For a bridge-compatible rollout, structured protocol fields remain opt-in:

  • with the default MCP_STRUCTURED_OUTPUT_ENABLED = False, the outer compatibility middleware removes outputSchema and structuredContent as a pair while preserving the existing text result;
  • when enabled after validating every client and transport bridge in a deployment, discovery advertises the concrete schemas and successful calls return matching structured content across HTTP, stdio, and factory-configured startup; factory startup installs the same complete core middleware stack as the built-in server; and
  • native tools still receive server-side output validation regardless of the wire-compatibility setting.

The change also:

  • gives previously generic chart preview, chart schema, chart info, dashboard info, and dataset info responses concrete return contracts;
  • fixes schema-title cleanup so generated title annotations are removed without deleting a response field literally named title;
  • preserves the original stripping behavior of the deprecated StructuredContentStripperMiddleware import and documents its replacement in UPDATING.md;
  • leaves task-protocol results untouched in compatibility mode and keeps structured OAuth error payloads schema-versioned;
  • validates trimmed chart-info success and error payloads against the advertised schema;
  • documents why extension tools retain FastMCP's default schema derivation; and
  • adds an exhaustive inventory test that locks the native tool set, exact read-only/destructive classifications, closed-world hints, mutating-tool idempotency hints, response-specific fields for every schema, and representative full top-level contracts.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable; this changes MCP protocol metadata and result envelopes, not the UI.

TESTING INSTRUCTIONS

PYTHONPATH="$PWD/superset-core/src" pytest -q \
  tests/unit_tests/mcp_service/test_mcp_tool_registration.py \
  tests/unit_tests/mcp_service/test_middleware.py \
  tests/unit_tests/mcp_service/test_mcp_e2e_smoke.py \
  tests/unit_tests/mcp_service/test_mcp_config.py \
  tests/unit_tests/mcp_service/test_mcp_server.py \
  tests/unit_tests/mcp_service/test_main_entrypoint.py \
  tests/unit_tests/mcp_service/chart/tool/test_get_chart_info.py \
  tests/unit_tests/mcp_service/chart/tool/test_update_chart_preview.py \
  tests/unit_tests/mcp_service/dashboard/tool/test_dashboard_tools.py::test_get_dashboard_info_not_found \
  tests/unit_tests/mcp_service/dashboard/tool/test_dashboard_tools.py::test_explicit_default_columns_excludes_filter_state \
  tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py::test_get_dataset_info_includes_columns_and_metrics

PYTHONPATH="$PWD/superset-core/src" pytest -q tests/unit_tests/mcp_service

git add .
pre-commit run

The focused startup/schema suite passes, the full MCP unit suite passes 4,011 tests with two skips, and all branch-scoped pre-commit hooks pass. Protocol-level tests cover enabled and compatibility modes, factory startup, and task-protocol pass-through, while chart, dashboard, dataset, and error responses are validated against their advertised output schemas.

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

@netlify

netlify Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit d0df5cc
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6aa9bb3a85d7ce00074e4131
😎 Deploy Preview https://deploy-preview-43828--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.

@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Sep 3, 2026
@codecov

codecov Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.89899% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.26%. Comparing base (4c27cbd) to head (d0df5cc).

Files with missing lines Patch % Lines
superset/core/mcp/core_mcp_injection.py 79.48% 5 Missing and 3 partials ⚠️
superset/mcp_service/__main__.py 60.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #43828      +/-   ##
==========================================
+ Coverage   80.25%   80.26%   +0.01%     
==========================================
  Files        2927     2927              
  Lines      173166   173244      +78     
  Branches    40156    40166      +10     
==========================================
+ Hits       138973   139057      +84     
+ Misses      31600    31591       -9     
- Partials     2593     2596       +3     
Flag Coverage Δ
hive 37.39% <55.55%> (+0.02%) ⬆️
mysql 56.91% <55.55%> (+<0.01%) ⬆️
postgres 56.94% <55.55%> (+<0.01%) ⬆️
presto 39.48% <55.55%> (+0.02%) ⬆️
python 84.70% <89.89%> (+0.02%) ⬆️
sqlite 56.63% <55.55%> (+<0.01%) ⬆️
unit 76.21% <89.89%> (+0.02%) ⬆️

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.

@aminghadersohi
aminghadersohi marked this pull request as ready for review September 4, 2026 05:50

@rebenitez1802 rebenitez1802 left a comment

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.

Request changes: the schema-derivation design is correct and genuinely clever — column-trimmed serializers still validate against a validation-mode superset schema, the security model is intact, and the metadata regression tests are strong — but a few rollout/robustness items should be resolved before merge, and none of them are schema-math bugs.

🔴 High — Removes the Claude.ai-bridge compatibility strip with no evidence it's now safe, and no UPDATING.md
ToolResultCompatibilityMiddleware.on_list_tools now just return tools and the on_call_tool structured_content strip is deleted (superset/mcp_service/middleware.py), so structuredContent/outputSchema flow to every client on every successful call. The old StructuredContentStripperMiddleware existed specifically because "Claude.ai's MCP bridge cannot handle structuredContent dicts, causing TypeError: encoding without a string argument." The PR presents no in-tree proof that limitation is resolved — it actually softened the error-path comment from "unverified against the live Claude.ai bridge" to "transport-level encoding failures," i.e. edited the uncertainty out rather than resolving it. server.py still carries active encoding without a string argument workarounds for other bridges (mcp-remote, Claude Desktop) on the input side, so this transport fragility isn't considered gone elsewhere. If the premise still holds, this is a hard regression for that transport across all ~70 tools. Please confirm the bridge accepts structuredContent now (or gate the strip behind config), and add an UPDATING.md entry for the client-visible contract change.

🟡 Medium — _strip_schema_titles deletes response fields literally named title from the advertised schema
superset/core/mcp/core_mcp_injection.py strips every dict key named title at any depth. In JSON Schema a field named title appears as the key properties.title, so its entire subschema is dropped. This is live today: open_sql_lab_with_context returns SqlLabResponse (superset/mcp_service/sql_lab/schemas.py:318), which has title: str | None, so title silently vanishes from that tool's outputSchema. It isn't a hard failure (the model isn't extra="forbid", so the emitted title validates as an allowed additional property), but the contract under-describes the response, the inventory test checks url not title so it goes unnoticed, and any future response model with a title field loses it too. See the inline applyable suggestion on _strip_schema_titles below.

🟡 Medium — Strict server-side output validation is now enforced for ~70 tools, but only the flagship trimming tools are proven to pass
Advertising outputSchema turns on jsonschema.validate(structuredContent, outputSchema) in the MCP SDK's call_tool handler (mcp/server/lowlevel/server.py); a divergence between a tool's serialized output and its validation-mode schema now returns "Output validation error" instead of the result. The validation-mode-superset design is verified correct for get_chart_info / get_dashboard_info / get_dataset_info (all fields optional, no extra="forbid", aliases aligned, column_name always re-added by the nested serializer), but the .data → .structured_content test migration removed the suite's only incidental schema-conformance check, and no test asserts a trimmed/aliased payload actually validates. Please add at least one round-trip test — jsonschema.validate(result.structured_content, tool.output_schema) (or assert result.data is not None) — for a select_columns-trimmed get_dashboard_info/get_dataset_info and for an error-branch response, so the advertised-vs-emitted contract is locked for the paths most likely to drift.

🟡 Medium — StructuredContentStripperMiddleware alias silently reverses behavior
The back-compat alias StructuredContentStripperMiddleware = ToolResultCompatibilityMiddleware (superset/mcp_service/middleware.py) preserves the import name but now points at a class that preserves structured content instead of stripping it. The docs invite operators to layer middleware in via a custom startup path, so anyone who added StructuredContentStripperMiddleware to get stripping (e.g. for the bridge above) gets the opposite behavior after upgrade with no code change, no warning, and no UPDATING.md note — the alias name now misdescribes the class. Please cover this in the same UPDATING.md entry and consider a deprecation comment on the alias.

🟢 Low — Host-only schema derivation is an unstated contract inconsistency
output_schema is only derived when context_type == "host" (core_mcp_injection.py), so extension-registered tools advertise no outputSchema and skip server-side output validation while native tools don't. Reasonable, but worth a one-line rationale comment so the asymmetry is intentional-by-record.

🟢 Low — Inventory test guards total collapse, not partial drift
test_mcp_tool_registration.py asserts one response-specific property per tool via a recursive "appears anywhere in the schema tree" match. That correctly rejects an unconstrained {"type": "object"}, but a schema that dropped its other properties (or nested the field in the error branch) would still pass. Consider asserting the expected top-level output properties for a couple of representative tools.


Net: strong, correct core with an excellent metadata regression harness. The blockers are safe rollout + change communication (the bridge strip and UPDATING.md), one concrete schema-derivation bug (title fields), and closing the round-trip test gap now that output validation is enforced server-side. The security model is intact — redaction runs before model_dump, so structuredContent carries the same already-redacted dict the text path did — and the required-field / alias / cast() / union-shape concerns were all checked and refuted with runtime evidence.

Comment thread superset/core/mcp/core_mcp_injection.py Resolved
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Addressed every item in the review:

  • Bridge-compatible rollout: added MCP_STRUCTURED_OUTPUT_ENABLED, defaulting to False. Compatibility mode strips outputSchema and structuredContent as a pair while retaining text results; enabling the setting passes both through. The setting is wired through HTTP and stdio startup, covered by middleware and real-ASGI protocol tests, and documented in both the MCP configuration guide and UPDATING.md.
  • Nested title field: schema cleanup removes only string-valued generated annotations, not a properties.title subschema. A direct regression test and the open_sql_lab_with_context inventory expectation cover this case.
  • Output-schema round trips: reduced-column dashboard and dataset responses plus a not-found error response are explicitly validated with jsonschema.validate against the registered tool schema.
  • Deprecated stripper: StructuredContentStripperMiddleware is now a real deprecated compatibility subclass that emits DeprecationWarning and retains stripping behavior. Its replacement is documented in UPDATING.md and the MCP guide.
  • Host-only behavior: added the rationale that extension-owned serializers cannot be assumed to follow the native validation-schema convention.
  • Partial schema drift: added representative full top-level field assertions for dashboard, dataset, SQL Lab, and chart-preview response shapes.

No review feedback was declined. The branch was rebased onto c03f3441bd565b9fd5f082d0b875c467eeae441c before these edits. Local validation is green: 198 focused tests, 3,729 full MCP unit tests, and the staged pre-commit suite.

Comment thread superset/mcp_service/server.py Resolved
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

A subsequent factory-startup finding was also confirmed and adopted: factory-configured servers now resolve the same structured-output setting and prepend the compatibility boundary ahead of custom middleware. The added parameterized startup test covers enabled/disabled behavior and ordering. Updated local totals: 200 focused tests and 3,731 full MCP unit tests; staged pre-commit hooks pass.

@bito-code-review

bito-code-review Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #adc7e4

Actionable Suggestions - 0
Additional Suggestions - 6
  • tests/unit_tests/mcp_service/dashboard/tool/test_dashboard_tools.py - 1
    • Incomplete data→structured_content migration · Line 1798-1798
      This assertion still reads `result.data`, but the rest of this diff migrates to `result.structured_content`. In fastmcp 3.4.7 `CallToolResult.data` defaults to `None`, so if `call_tool` no longer populates it this test fails; even if it passes, it's inconsistent with the migration. Use `result.structured_content`.
  • superset/mcp_service/server.py - 1
    • Duplicated config resolution · Line 1021-1028
      The `config.get("MCP_STRUCTURED_OUTPUT_ENABLED", MCP_STRUCTURED_OUTPUT_ENABLED)` expression is duplicated verbatim in the factory path (1023-1025) and the default path (1058-1060). If the key or fallback changes in one place, the two server paths diverge in structured-output behavior. Consider extracting a shared helper used by both call sites.
  • superset/mcp_service/chart/tool/update_chart_preview.py - 1
    • Inconsistent error response schema · Line 168-168
      The return type is now the `UpdateChartPreviewResponse` TypedDict, and every other return path (dataset_not_found, DatasetNotAccessible, validation_error, PreviewError, generic exception) includes `schema_version`/`api_version`. The two OAuth2 error paths (lines 410-414, 419-423) omit them, so the declared output schema is inconsistent across error responses. Add both fields for uniformity.
  • superset/mcp_service/middleware.py - 1
    • Invisible deprecation warning · Line 857-862
      `DeprecationWarning` is suppressed by default outside `__main__` in Python 3.11, so operators using this class in custom startup paths (per docs/UPDATING.md) will never see this notice. Consider `FutureWarning` or a `logger.warning` so the deprecation is actually surfaced.
  • tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py - 1
    • Weak schema validation · Line 1266-1266
      `validate(instance=result.structured_content, schema=tool.output_schema)` runs against the `select_columns`-filtered payload, which only contains `id/table_name/schema/columns/metrics`. Since every `DatasetInfo` field is optional, this passes trivially and never verifies the full schema shape. Consider validating an unfiltered response to make the check meaningful.
  • tests/unit_tests/mcp_service/test_mcp_tool_registration.py - 1
    • Brittle exact tool-set assert · Line 262-262
      This strict equality requires the global `mcp` instance to expose exactly `EXPECTED_TOOL_OUTPUT_FIELDS`. `init_fastmcp_server` calls `_remove_disabled_tools` and `_apply_config_guards` (app.py:1054-1056), which can remove tools from that shared instance. If any tool is disabled via `MCP_DISABLED_TOOLS` or a config guard, this assertion fails. Consider a subset assertion or an explicit full-set reset.
Review Details
  • Files reviewed - 26 · Commit Range: dc590c6..f917412
    • docs/admin_docs/configuration/mcp-server.mdx
    • superset/core/mcp/core_mcp_injection.py
    • superset/mcp_service/__main__.py
    • superset/mcp_service/chart/schemas.py
    • superset/mcp_service/chart/tool/get_chart_info.py
    • superset/mcp_service/chart/tool/get_chart_type_schema.py
    • superset/mcp_service/chart/tool/update_chart_preview.py
    • superset/mcp_service/dashboard/tool/get_dashboard_info.py
    • superset/mcp_service/dataset/tool/get_dataset_info.py
    • superset/mcp_service/mcp_config.py
    • superset/mcp_service/middleware.py
    • superset/mcp_service/server.py
    • tests/unit_tests/mcp_service/chart/tool/test_update_chart_preview.py
    • tests/unit_tests/mcp_service/dashboard/tool/test_dashboard_tools.py
    • tests/unit_tests/mcp_service/dashboard/tool/test_update_dashboard.py
    • tests/unit_tests/mcp_service/database/tool/test_database_tools.py
    • tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py
    • tests/unit_tests/mcp_service/query/tool/test_query_tools.py
    • tests/unit_tests/mcp_service/saved_query/tool/test_saved_query_tools.py
    • tests/unit_tests/mcp_service/test_main_entrypoint.py
    • tests/unit_tests/mcp_service/test_mcp_config.py
    • tests/unit_tests/mcp_service/test_mcp_e2e_smoke.py
    • tests/unit_tests/mcp_service/test_mcp_server.py
    • tests/unit_tests/mcp_service/test_mcp_tool_registration.py
    • tests/unit_tests/mcp_service/test_middleware.py
    • tests/unit_tests/mcp_service/test_middleware_logging.py
  • Files skipped - 3
    • UPDATING.md - Reason: Filter setting
    • superset/mcp_service/CLAUDE.md - Reason: Filter setting
    • superset/mcp_service/PRODUCTION.md - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@rebenitez1802 rebenitez1802 left a comment

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.

Request changes: the opt-in redesign is the right call and all three round-1 blockers are cleanly addressed — but the new factory-server commit reintroduces the exact "Output validation error" this PR exists to prevent, plus a task-protocol AttributeError.

✅ Round-1 feedback resolved (nice work): structured output is now opt-in behind MCP_STRUCTURED_OUTPUT_ENABLED (default False, mcp_config.py:109), so the text-only wire contract — and Claude.ai-bridge compatibility — is preserved by default, with an UPDATING.md entry and a test_structured_output_can_be_disabled_over_real_asgi_transport that proves disabled mode returns a real payload (not an error) over the real ASGI transport. StructuredContentStripperMiddleware now retains stripping + emits a DeprecationWarning. The _strip_schema_titles fix was applied verbatim. get_dashboard_info/get_dataset_info gained explicit jsonschema.validate round-trip tests (trimmed + aliased + error branch).

🔴 High — Factory-server path hard-errors every host tool in the default (disabled) mode
The new commit (server.py:1020-1029) installs ToolResultCompatibilityMiddleware as the only core middleware on the factory path, because MCP_FACTORY_CONFIG has no middleware key (mcp_config.py:244) so factory_config.get("middleware") or () is empty. output_schema is set on host tools unconditionally (core_mcp_injection.py:228-230), and in disabled mode the middleware strips structured_content -> None (middleware.py:844) while leaving meta=None. In FastMCP 3.4.7, ToolResult.to_mcp_result() emits a bare content list (not a CallToolResult) when meta is None and not is_error, so the MCP SDK low-level wrapper hits outputSchema is not None and structuredContent is None -> "Output validation error: outputSchema defined but no structured output returned". On the default path this is silently avoided only because LoggingMiddleware always injects meta, forcing a CallToolResult — the factory path has no LoggingMiddleware. Reproduced end-to-end with the pinned fastmcp==3.4.7 + mcp==1.29.1: factory stack -> isError=True; default stack -> works. Reachability caveat: the OSS-default factory instance auto-discovers 0 host tools, so a pure-default factory server serves nothing — but the bug bites the moment a factory server actually serves host tools, which is the entire purpose of the commit, and the added test only asserts middleware placement (mocked create_mcp_app), never a real tool call. Fix: have the factory path reuse build_middleware_list(structured_output_enabled=...) so LoggingMiddleware/error handling are present; better still, make ToolResultCompatibilityMiddleware self-contained (also clear the live tool's output_schema when stripping), so correctness doesn't silently depend on another middleware injecting meta — that coupling is fragile and undocumented.

🟡 Medium — Dropped isinstance guard -> AttributeError on task-protocol (SEP-1686) calls in disabled mode
The strip condition changed from master's if isinstance(result, ToolResult) and result.structured_content is not None: to if not self.structured_output_enabled and result.structured_content is not None: (middleware.py:844). A task-augmented tools/call makes call_next return a CreateTaskResult, which has no structured_content attribute (hasattr(...) == False), so in disabled mode result.structured_content raises AttributeError outside the method's try/except -> the SDK turns it into an isError result and the task protocol breaks. LoggingMiddleware kept exactly this guard (middleware.py:619). See the inline applyable suggestion on middleware.py:844 below.

🟡 Medium — get_chart_info round-trip validation still unguarded
get_chart_info got the same annotation-tightening as the other two (dict[str, Any] | ChartError -> ChartInfo | ChartError), which is what makes its advertised output_schema strict, but it has no jsonschema.validate round-trip test (test_get_chart_info.py reads the text channel only), it's absent from the e2e smoke test (which only exercises health_check), and it's not in the strengthened EXPECTED_TOP_LEVEL_OUTPUT_FIELDS inventory set. Since output_schema is unconditional, a ChartInfo/trimming divergence would hard-fail in production and no test would catch it. Fix: add a trimmed-payload validate(result.structured_content, tool.output_schema) test mirroring test_dashboard_tools.py:1777-1801 (plus its error branch).


Net: the redesign is sound and the round-1 blockers are genuinely fixed. The blocker now is the factory commit (Finding 1) reintroducing the SDK validation error on the path it's meant to support; the task-protocol guard and the get_chart_info test are quick follow-ups.

Comment thread superset/mcp_service/middleware.py Resolved
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Addressed all three blocking findings and reviewed the newer automated suggestions:

  • Factory default-disabled validation: factory-created servers now install the same complete core middleware stack as built-in startup, before custom middleware. The compatibility middleware also keeps a protocol result envelope when stripping structured content, so it remains safe even when used independently. A real streamable-HTTP regression exercises an isolated, factory-like FastMCP server in default-disabled mode and verifies a successful text-only response rather than an output-validation error.
  • Task protocol: restored the exact isinstance(result, ToolResult) guard, widened the middleware result typing, and added a regression using a real CreateTaskResult to prove pass-through without attribute access.
  • get_chart_info: the selected-column success path and not-found error path both execute through the protocol client and validate structuredContent against the advertised outputSchema; the native-tool inventory also locks representative chart-info fields.
  • Additional consistency findings: removed the obsolete dashboard result.data assertion, centralized structured-output configuration resolution, and made OAuth chart-preview errors include the schema/API version fields required by their declared contract, with coverage for both OAuth exception types.

I kept three low-priority suggestions unchanged after evaluation:

  • DeprecationWarning remains appropriate for a library import alias; the migration is explicitly surfaced in UPDATING.md and the MCP administration documentation, while a runtime logger warning would add unsolicited server noise.
  • Dataset validation intentionally uses a filtered/column-trimmed response because that is the serializer projection and alias-drift boundary the regression is designed to protect; the schema deliberately permits the full model.
  • The native-tool inventory intentionally uses exact equality rather than a subset. This PR is an exhaustive metadata audit, so allowing newly registered tools to bypass review would weaken the regression.

Local validation is green: 260 focused tests, 3,735 tests in the full MCP unit suite, and all staged pre-commit hooks. The PR remains ready for review.

@rebenitez1802 rebenitez1802 left a comment

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.

Approve: both round-2 bugs are genuinely fixed and runtime-verified against the pinned libraries (fastmcp==3.4.7 + mcp==1.29.1); only a trivial DRY nit remains.

Factory-path hard-error (prior High) — resolved, belt-and-suspenders. The factory path now installs *build_middleware_list(...) (server.py:1029), so it gets LoggingMiddleware (whose non-null meta was the only thing keeping the default path working) plus RBAC/GlobalErrorHandler — and the compat middleware is now self-contained via meta=result.meta or {}. Verified at runtime: fastmcp 3.4.7's to_mcp_result() gates on meta is not None (not truthiness), so {} correctly retains the CallToolResult envelope (low-level repro: meta=None -> "Output validation error", meta={} -> success). No double-add — the factory config carries no middleware key and create_mcp_app injects none of its own. Locked by test_compatibility_middleware_is_self_contained_over_real_asgi.

Task-protocol AttributeError (prior Medium) — resolved. The isinstance(result, ToolResult) guard is restored (signature widened to Any). Runtime-confirmed that a CreateTaskResult (SEP-1686 task path) is not a ToolResult and lacks structured_content, so it now passes through untouched; test_task_protocol_result_passes_through_unchanged covers it.

get_chart_info round-trip test (prior Medium) — resolved. test_get_chart_info.py now runs jsonschema.validate(response.structured_content, tool.output_schema) on both the redacted-success and error branches. (update_chart_preview also gained schema_version/api_version on its two OAuth2 error branches so all 8 return branches are consistent — cosmetic, safe since the response is a total=False TypedDict.)

🟢 Low (non-blocking) — _structured_output_enabled helper not applied everywhere. The new helper (server.py:917) is used at the two server.py call sites, but superset/mcp_service/__main__.py:152,189 still inline the identical flask_app.config.get("MCP_STRUCTURED_OUTPUT_ENABLED", MCP_STRUCTURED_OUTPUT_ENABLED) lookup twice, despite the helper's docstring saying it covers "every startup path." Value-identical, no functional impact — call _structured_output_enabled(flask_app) there too (or soften the docstring) if you touch this again.

Net: the design is sound, all findings across the review rounds are addressed, and the risky paths are runtime-verified and regression-tested. Nice work on the opt-in default and the belt-and-suspenders factory fix. LGTM.

@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Followed up on the remaining non-blocking wording nit: the resolver docstring now accurately limits its scope to server-managed startup paths. The stdio entry point intentionally retains its local lookup and behavior; this is a documentation-only clarification with no startup semantics change. Its 24 focused startup tests and commit-scoped pre-commit hooks pass.

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 9, 2026
@aminghadersohi
aminghadersohi force-pushed the fix/mcp-tool-metadata branch 2 times, most recently from 53ab218 to 35fc0ce Compare September 9, 2026 18:51
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Rebased the branch onto the latest fetched apache/master and resolved the UPDATING.md overlap by retaining both upstream and MCP migration entries. The rebase exposed a genuine compatibility issue from the upstream chart-preview changes: successful responses return form_data, but the new typed response contract did not declare it. The TypedDict and exhaustive output-schema inventory now include that field.

Post-rebase validation is green locally: 3,913 MCP tests passed with one skip, the focused chart-preview/registration tests passed, and the complete branch-scoped pre-commit run passed. The update was pushed with an explicit force-with-lease against the previously fetched fork head.

@rebenitez1802 rebenitez1802 left a comment

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.

Re-approving after reviewing the incremental changes since my prior approval (rebase + two new commits).

The author-introduced delta since 9f5423c is small and self-contained:

  • 35fc0ce adds form_data: dict[str, Any] to UpdateChartPreviewResponse (and the corresponding inventory-test field). This makes the advertised outputSchema honest about a field the tool already returned (update_chart_preview.py), so it strengthens the advertised-schema == actual-structuredContent invariant rather than weakening it. form_data is always a serializable dict on the success path, error/OAuth branches stay valid under total=False, and the value is covered by test_cached_gauge_update_preserves_controls_and_compiles plus the registration schema-property assertion.
  • bdf94e8 is docs-only (docstring wording + a blank line in UPDATING.md); the _structured_output_enabled reword is more accurate.

No blocking issues. LGTM.

@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Sep 9, 2026
@bito-code-review

Copy link
Copy Markdown
Contributor

AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 10, 2026
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Rebased onto the latest fetched apache/master. The only content conflict was in get_chart_info; the resolution preserves upstream active-filter attachment and the typed/schema-validating return contract. The rebase also exposed two dropped typing imports required by the upstream active-filter additions; both are restored and covered by the upstream unsaved-chart regression.

Post-rebase validation: 229 focused MCP tests passed, the full MCP suite passed 4,011 tests with two skips, and the complete branch-scoped pre-commit run passed. The rewritten branch was pushed with an explicit force-with-lease against the fetched fork head.

@github-actions github-actions Bot added requires:rebase Requires rebasing on top of current master and removed requires:rebase Requires rebasing on top of current master labels Sep 11, 2026
The tool metadata test asserts an exact inventory of registered tools so
every new tool goes through the safety-hint and output-schema review.
get_dashboard_data landed on master, so add its response-specific output
field to keep that gate accurate.
@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Sep 15, 2026
@bito-code-review

bito-code-review Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #0e0cf0

Actionable Suggestions - 0
Additional Suggestions - 9
  • superset/mcp_service/server.py - 1
    • Factory middleware over-injection · Line 1027-1033
      The factory path now unconditionally prepends the full core stack (RBAC, Logging, GlobalErrorHandler, ToolResultCompatibility) to `factory_config["middleware"]`. Previously `create_mcp_app(**factory_config)` used the user's middleware as-is. `get_mcp_factory_config()` documents that users customize middleware, so forcing RBAC filtering and error handling onto factory servers changes behavior they didn't opt into, and duplicates any core middleware already present in their config. Consider injecting only `ToolResultCompatibilityMiddleware`.
  • tests/unit_tests/mcp_service/test_mcp_e2e_smoke.py - 1
    • Test default mismatches prod · Line 168-168
      `_real_asgi_client` defaults `structured_output_enabled=True`, but production defaults to `MCP_STRUCTURED_OUTPUT_ENABLED = False` (mcp_config.py:109), and `build_middleware_list()` (server.py:892) also defaults to that. So the default-path smoke tests exercise a non-default config and a regression in the default (False) path would go uncaught. Change the default to `False` and pass `structured_output_enabled=True` explicitly at the call sites that assert structured output: `test_tools_list_over_real_asgi_transport` (line 222) and `test_tools_call_health_check_over_real_asgi_transport` (line 263).
  • superset/mcp_service/__main__.py - 1
    • Duplicated config resolution · Line 151-155
      Both new call sites (lines 151-155 and 188-192) inline the same `flask_app.config.get("MCP_STRUCTURED_OUTPUT_ENABLED", ...)` expression that already exists as `_structured_output_enabled(flask_app)` in `server.py`. Reusing that helper keeps the config key/default in one place and avoids divergence if either changes.
  • superset/mcp_service/chart/tool/get_chart_type_schema.py - 1
    • Schema placement consistency · Line 51-58
      `ChartTypeSchemaResponse` is defined in the tool file, but CLAUDE.md (line 277) directs schemas to `{module}/schemas.py`, and the analogous `UpdateChartPreviewResponse` TypedDict lives in `chart/schemas.py`. Consider relocating it there for consistency and reuse.
  • docs/admin_docs/configuration/mcp-server.mdx - 1
    • Missing middleware in table · Line 775-775
      The rewritten table claims to describe the default stack assembled in `build_middleware_list()`, but omits `RBACToolVisibilityMiddleware`, which `build_middleware_list()` returns at `server.py:911` (filters `tools/list` by the caller's FAB permissions). Operators reading this table would miss a default security middleware. Add a row for it.
  • superset/mcp_service/dashboard/tool/get_dashboard_info.py - 1
    • Misleading type assertion · Line 252-258
      `cast(DashboardInfo, ...)` is a runtime no-op, so the success path still returns a plain `dict` from `model_dump(mode="json")`, contradicting the new `-> DashboardInfo | DashboardError` annotation. Any future caller doing `isinstance(result, DashboardInfo)` or attribute access would break. Consider `DashboardInfo.model_validate(...)` to return a real instance, as `get_dashboard_layout` does.
  • tests/unit_tests/mcp_service/test_mcp_tool_registration.py - 2
    • Brittle exact-set assertion · Line 264-264
      The strict equality `{tool.name ...} == set(EXPECTED_TOOL_OUTPUT_FIELDS)` couples this test to the exact registered tool set. If `MCP_DISABLED_TOOLS` is configured in the test environment (a supported path in `_remove_disabled_tools`), tools are removed and this assertion fails even though remaining tools are correctly annotated. Consider a subset assertion or documenting the empty-config requirement.
    • Redundant double-reporting · Line 278-286
      When `readOnlyHint`/`destructiveHint` is None, the tool is already added to `missing_by_tool` (line 268-271), but `None is not True` also appends it to `incorrect_read_only_tools`/`incorrect_destructive_tools`. This double-reports the same tool in two failure lists, making the assertion output harder to read. Guard the classification checks on the field being non-None.
  • tests/unit_tests/mcp_service/chart/tool/test_update_chart_preview.py - 1
    • Inline import moved to module level · Line 193-193
      This import is placed inside the test function body. Per repo standard, imports belong at module level unless a circular dependency exists and is documented — none applies here. Move it to the top of the file alongside the other `superset.exceptions` imports for consistency and discoverability.
Review Details
  • Files reviewed - 27 · Commit Range: d55bda8..d0df5cc
    • docs/admin_docs/configuration/mcp-server.mdx
    • superset/core/mcp/core_mcp_injection.py
    • superset/mcp_service/__main__.py
    • superset/mcp_service/chart/schemas.py
    • superset/mcp_service/chart/tool/get_chart_info.py
    • superset/mcp_service/chart/tool/get_chart_type_schema.py
    • superset/mcp_service/chart/tool/update_chart_preview.py
    • superset/mcp_service/dashboard/tool/get_dashboard_info.py
    • superset/mcp_service/dataset/tool/get_dataset_info.py
    • superset/mcp_service/mcp_config.py
    • superset/mcp_service/middleware.py
    • superset/mcp_service/server.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_info.py
    • tests/unit_tests/mcp_service/chart/tool/test_update_chart_preview.py
    • tests/unit_tests/mcp_service/dashboard/tool/test_dashboard_tools.py
    • tests/unit_tests/mcp_service/dashboard/tool/test_update_dashboard.py
    • tests/unit_tests/mcp_service/database/tool/test_database_tools.py
    • tests/unit_tests/mcp_service/dataset/tool/test_dataset_tools.py
    • tests/unit_tests/mcp_service/query/tool/test_query_tools.py
    • tests/unit_tests/mcp_service/saved_query/tool/test_saved_query_tools.py
    • tests/unit_tests/mcp_service/test_main_entrypoint.py
    • tests/unit_tests/mcp_service/test_mcp_config.py
    • tests/unit_tests/mcp_service/test_mcp_e2e_smoke.py
    • tests/unit_tests/mcp_service/test_mcp_server.py
    • tests/unit_tests/mcp_service/test_mcp_tool_registration.py
    • tests/unit_tests/mcp_service/test_middleware.py
    • tests/unit_tests/mcp_service/test_middleware_logging.py
  • Files skipped - 3
    • UPDATING.md - Reason: Filter setting
    • superset/mcp_service/CLAUDE.md - Reason: Filter setting
    • superset/mcp_service/PRODUCTION.md - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@aminghadersohi
aminghadersohi merged commit 0f02102 into apache:master Sep 16, 2026
76 checks passed
@aminghadersohi
aminghadersohi deleted the fix/mcp-tool-metadata branch September 16, 2026 09:43
tien238lnd added a commit to tien238lnd/superset that referenced this pull request Sep 17, 2026
…et updates

- restore_dataset: check editorship before composing any response that
  names the dataset, as restore_chart does. The restore lookup bypasses
  the RBAC base filter, so a dataset outside the caller's scope now reads
  as NotFound, and a visible one the caller cannot edit gets a Forbidden
  response naming only its id.
- update_dataset: RefreshDatasetCommand skips, without raising, SQL it
  cannot render outside a query (apache#38012). The command now exposes
  metadata_refreshed, and update_dataset reports a skipped refresh as a
  warning instead of columns_synced=true. A failure while setting
  main_dttm_col after the re-sync is reported as a warning next to the
  changes already saved. cache_timeout rejects booleans.
- delete_dataset: validate the command (lookup and editorship) before
  counting dependent charts and dashboards.
- Register the three tools in the tool metadata test added by apache#43828 and
  in the RBAC enforcement test.

Co-Authored-By: Claude Opus 5 <[email protected]>
villebro pushed a commit that referenced this pull request Sep 20, 2026
villebro added a commit that referenced this pull request Sep 22, 2026
get_dashboard_data (#44113) was never backported to 7.0, but the
cherry-pick of #43828's EXPECTED_TOOL_OUTPUT_FIELDS snapshot brought
in a stale entry for it, failing
test_all_registered_tools_have_complete_metadata's set-equality
assertion against the live tool registry.
tien238lnd added a commit to tien238lnd/superset that referenced this pull request Sep 23, 2026
…et updates

- restore_dataset: check editorship before composing any response that
  names the dataset, as restore_chart does. The restore lookup bypasses
  the RBAC base filter, so a dataset outside the caller's scope now reads
  as NotFound, and a visible one the caller cannot edit gets a Forbidden
  response naming only its id.
- update_dataset: RefreshDatasetCommand skips, without raising, SQL it
  cannot render outside a query (apache#38012). The command now exposes
  metadata_refreshed, and update_dataset reports a skipped refresh as a
  warning instead of columns_synced=true. A failure while setting
  main_dttm_col after the re-sync is reported as a warning next to the
  changes already saved. cache_timeout rejects booleans.
- delete_dataset: validate the command (lookup and editorship) before
  counting dependent charts and dashboards.
- Register the three tools in the tool metadata test added by apache#43828 and
  in the RBAC enforcement test.

Co-Authored-By: Claude Opus 5 <[email protected]>
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 size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants