Skip to content

Commit 51f71b2

Browse files
eschuthoclauderusackassadpandajoe
authored
feat(mcp): allow skipping MCP host-tool registration in non-MCP processes (#43842)
Signed-off-by: Elizabeth Thompson <elizabeth@preset.io> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: Evan Rusackas <evan@preset.io> Co-authored-by: Evan Rusackas <evan@rusackas.com> Co-authored-by: Joe Li <joe@preset.io>
1 parent 0d8bb37 commit 51f71b2

4 files changed

Lines changed: 315 additions & 11 deletions

File tree

‎superset/config.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,17 @@ class D3TimeFormat(TypedDict, total=False):
721721
# - stable: Production-ready, tested and supported
722722
# - deprecated: Will be removed in a future major release
723723

724+
# Whether this process registers the MCP *host tools* at startup. Registering
725+
# them imports the MCP service app, which has a real per-process memory cost, and
726+
# only processes that serve MCP (the web app and the standalone MCP service) need
727+
# them. Deployments can set this to False for processes that never serve MCP (e.g.
728+
# Celery workers) to avoid that cost.
729+
#
730+
# This gates only host-tool registration. The MCP decorators (@tool/@prompt) are
731+
# always registered regardless of this flag, so extensions that apply them at
732+
# import time keep working in every process.
733+
CORE_MCP_HOST_TOOLS_ENABLED = True
734+
724735
DEFAULT_FEATURE_FLAGS: dict[str, bool] = {
725736
# =================================================================
726737
# IN DEVELOPMENT

‎superset/core/mcp/core_mcp_injection.py‎

Lines changed: 121 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424

2525
import inspect
2626
import logging
27+
import sys
2728
from typing import Any, Callable, get_type_hints, Optional, TypeVar
2829

2930
from pydantic import TypeAdapter
@@ -40,6 +41,60 @@
4041

4142
logger = logging.getLogger(__name__)
4243

44+
# The concrete ``@tool``/``@prompt`` decorators register with the FastMCP instance
45+
# that lives in ``superset.mcp_service.app``. That module is the memory-heavy part
46+
# of MCP setup and is imported by ``initialize_core_mcp_host_tools`` before any
47+
# extension applies a decorator. Processes that never serve MCP (e.g. Celery
48+
# workers with ``CORE_MCP_HOST_TOOLS_ENABLED = False``) only swap the decorators
49+
# and never import it. In those processes a decoration must stay a no-op rather
50+
# than importing the service app on demand -- otherwise applying ``@tool`` in an
51+
# extension would still load the host-tool stack and defeat the memory savings.
52+
_MCP_SERVICE_APP_MODULE = "superset.mcp_service.app"
53+
54+
55+
def _mcp_host_tools_loaded() -> bool:
56+
"""Whether the MCP service app (and thus the host tools) is loaded here."""
57+
return _MCP_SERVICE_APP_MODULE in sys.modules
58+
59+
60+
# Registrations already reported as skipped, so each one is logged only once.
61+
_skipped_registrations: set[str] = set()
62+
63+
64+
def _warn_skipped_registration(kind: str, base_id: str) -> None:
65+
"""
66+
Log (once per registration) that an ``@tool``/``@prompt`` decoration was
67+
skipped because the MCP service app is not loaded in this process.
68+
69+
This is the intended behavior in processes that never serve MCP, but if
70+
``CORE_MCP_HOST_TOOLS_ENABLED = False`` reaches a process that does serve
71+
MCP, the registration would otherwise vanish without any trace.
72+
"""
73+
registration_id, _ = _get_prefixed_id_with_context(base_id)
74+
key = f"{kind}:{registration_id}"
75+
if key in _skipped_registrations:
76+
return
77+
_skipped_registrations.add(key)
78+
logger.warning(
79+
"Skipping MCP %s registration for %s: the MCP service app is not loaded "
80+
"in this process. This is expected in processes that do not serve MCP "
81+
"(CORE_MCP_HOST_TOOLS_ENABLED = False). If this process serves MCP, check "
82+
"that the setting is enabled and that initialize_core_mcp_host_tools() did "
83+
"not fail to import the service app, so the %s is registered.",
84+
kind,
85+
registration_id,
86+
kind,
87+
)
88+
89+
90+
def _fastmcp_available() -> bool:
91+
"""Whether the optional ``fastmcp`` dependency is installed."""
92+
try:
93+
from fastmcp.tools import Tool # noqa: F401
94+
except ImportError:
95+
return False
96+
return True
97+
4398

4499
def _strip_schema_titles(value: Any) -> Any:
45100
"""Remove generated JSON Schema titles while preserving useful metadata."""
@@ -142,7 +197,7 @@ def _get_prefixed_id_with_context(base_id: str) -> tuple[str, str]:
142197
return prefixed_id, context_type
143198

144199

145-
def create_tool_decorator(
200+
def create_tool_decorator( # noqa: C901
146201
func_or_name: str | Callable[..., Any] | None = None,
147202
*,
148203
name: Optional[str] = None,
@@ -181,6 +236,13 @@ def create_tool_decorator(
181236
"""
182237

183238
def decorator(func: F) -> Callable[..., Any]:
239+
# Skip registration when the MCP service app is not loaded in this
240+
# process, so applying @tool never imports the heavy host-tool stack
241+
# (see the module-level note on _MCP_SERVICE_APP_MODULE).
242+
if not _mcp_host_tools_loaded():
243+
_warn_skipped_registration("tool", name or func.__name__)
244+
return func
245+
184246
try:
185247
# Import here to avoid circular imports
186248
from superset.mcp_service.app import mcp
@@ -304,6 +366,13 @@ def create_prompt_decorator(
304366
"""
305367

306368
def decorator(func: F) -> Callable[..., Any]:
369+
# Skip registration when the MCP service app is not loaded in this
370+
# process, so applying @prompt never imports the heavy host-tool stack
371+
# (see the module-level note on _MCP_SERVICE_APP_MODULE).
372+
if not _mcp_host_tools_loaded():
373+
_warn_skipped_registration("prompt", name or func.__name__)
374+
return func
375+
307376
try:
308377
# Import here to avoid circular imports
309378
from superset.mcp_service.app import mcp
@@ -372,18 +441,25 @@ def parameterized_decorator(func: F) -> Callable[..., Any]:
372441
return parameterized_decorator
373442

374443

375-
def initialize_core_mcp_dependencies() -> None:
444+
def initialize_core_mcp_decorators() -> None:
376445
"""
377-
Initialize MCP dependency injection by replacing abstract functions
378-
in superset_core.api.mcp with concrete implementations.
379-
380-
Also imports MCP service app to register all host tools BEFORE extension loading.
446+
Replace the abstract MCP decorators in ``superset_core.mcp.decorators`` with
447+
concrete host implementations.
448+
449+
This must run in *every* process that may import extensions -- not only those
450+
that serve MCP. Extensions can apply ``@tool``/``@prompt`` at import time, and
451+
the abstract decorators raise ``NotImplementedError`` until they are replaced
452+
here, so skipping this step would break such extensions at import. It is
453+
comparatively cheap: it does not import the MCP service app or register any
454+
host tools (see ``initialize_core_mcp_host_tools`` for that). The concrete
455+
decorators it installs are also lazy -- applying ``@tool``/``@prompt`` only
456+
registers (and imports the service app) in processes where the host tools are
457+
already loaded, so extensions stay import-safe without pulling in the
458+
host-tool stack when it is disabled.
381459
"""
382460
import superset_core.mcp.decorators
383461

384-
try:
385-
from fastmcp.tools import Tool # noqa: F401
386-
except ImportError:
462+
if not _fastmcp_available():
387463
logger.info(
388464
"fastmcp is not installed, skipping MCP initialization. "
389465
"Install it with: pip install 'apache-superset[fastmcp]'"
@@ -396,6 +472,26 @@ def initialize_core_mcp_dependencies() -> None:
396472

397473
logger.info("MCP dependency injection initialized successfully")
398474

475+
476+
def initialize_core_mcp_host_tools() -> None:
477+
"""
478+
Import the MCP service app so that all host tools are registered BEFORE
479+
extension loading.
480+
481+
This carries a real per-process memory cost -- it imports the MCP service app
482+
and every host tool module -- and is only needed in processes that actually
483+
serve MCP (the web app and the standalone MCP service). Deployments gate it
484+
off (``CORE_MCP_HOST_TOOLS_ENABLED = False``) for processes that never serve
485+
MCP, e.g. Celery workers.
486+
487+
Like ``initialize_core_mcp_decorators``, this is a quiet no-op when the
488+
optional ``fastmcp`` dependency is not installed, since the service app
489+
cannot be imported without it.
490+
"""
491+
if not _fastmcp_available():
492+
logger.debug("fastmcp is not installed, skipping MCP host tool registration")
493+
return
494+
399495
try:
400496
# Import MCP service app to register host tools BEFORE extension loading
401497
# This prevents host tools from being registered during extension context
@@ -404,3 +500,19 @@ def initialize_core_mcp_dependencies() -> None:
404500
logger.info("MCP service app imported - host tools registered")
405501
except Exception as e:
406502
logger.error("Failed to register MCP host tools: %s", e)
503+
504+
505+
def initialize_core_mcp_dependencies() -> None:
506+
"""
507+
Initialize MCP dependency injection by replacing abstract functions
508+
in superset_core.mcp.decorators with concrete implementations, then registering the
509+
host tools.
510+
511+
Kept for backwards compatibility and callers that want the full MCP setup in a
512+
single call. Processes that must avoid the host-tool import cost should instead
513+
call ``initialize_core_mcp_decorators`` unconditionally and gate
514+
``initialize_core_mcp_host_tools`` on ``CORE_MCP_HOST_TOOLS_ENABLED`` (see
515+
``SupersetAppInitializer.init_core_dependencies``).
516+
"""
517+
initialize_core_mcp_decorators()
518+
initialize_core_mcp_host_tools()

‎superset/initialization/__init__.py‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -636,11 +636,24 @@ def init_core_dependencies(self) -> None:
636636
initialize_core_api_dependencies,
637637
)
638638
from superset.core.mcp.core_mcp_injection import (
639-
initialize_core_mcp_dependencies,
639+
initialize_core_mcp_decorators,
640+
initialize_core_mcp_host_tools,
640641
)
641642

642643
initialize_core_api_dependencies()
643-
initialize_core_mcp_dependencies()
644+
645+
# The MCP decorators (@tool/@prompt) must be registered in every process:
646+
# extensions can apply them at import time, and the abstract versions raise
647+
# NotImplementedError until they are swapped for the concrete ones. This is
648+
# cheap and does not import the MCP service app.
649+
initialize_core_mcp_decorators()
650+
651+
# Registering the MCP host tools imports the MCP service app, which has a
652+
# real per-process memory cost. Only processes that serve MCP (the web app
653+
# and the standalone MCP service) need it, so deployments can disable it for
654+
# processes that never serve MCP -- e.g. Celery workers -- to avoid the cost.
655+
if self.config.get("CORE_MCP_HOST_TOOLS_ENABLED", True):
656+
initialize_core_mcp_host_tools()
644657

645658
def init_all_dependencies_and_extensions(self) -> None:
646659
"""

0 commit comments

Comments
 (0)