Skip to content

fix(mcp): expose query context to Jinja macros - #42822

Merged
aminghadersohi merged 15 commits into
apache:masterfrom
aminghadersohi:aminghadersohi/mcp-jinja-form-data
Aug 14, 2026
Merged

aminghadersohi merged 15 commits into
apache:masterfrom
aminghadersohi:aminghadersohi/mcp-jinja-form-data

Conversation

@aminghadersohi

Copy link
Copy Markdown
Contributor

SUMMARY

The chart data API makes its query request available through Flask's global form-data fallback because Jinja macros such as filter_values, get_filters, and url_param read query inputs from that context. Programmatically constructed MCP queries skipped that step, so virtual datasets and metrics using those macros could fail despite the equivalent API query succeeding.

This extracts the API's form-data assignment into a shared helper and uses it for get_chart_data and query_dataset. MCP query contexts are represented in the same datasource/queries/form-data shape consumed by the existing Jinja lookup path; no synthetic request context or duplicated macro-specific behavior is introduced.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable; this is a backend-only query execution fix.

TESTING INSTRUCTIONS

  • pytest -q tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py tests/unit_tests/mcp_service/dataset/tool/test_query_dataset.py (136 passed)
  • pytest -q tests/unit_tests/mcp_service (3318 passed; one unrelated existing health-check smoke failure because the test environment has no version string configured)
  • uvx pre-commit run --files superset/charts/data/api.py superset/charts/data/form_data.py superset/mcp_service/chart/tool/get_chart_data.py superset/mcp_service/dataset/tool/query_dataset.py tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py tests/unit_tests/mcp_service/dataset/tool/test_query_dataset.py
  • pre-commit run --all-files (Python checks passed; frontend-only hooks could not complete because frontend dependencies such as glob and postcss-styled-syntax are not installed; the formatter also reported pre-existing frontend formatting drift)

The regression tests execute filter_values and get_filters during an MCP query_dataset call and cover url_param plus implicit dataset lookup for metric() using chart-shaped query context.

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

Blast radius

This affects only MCP chart and dataset query execution plus the existing chart-data API context assignment. It does not change authorization, RLS, workspace isolation, schemas, migrations, feature flags, or non-MCP query behavior.

Risk & rollback

Risk is limited to the Flask-global form-data payload used while compiling MCP queries. The payload is built from the already validated query context and matches the existing API representation. Rollback is a revert of this commit.

Review guidance

Start with superset/charts/data/form_data.py, then verify the two MCP call sites populate it immediately before ChartDataCommand execution. The tests document the request-dependent macro boundary.

Eval evidence

No model or prompt evaluation was run because this change does not modify tool schemas, descriptions, prompts, model routing, or generated responses. The deterministic MCP regression coverage passes 136/136; the full MCP unit suite passes 3318/3319 with the environment-only health-check failure described above.

Cost & latency delta

No model parameters, prompts, or tool payload schemas changed, so token and model-cost delta is zero. The added work serializes the already-built query objects once per affected call; no external request or database query is added.

Prompt / non-determinism

No prompt, model routing, or non-deterministic behavior changed.

@github-actions github-actions Bot added the api Related to the REST API label Aug 6, 2026
@codecov

codecov Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 53.84615% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.63%. Comparing base (c395b9a) to head (958365b).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
superset/charts/data/form_data.py 43.75% 9 Missing ⚠️
superset/charts/data/api.py 75.00% 1 Missing ⚠️
superset/mcp_service/chart/tool/get_chart_data.py 50.00% 1 Missing ⚠️
superset/mcp_service/dataset/tool/query_dataset.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #42822      +/-   ##
==========================================
- Coverage   66.69%   66.63%   -0.07%     
==========================================
  Files        2872     2868       -4     
  Lines      163452   163012     -440     
  Branches    37725    37507     -218     
==========================================
- Hits       109019   108625     -394     
+ Misses      52304    52258      -46     
  Partials     2129     2129              
Flag Coverage Δ
hive 38.21% <38.46%> (+<0.01%) ⬆️
mysql 57.91% <53.84%> (-0.01%) ⬇️
postgres 57.94% <53.84%> (-0.01%) ⬇️
presto 40.16% <46.15%> (+<0.01%) ⬆️
python 59.33% <53.84%> (-0.01%) ⬇️
sqlite 57.58% <53.84%> (-0.01%) ⬇️
unit 100.00% <ø> (ø)

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 August 12, 2026 04:30
@dosubot dosubot Bot added change:backend Requires changing the backend global:jinja Related to Jinja templating labels Aug 12, 2026
Comment thread superset/charts/data/form_data.py Resolved
@bito-code-review

Copy link
Copy Markdown
Contributor

The flagged issue is correct. The set_query_context_form_data function currently only serializes queries and form_data from the QueryContext, which can omit critical fields like time_range that Jinja macros rely on for templated SQL.

To resolve this, you should update set_query_context_form_data in superset/charts/data/form_data.py to explicitly include the time_range field if it exists on the QueryContext or its query objects.

Would you like me to implement this fix and check the rest of the PR comments for you?

superset/charts/data/form_data.py

def set_query_context_form_data(
    query_context: QueryContext,
    datasource_id: int,
    datasource_type: str,
) -> None:
    """Expose a programmatically-created query like a chart data API request."""
    set_form_data(
        {
            "datasource": {"id": datasource_id, "type": datasource_type},
            "queries": [
                query.to_dict() for query in getattr(query_context, "queries", [])
            ],
            "form_data": getattr(query_context, "form_data", None) or {},
            "time_range": getattr(query_context, "time_range", None),  # Add this
        }
    )

@bito-code-review

bito-code-review Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #3a654c

Actionable Suggestions - 0
Additional Suggestions - 3
  • superset/mcp_service/chart/tool/get_chart_data.py - 1
    • Inline import at function scope · Line 666-666
      Inline import should be moved to module-level per repository convention. Rule [12745] requires module-level imports unless a circular dependency exists (must be documented). No circular dependency is evident here, and `set_query_context_form_data` has no dependencies that would cause import-time side effects.
  • superset/charts/data/form_data.py - 2
    • Code duplication with async_queries · Line 28-30
      The `set_form_data` function is identical to the one in `superset/tasks/async_queries.py` (line 50-51). Duplicating this creates maintenance risk — any future change to the implementation must be applied in two places, risking divergence.
    • Missing test coverage · Line 28-47
      While `set_query_context_form_data` is tested in `tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py:135`, the new module `superset/charts/data/form_data.py` has no dedicated test file. The `set_form_data` function lacks its own unit test coverage.
Review Details
  • Files reviewed - 6 · Commit Range: 7c75aa5..979bcc2
    • superset/charts/data/api.py
    • superset/charts/data/form_data.py
    • superset/mcp_service/chart/tool/get_chart_data.py
    • superset/mcp_service/dataset/tool/query_dataset.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
    • tests/unit_tests/mcp_service/dataset/tool/test_query_dataset.py
  • Files skipped - 0
  • 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 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

@netlify

netlify Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

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

@bito-code-review

bito-code-review Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #a0d65d

Actionable Suggestions - 0
Review Details
  • Files reviewed - 3 · Commit Range: 979bcc2..1c9a1dc
    • superset/charts/data/form_data.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
    • tests/unit_tests/mcp_service/dataset/tool/test_query_dataset.py
  • Files skipped - 0
  • 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 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

@bito-code-review

bito-code-review Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #492ac7

Actionable Suggestions - 0
Review Details
  • Files reviewed - 1 · Commit Range: 1c9a1dc..ab4a0a0
    • superset/charts/data/form_data.py
  • Files skipped - 0
  • 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 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

@gabotorresruiz gabotorresruiz 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.

Hey Amin, thanks for this fix, the missing Jinja context for programmatic MCP queries is real and worth closing, and thanks for the quick turnaround on the CI failure. Two blocking points below, both verified by execution on this head: the serializer still does not carry what most of the targeted macros read (only get_time_filter() and the implicit metric() dataset lookup actually change behavior), and the new getattr guard shapes production code around a test mock. Details inline with suggested fixes, plus one non-blocking symmetry question.

Comment thread superset/charts/data/form_data.py Resolved
Comment thread superset/charts/data/form_data.py Resolved
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Addressed the requested changes in the latest head:

  • serialize real QueryObject filters under the key consumed by Jinja macros
  • preserve time_range and hoist url_params from query-context form data
  • replace mocked to_dict() regression fixtures with real QueryObject instances
  • remove the production getattr guard and fix the OAuth test stub instead
  • move the new helper imports to module scope

Pre-commit passes on all changed files. Targeted pytest collection remains blocked only in this local workspace by its stale sqlglot installation (missing sqlglot.dialects.singlestore); CI has been triggered for head b1daf8b.

@gabotorresruiz gabotorresruiz 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.

Thanks Amin, this addressed everything and fast. I re-verified on this head with real objects rather than mocks: after set_query_context_form_data, filter_values(), get_filters(), url_param(), get_time_filter() and the implicit metric() dataset lookup all resolve correctly, and a templated virtual dataset rendered through get_query_str_extended now carries the time range and url_params into the generated SQL. The regression tests building real QueryObjects are exactly the shape that would have caught the original gap, and moving the OAuth fixture fix into the test instead of the helper keeps the production contract honest. Scoping the helper to the two MCP data-execution paths with the sibling callers as a follow-up works for me. LGTM.

@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Final review-comment audit complete:

Latest update: 8c10f89. Pre-commit passes on all changed files.

@bito-code-review bito-code-review Bot 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.

Code Review Agent Run #af39ad

Actionable Suggestions - 1
  • superset/charts/data/form_data.py - 1
Additional Suggestions - 1
  • tests/unit_tests/mcp_service/dataset/tool/test_query_dataset.py - 1
    • C098-12745: Inline import should be module-level · Line 190-190
      Inline import should be at module-level per project convention. Move `QueryObject` to the existing import block at the top of the file.
Review Details
  • Files reviewed - 7 · Commit Range: ab4a0a0..958365b
    • superset/charts/data/form_data.py
    • superset/mcp_service/chart/tool/get_chart_data.py
    • superset/mcp_service/dataset/tool/query_dataset.py
    • tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
    • tests/unit_tests/mcp_service/dataset/tool/test_query_dataset.py
    • superset/tasks/async_queries.py
    • tests/unit_tests/charts/data/form_data_test.py
  • Files skipped - 0
  • 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 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

Comment thread superset/charts/data/form_data.py Resolved
@aminghadersohi

Copy link
Copy Markdown
Contributor Author

Reviewed the remaining unresolved Bito thread. It conflated the direct Jinja template-context filter path with the Flask-global form-data fallback: the latter intentionally consumes the plural filters key via convert_legacy_filters_into_adhoc, while QueryObject.to_dict() still retains the singular filter key. Real-QueryObject regression tests and reviewer execution confirm filter_values() and get_filters() work. I replied with the technical rationale and resolved the thread.

Unresolved review threads: 0. Review status: APPROVED. Failed checks: 0.

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

Labels

api Related to the REST API change:backend Requires changing the backend global:jinja Related to Jinja templating size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants