Skip to content

fix(mcp): keep isError through call_tool and test native tool surface parity - #45081

Merged
aminghadersohi merged 11 commits into
apache:masterfrom
aminghadersohi:mcp-native-named-tools
Oct 10, 2026
Merged

aminghadersohi merged 11 commits into
apache:masterfrom
aminghadersohi:mcp-native-named-tools

Conversation

@aminghadersohi

Copy link
Copy Markdown
Contributor

SUMMARY

The MCP service serves one set of registered tools in two discovery shapes, both built from build_middleware_list():

  • compatibility (default): MCP_TOOL_SEARCH_CONFIG["enabled"] = True. tools/list returns the pinned tools plus search_tools/call_tool.
  • native: enabled = False. tools/list returns every permitted tool under its real name.

Neither shape had a contract test for the native surface or for parity between the two. This PR adds those tests, records a measured inventory of the native catalog, and fixes one parity bug they found. No default changes.

Fix: call_tool lost isError. LoggingMiddleware rebuilds the ToolResult to attach mcp_call_id, and the rebuild dropped is_error. A direct call raises at that layer, so the flag survived. A call forwarded by the call_tool proxy is different: its inner middleware chain has already turned the exception into an error result. The outer rebuild then turned that into a success, so a permission denial or validation error sent through call_tool reached the client with isError: false. It was also logged as successful. The rebuild now keeps is_error, and a returned error result is logged as a failure.

Native inventory (native_tool_inventory.json): for each registered tool it records the annotations, description length, input/output schema size, and the full tools/list entry size with structured output disabled and enabled, plus catalog totals. These are measured from the canonical definitions over the MCP protocol, not maintained by hand. Sizes may shrink; growth past 2% or 200 bytes fails until the report is regenerated with SUPERSET_MCP_UPDATE_TOOL_INVENTORY=1. Measured on this branch: 79 tools. The full native listing is 218,156 bytes text-only and 524,788 bytes structured. The largest entry is manage_native_filters at 10,916 bytes text-only and generate_chart at 28,070 bytes structured. The longest description is generate_chart at 6,688 characters.

Contract tests (test_native_tool_surface.py), all checked on the native path, a direct named call in compatibility mode, and the call_tool proxy:

  • Native tools/list lists every registered tool exactly once, as one deterministic page with no cursor and no synthetic tools.
  • Listed descriptions, annotations, and input schemas equal the canonical definitions. Schemas are dereferenced by FastMCP's default dereference_schemas.
  • outputSchema is present for every tool only when MCP_STRUCTURED_OUTPUT_ENABLED = True.
  • Every advertised schema is valid Draft 2020-12 with no dangling $ref.
  • No single entry exceeds a 100 KB list page.
  • Every registered tool dispatches under its real name. Each call ends at schema validation or the authorization gate, with identical error results on all three paths. Tools in ALLOWED_UNPROTECTED run for every caller, as designed.
  • A successful call returns identical content and structuredContent on all three paths under both structured-output settings, and the structured result validates against the advertised schema.
  • Validation errors keep identical details through the proxy.
  • RBAC, token scopes, and the restricted-principal policy give the same visible set (native tools/list vs search_tools) and the same denial. A hidden tool named directly or through call_tool is rejected.
  • Revoking a permission hides and blocks the tool on the next request on every path.
  • A tool removed from the registry, for example by MCP_DISABLED_TOOLS, is unreachable and absent from search.

Docs: mcp-server.mdx now describes both discovery modes and authorization in each. It adds migration steps and mixed-version and multi-pod rollout notes, and states that compatibility mode remains supported and any default change will be listed in UPDATING.md. It also removes a stale reference to middleware classes that do not exist; the service applies no rate limiting of its own.

Known differences, kept unchanged and documented:

  • With no authentication source configured (development only), native tools/list fails open while search_tools shows only permission-free tools. Protected calls are rejected either way.
  • Read-only tools leave idempotentHint unset.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable; MCP protocol behavior and tests only.

TESTING INSTRUCTIONS

PYTHONPATH="$PWD/superset-core/src" pytest -q \
  tests/unit_tests/mcp_service/test_native_tool_surface.py \
  tests/unit_tests/mcp_service/test_middleware_logging.py

Without the LoggingMiddleware change, 7 of the 17 surface tests fail because proxied errors arrive with isError: false.

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

…ibility mode

Add tests that build the native and compatibility (search_tools/call_tool)
surfaces from the registered tools and the default middleware stack, and
check that both expose the same definitions, results, validation errors, and
authorization decisions: RBAC, token scopes, restricted-principal policy, and
permission revocation. Record a measured native catalog inventory (per-tool
annotations, description and schema sizes, list entry sizes with structured
output disabled and enabled, catalog totals) and fail on unreviewed growth.

Fix LoggingMiddleware dropping isError when it rewraps a returned error
result. Calls forwarded by the call_tool proxy return their converted error
as a result, so permission and validation errors reached clients as
successful results and were logged as successes.

Document the native and compatibility discovery modes, migration, and
mixed-version rollout.
@netlify

netlify Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit e18e7dc
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ac9b1fe4f8e2500086c7a0d
😎 Deploy Preview https://deploy-preview-45081--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 Oct 8, 2026
@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt PR Risk: Low Risk

  • The PR appears safe to merge; the focused tests cover single-count metrics for successful and failed calls through default and renamed proxies.
  • The compatibility listing is checked against the gateway page limit in both structured-output modes.

Assessed commit: e18e7dc84468

@codecov

codecov Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.85%. Comparing base (1267bd1) to head (0658fd7).

Files with missing lines Patch % Lines
superset/mcp_service/middleware.py 87.50% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master   #45081   +/-   ##
=======================================
  Coverage   82.85%   82.85%           
=======================================
  Files        3017     3017           
  Lines      192909   192923   +14     
  Branches    44974    44976    +2     
=======================================
+ Hits       159836   159850   +14     
  Misses      30034    30034           
  Partials     3039     3039           
Flag Coverage Δ
hive 35.30% <0.00%> (-0.01%) ⬇️
mysql 53.71% <0.00%> (-0.01%) ⬇️
postgres 53.71% <0.00%> (-0.01%) ⬇️
presto 37.13% <0.00%> (-0.01%) ⬇️
python 86.50% <87.50%> (+<0.01%) ⬆️
sqlite 53.46% <0.00%> (-0.01%) ⬇️
unit 80.15% <87.50%> (+<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.

@aminghadersohi

Copy link
Copy Markdown
Contributor Author

AI review at head e388bda

Verdict: CLEAN

Reviewed the full five-file diff against master for correctness, regressions, security (against SECURITY.md), and test coverage. No actionable findings. Preserving ToolResult.is_error fixes proxied error responses without changing successful content, structured output, or authorization. The new contract tests cover discovery/schema fidelity, direct/proxy parity, denied calls, token scopes, restricted principals, permission revocation, and removed tools.

Validation:

  • Touched unit tests: test_native_tool_surface.py and test_middleware_logging.py — 93 passed.
  • Additional regression tests: test_middleware.py and test_tool_search_transform.py — 250 passed.
  • pre-commit run --files on all five branch-changed files — passed (including mypy, ruff, and pylint).
  • Diff whitespace check passed; live head reverified unchanged before posting.

No fixes or commits needed; worktree remains clean. Local Superset HTTP health was unavailable, so no live HTTP deployment validation was performed; protocol contract tests ran successfully using the in-process MCP client.

@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Acceptance test at head e388bda

Setup. Local Python 3.11 venv from requirements/development.txt (fastmcp 3.4.7), with a throwaway SQLite metadata DB, an admin user and a Gamma user. I ran the real HTTP server (superset mcp run) in both discovery modes (MCP_TOOL_SEARCH_CONFIG["enabled"] True/False), as each user, with MCP_STRUCTURED_OUTPUT_ENABLED both off and on. All calls went through a FastMCP Client over streamable HTTP. For the "before" runs, the same server was started with master's middleware.py. All servers were stopped afterwards, and the only writes were to the throwaway DB.

The PR also runs green locally: the two test files pass, 93 passed. Swapping master's middleware.py back in gives 8 failures: 7 in test_native_tool_surface.py and 1 in test_middleware_logging.py. That matches the PR body. CI is green at this head.

# Acceptance criterion (as claimed in the PR body) Result Evidence (live server)
1 Every allowed operation is exposed under its real name with description, input schema, output schema when enabled, and annotations PASS Native tools/list as admin returns 77 tools in one page (nextCursor: null) with no search_tools/call_tool. All 77 carry readOnlyHint and destructiveHint. idempotentHint is set on 30; leaving it unset on read-only tools is a gap the PR documents. With structured output on, 77/77 have outputSchema; with it off, 0/77. The inventory's 79 tools minus list_tasks/get_task_info = 77; those two are removed by the GLOBAL_TASK_FRAMEWORK flag.
1 isError, structuredContent and validation details are preserved PASS (fixed by this PR) Before/after through call_tool. Gamma create_theme: before = isError=False with "Permission denied: can_write on Theme…", after = isError=True with the same text. Missing chart_type on get_chart_type_schema: before = isError=False with "Validation error…: chart_type: Field required", after = isError=True with the same text. With the fix, all three paths (native, direct named call in compatibility mode, call_tool) return identical text and isError=True. The server log records the proxied denial as success=False; before the fix it was success=True. A successful get_chart_type_schema returns identical content on all three paths, with structuredContent present only when structured output is enabled.
2 Native mode needs no schema fetch or opaque dispatcher; compatibility mode keeps working and is tested PASS Native mode calls tools directly by name. Compatibility mode lists health_check, get_instance_info, search_tools and call_tool in 2,675 bytes; real names stay directly callable, and search_tools/call_tool work. Defaults are unchanged.
2 Migration and deprecation policy documented without breaking existing clients PASS mcp-server.mdx adds "Tool discovery modes" and "Migrating to native mode", with mixed-version and multi-pod notes. It states that compatibility mode stays supported and that any default change will be announced in UPDATING.md.
3 Canonical definitions reused, not a second catalog; both structured-output settings tested PASS The tests and the inventory are generated from the registered tools over the MCP protocol. Live: text-only native catalog is 215,049 bytes and structured is 516,627 bytes. The largest entries are manage_native_filters at 10,916 bytes text-only and generate_chart at 28,245 bytes structured, within the inventory's 2%/200-byte headroom.
4 List and call coverage for every tool; deterministic pagination; schemas valid with no dangling refs; catalog and largest tool/page measured PASS Live structured listing: all 154 input and output schemas pass Draft202012Validator.check_schema, and none contains a $ref (they are dereferenced). list_charts structuredContent validates against its advertised outputSchema. Two consecutive listings come back in the same order. No single entry is over 100 KB. The full native catalog is larger than one 100 KB page and is not paginated; the docs and tests say so.
5 Same RBAC, scopes, restricted-role policy and service flags on both paths; named calls cannot bypass filtering; permission revocation applies PASS Gamma: native tools/list shows 48 of 77 tools; create_theme is absent from both the list and search_tools, and calling it by name or through call_tool is denied with the same error. Live revocation, no restart: after granting can_write on Theme to Gamma, create_theme is listed natively, found by search, and succeeds on both paths. After revoking it, the next request hides it on both paths and denies the call on both. Flag-removed list_tasks: rejected natively and through call_tool, and absent from search. Token scopes and the restricted-principal policy are covered by the PR's contract tests, which pass, rather than this live run.
6 Superset-side changes only; existing native code retained, missing tests and docs added PASS Only middleware.py changes (+7/−1), plus tests, the inventory and docs. Native mode itself already existed.

Observation, not blocking: a tool removed by a service flag, called by name, returns Internal error in list_tasks: An unexpected error occurred rather than an "unknown tool" message. It is still rejected (isError=True) on every path, and master behaves the same way.

Verdict: PASS. No changes pushed.

@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 isError fix works, but introduces incorrect error metrics for proxied failures. All 93 focused tests passed.

🟡 Medium — Proxy validation failures inflate error metrics

At middleware.py:891–894, the outer proxy marks returned errors unsuccessful but loses the inner user-error classification. Reproduced with get_chart_type_schema({}): direct calls increment only .warning, while call_tool increments both .warning and .error, incorrectly counting ordinary validation failures as errors. Fix: suppress redundant proxy outcome metrics or preserve the inner classification, and add a proxy metrics regression test.

A failure forwarded by the call_tool proxy is returned as an error result
rather than raised, so the proxy's own call was counted as a system error in
addition to the warning or error the proxied tool had already recorded.
Skip the proxy-level outcome and timing metrics for such a returned failure;
the result still reports isError and the call is still audited as failed.

Add tests that compare the metrics of direct and proxied validation and
permission failures, direct failures with and without the proxy installed,
and proxied successes.
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Addressed in 61efcbd.

The proxy-level outcome and timing metrics are now skipped when call_tool returns a failure rather than raising it, because the proxied tool already counted that failure with its own warning/error classification. The result still carries isError, and the call is still logged as unsuccessful.

Added tests covering a proxied validation failure and a proxied permission failure (isError true, one counter, same as the direct call), direct failures with and without the proxy installed, and proxied success (unchanged). get_chart_type_schema({}) through call_tool now increments only .warning.

The managed-dashboard refusal fields added to the dashboard tool outputs grow
their recorded output schemas.

@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 default proxy issue is fixed, but remains with customized proxy names. All 97 focused tests passed.

🟡 Medium — Configured proxy names bypass the metrics fix

At middleware.py:861, suppression depends on mcp_tool, which is populated only for literal call_tool. Reproduced with call_tool_name="invoke_tool": invalid get_chart_type_schema arguments emit both get_chart_type_schema.warning and invoke_tool.error, falsely increasing aggregate error counts. Fix: recognize the configured proxy name and cover it in the metrics regression tests.

…ied failures

The proxied-failure metrics suppression keyed on the proxy being literally
named call_tool, so a renamed proxy (call_tool_name in
MCP_TOOL_SEARCH_CONFIG) counted a forwarded validation failure a second
time as an error. Resolve the proxy name from the same setting the proxy is
registered under, and cover default and custom names in the metrics tests.
@aminghadersohi

aminghadersohi commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

@rebenitez1802 Fixed in b301ec3.

The proxied-failure suppression now resolves the proxy name from MCP_TOOL_SEARCH_CONFIG["call_tool_name"], the same setting the proxy is registered under, instead of the literal call_tool. The default behaviour is unchanged. The metric-key fallback for an unregistered proxied name uses the configured name too.

The regression test in test_native_tool_surface.py is parametrized over the default and invoke_tool. Invalid get_chart_type_schema arguments now emit exactly one mcp.tool.get_chart_type_schema.warning for both names. Without the fix, the invoke_tool case fails. Unit tests in test_middleware_logging.py cover name resolution and the no-recount path. tests/unit_tests/mcp_service passes (7505 passed, 3 skipped).

@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 isError fix and the round-1/round-2 metric fixes all landed correctly, but the de-dup guard is only half-symmetric — successful proxied calls are still double-counted, and the new test hides it behind set().

Both prior comments resolved. The isError rebuild now preserves is_error (middleware.py:932), returned error results are classified as failures (middleware.py:920-923), and the configured proxy name is honored everywhere via _call_tool_proxy_name() (middleware.py:540, 682, 853) — consistent with the registration source at server.py:1105. test_forwarded_failure_through_renamed_proxy_is_not_recounted and test_proxied_failure_is_counted_once_under_any_configured_proxy_name[invoke_tool] cover exactly the renamed-proxy case I raised in round 2. 👍

Two findings inline below.

Comment thread superset/mcp_service/middleware.py Resolved
Suppress redundant proxy counters and timings for successful as well as failed calls, while retaining metrics for proxy-level exceptions. Assert exact success metric lists and cover default and configured proxy names.

@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 findings fixed exactly, and the metric de-dup is now symmetric and well covered. No blocking issues.

🟡 Medium (successful proxied calls double-counted) — resolved. The guard at middleware.py:895 is now if mcp_tool is not None and raised_is_user_error is None: return, so the outer proxy pass skips the redundant emission for both successes and failures, while a genuine proxy-level raise (raised_is_user_error set) is still counted. Docstring generalized to "An outcome the call_tool proxy merely forwards…".

🟢 Low (test masked the bug with set()) — resolved. test_proxied_success_metrics_are_unchanged now asserts proxied_keys == direct_keys and compares timing (proxied_timing == direct_timing) instead of collapsing duplicates through set(). A new test_proxied_success_is_counted_once_under_any_configured_proxy_name[call_tool, invoke_tool] pins the once-only success count under a renamed proxy too.

The mock-based unit test I'd flagged as needing rework was handled: test_metric_uses_resolved_tool_name_for_call_tool_proxy became test_forwarded_success_is_not_recounted_by_call_tool_proxy (asserts incr/timing not called), and a new test_proxy_level_exception_is_still_counted[warning, error] confirms the de-dup never suppresses an exception raised by the proxy itself.

Failure and success paths are now consistently counted once on every discovery surface. Nice work. (Note: I couldn't run the focused suite locally due to a stale-venv version skew unrelated to this PR; relying on the reported pass and CI.)

@aminghadersohi
aminghadersohi merged commit 8aeb285 into apache:master Oct 10, 2026
71 checks passed
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/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants