Skip to content

fix(mcp): resolve Flask app context error in MCP tools - #37309

Merged
rusackas merged 1 commit into
apache:masterfrom
aminghadersohi:amin/fix-mcp-flask-app-context-v2
Jan 21, 2026
Merged

rusackas merged 1 commit into
apache:masterfrom
aminghadersohi:amin/fix-mcp-flask-app-context-v2

Conversation

@aminghadersohi

Copy link
Copy Markdown
Contributor

SUMMARY

Flask-AppBuilder deprecated appbuilder.app - it now returns a LocalProxy to current_app instead of the actual Flask app instance.

Root Cause:
The previous code in superset/mcp_service/flask_singleton.py checked appbuilder.app is not None which always returned True because it compared a LocalProxy object (not None) rather than the resolved value. This caused the code to store the LocalProxy instead of the actual Flask app.

When MCP tools later called app.app_context() outside of a Flask context (e.g., in HTTP server mode with uvicorn), the LocalProxy couldn't resolve, causing:

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context().

Fix:

  • Check appbuilder._session is not None to properly detect if appbuilder was initialized via init_app()
  • Use current_app._get_current_object() to get the actual Flask app instance when in an app context
  • Create a minimal Flask app when not in an app context (standalone MCP server mode)

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Before:

[01/21/26 11:46:33] Error calling tool 'health_check'                           
                    RuntimeError: Working outside of application context.

After:

Calling health_check tool...
SUCCESS! Result: <fastmcp.tools.tool.ToolResult object at 0x12e3194c0>
INFO:superset.mcp_service.system.tool.health_check:Health check completed successfully

TESTING INSTRUCTIONS

  1. Start the MCP server in HTTP mode:

    superset mcp run
  2. Call the health_check tool (or any MCP tool) - it should now work without the "Working outside of application context" error

  3. Alternatively, test programmatically:

    import asyncio
    from superset.mcp_service.app import mcp
    
    tools = mcp._tool_manager._tools
    health_check_tool = tools.get('health_check')
    result = asyncio.run(health_check_tool.run(arguments={}))
    print(result)  # Should succeed

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

Flask-AppBuilder deprecated `appbuilder.app` - it now returns a
LocalProxy to `current_app` instead of the actual Flask app instance.

The previous code checked `appbuilder.app is not None` which always
returned True (comparing LocalProxy object identity, not the resolved
value), causing it to store the LocalProxy instead of the actual app.

When MCP tools later called `app.app_context()` outside of a Flask
context, the LocalProxy couldn't resolve, causing:
"RuntimeError: Working outside of application context"

This fix:
- Checks `appbuilder._session is not None` to properly detect if
  appbuilder was initialized via init_app()
- Uses `current_app._get_current_object()` to get the actual Flask app
  when in an app context
- Creates a minimal Flask app when not in an app context (standalone
  MCP server mode)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@codeant-ai-for-open-source

Copy link
Copy Markdown
Contributor

CodeAnt AI is reviewing your PR.


Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@bito-code-review

bito-code-review Bot commented Jan 21, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #5ceba3

Actionable Suggestions - 0
Review Details
  • Files reviewed - 1 · Commit Range: 6f90b63..6f90b63
    • superset/mcp_service/flask_singleton.py
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ 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 evan@preset.io.

Documentation & Help

AI Code Review powered by Bito Logo

@dosubot dosubot Bot added the change:backend Requires changing the backend label Jan 21, 2026
@codeant-ai-for-open-source

Copy link
Copy Markdown
Contributor

CodeAnt AI finished reviewing your PR.

@netlify

netlify Bot commented Jan 21, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 6f90b63
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/69710acdcf2c730008e03c22
😎 Deploy Preview https://deploy-preview-37309--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

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

@codecov

codecov Bot commented Jan 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.59%. Comparing base (13013bb) to head (6f90b63).
⚠️ Report is 12 commits behind head on master.

Files with missing lines Patch % Lines
superset/mcp_service/flask_singleton.py 0.00% 8 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           master   #37309       +/-   ##
===========================================
+ Coverage        0   67.59%   +67.59%     
===========================================
  Files           0      644      +644     
  Lines           0    48319    +48319     
  Branches        0     5300     +5300     
===========================================
+ Hits            0    32663    +32663     
- Misses          0    14365    +14365     
- Partials        0     1291     +1291     
Flag Coverage Δ
hive 42.68% <0.00%> (?)
mysql 65.63% <0.00%> (?)
postgres 65.68% <0.00%> (?)
presto 46.26% <0.00%> (?)
python 67.56% <0.00%> (?)
sqlite 65.40% <0.00%> (?)
unit 100.00% <ø> (?)

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

☔ View full report in Codecov by Sentry.
📢 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.

@villebro villebro left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems we've been playing whack-a-mole on this, let's hope this finally resolves the remaining issues 😃

@sadpandajoe sadpandajoe added the review:checkpoint Last PR reviewed during the daily review standup label Jan 21, 2026
@rusackas
rusackas merged commit ec36791 into apache:master Jan 21, 2026
79 of 80 checks passed
@sadpandajoe sadpandajoe removed the review:checkpoint Last PR reviewed during the daily review standup label Jan 26, 2026
alex-poor pushed a commit to alex-poor/superset that referenced this pull request Mar 15, 2026
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
qfcwell pushed a commit to qfcwell/superset that referenced this pull request May 12, 2026
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

change:backend Requires changing the backend size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants