Repository navigation
fix(mcp): advertise typed tool outputs - #43828
Conversation
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
631d94c to
343f8fb
Compare
rebenitez1802
left a comment
There was a problem hiding this comment.
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.
343f8fb to
dc590c6
Compare
|
Addressed every item in the review:
No review feedback was declined. The branch was rebased onto |
|
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. |
Code Review Agent Run #adc7e4Actionable Suggestions - 0Additional Suggestions - 6
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
rebenitez1802
left a comment
There was a problem hiding this comment.
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.
|
Addressed all three blocking findings and reviewed the newer automated suggestions:
I kept three low-priority suggestions unchanged after evaluation:
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
left a comment
There was a problem hiding this comment.
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.
|
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. |
53ab218 to
35fc0ce
Compare
|
Rebased the branch onto the latest fetched 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
left a comment
There was a problem hiding this comment.
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:
35fc0ceaddsform_data: dict[str, Any]toUpdateChartPreviewResponse(and the corresponding inventory-test field). This makes the advertisedoutputSchemahonest about a field the tool already returned (update_chart_preview.py), so it strengthens the advertised-schema == actual-structuredContentinvariant rather than weakening it.form_datais always a serializable dict on the success path, error/OAuth branches stay valid undertotal=False, and the value is covered bytest_cached_gauge_update_preserves_controls_and_compilesplus the registration schema-property assertion.bdf94e8is docs-only (docstring wording + a blank line inUPDATING.md); the_structured_output_enabledreword is more accurate.
No blocking issues. LGTM.
|
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR). Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
35fc0ce to
ca798e6
Compare
|
Rebased onto the latest fetched 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. |
ca798e6 to
1d4cce3
Compare
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.
Code Review Agent Run #0e0cf0Actionable Suggestions - 0Additional Suggestions - 9
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
…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]>
(cherry picked from commit 0f02102)
…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]>
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:
MCP_STRUCTURED_OUTPUT_ENABLED = False, the outer compatibility middleware removesoutputSchemaandstructuredContentas a pair while preserving the existing text result;The change also:
titleannotations are removed without deleting a response field literally namedtitle;StructuredContentStripperMiddlewareimport and documents its replacement inUPDATING.md;BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
Not applicable; this changes MCP protocol metadata and result envelopes, not the UI.
TESTING INSTRUCTIONS
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