π The fast, Pythonic way to build MCP servers and clients.
Advertise the MCP Apps extension only when the server serves an app (#5062)
Lancyb89222b17aa3
diff --git a/docs/apps/low-level.mdx b/docs/apps/low-level.mdxindex 4fc6a1c64..aab5a4608 100644--- a/docs/apps/low-level.mdx+++ b/docs/apps/low-level.mdx@@ -300,7 +300,25 @@ The tool generates a QR code as a base64 PNG. The resource loads the MCP Apps JS## Checking client support-Not all hosts support the Apps extension. You can check at runtime using the tool's [context](/servers/context):+FastMCP declares `io.modelcontextprotocol/ui` in `capabilities.extensions` when a registered component carries `_meta.ui`, a resource or resource template uses `ui://`, or a resource uses the MCP Apps MIME type. An untransformed server with no app components omits the declaration. Providers with transforms, proxies, and other dynamic providers retain it conservatively: they may introduce apps that cannot be inspected synchronously during capability negotiation.++Capabilities are negotiated once, when a session initializes. An app tool or `ui://` resource added while a client is connected is not advertised to that client until it reconnects; new sessions see it immediately. If your server registers apps at runtime, register the extension explicitly so every session sees it from the start:++```python+from fastmcp import FastMCP+from fastmcp.apps import UI_EXTENSION_ID+from fastmcp.server.extensions import ServerExtension+++class AppsExtension(ServerExtension):+ identifier = UI_EXTENSION_ID+++mcp = FastMCP("Dynamic Apps")+mcp.add_extension(AppsExtension())+```++Not all hosts support the Apps extension. A host that supports it declares the extension back, which is what you check at runtime using the tool's [context](/servers/context):```pythonfrom fastmcp import Contextdiff --git a/fastmcp_slim/fastmcp/apps/config.py b/fastmcp_slim/fastmcp/apps/config.pyindex 4930c25d9..eb51bc16e 100644--- a/fastmcp_slim/fastmcp/apps/config.py+++ b/fastmcp_slim/fastmcp/apps/config.py@@ -194,6 +194,22 @@ def app_config_to_meta_dict(app: AppConfig | dict[str, Any]) -> dict[str, Any]:return app+def component_serves_app(component: FastMCPComponent) -> bool:+ """Whether a component participates in the MCP Apps extension.++ A component does so by declaring ``meta["ui"]`` (``app=AppConfig(...)`` on a+ tool or resource) or by being the UI document itself: a ``ui://`` resource,+ or any resource the host would render as ``UI_MIME_TYPE``.+ """+ if component.meta and "ui" in component.meta:+ return True+ # `Resource.uri` is an AnyUrl, so compare on the string form.+ uri = getattr(component, "uri", None) or getattr(component, "uri_template", None)+ if uri is not None and str(uri).lower().startswith("ui://"):+ return True+ return getattr(component, "mime_type", None) == UI_MIME_TYPE++def is_model_visible(component: FastMCPComponent) -> bool:"""Whether a component belongs on model-facing discovery and proxy surfaces.diff --git a/fastmcp_slim/fastmcp/server/low_level.py b/fastmcp_slim/fastmcp/server/low_level.pyindex f27f07463..e46de1884 100644--- a/fastmcp_slim/fastmcp/server/low_level.py+++ b/fastmcp_slim/fastmcp/server/low_level.py@@ -555,6 +555,9 @@ class LowLevelServer(_Server[LifespanResultT]):) -> mcp_types.ServerCapabilities:"""Override to advertise registered extensions and the MCP Apps UI extension.+ The UI extension is advertised when the server may serve an app,+ including through transforms or dynamic providers (`FastMCP.may_serve_apps`).+``ServerCapabilities.extensions`` is a real declared field in v2, so weupdate it directly. The`FastMCP(experimental_capabilities=...)` merge also lives here rather@@ -578,19 +581,22 @@ class LowLevelServer(_Server[LifespanResultT]):# Advertise every registered extension's settings under# capabilities.extensions[identifier]. The hand-rolled UI splice stays# for now (MCP Apps migrates onto the extension API in a later phase);- # the two coexist. Advertisement is unconditional β the SDK's pre-2026- # version sieve strips capabilities.extensions on legacy eras, a known+ # the two coexist. It is advertised only when the server may serve an+ # app, including through transforms or dynamic providers.+ # The SDK's pre-2026 version+ # sieve strips capabilities.extensions on legacy eras, a known# limitation (sdk-feedback #2).existing_extensions = capabilities.extensions or {}registered_extensions = {extension.identifier: extension.settings()for extension in self.fastmcp._extensions.values()}+ app_extensions = {UI_EXTENSION_ID: {}} if self.fastmcp.may_serve_apps else {}return capabilities.model_copy(update={"extensions": {**existing_extensions,- UI_EXTENSION_ID: {},+ **app_extensions,**registered_extensions,},}diff --git a/fastmcp_slim/fastmcp/server/providers/aggregate.py b/fastmcp_slim/fastmcp/server/providers/aggregate.pyindex 4df9100c7..88bd376fb 100644--- a/fastmcp_slim/fastmcp/server/providers/aggregate.py+++ b/fastmcp_slim/fastmcp/server/providers/aggregate.py@@ -261,6 +261,13 @@ class AggregateProvider(Provider):def __repr__(self) -> str:return f"AggregateProvider(providers={self.providers!r})"+ @property+ def may_serve_apps(self) -> bool:+ """Whether transforms or child providers may serve MCP App UI."""+ return bool(self._transforms) or any(+ provider.may_serve_apps for provider in self.providers+ )+# -------------------------------------------------------------------------# Tools# -------------------------------------------------------------------------diff --git a/fastmcp_slim/fastmcp/server/providers/base.py b/fastmcp_slim/fastmcp/server/providers/base.pyindex aff0471f7..5e69c7a5d 100644--- a/fastmcp_slim/fastmcp/server/providers/base.py+++ b/fastmcp_slim/fastmcp/server/providers/base.py@@ -118,6 +118,23 @@ class Provider:def __repr__(self) -> str:return f"{self.__class__.__name__}()"+ @property+ def may_serve_apps(self) -> bool:+ """Whether this provider may serve MCP App UI (``meta["ui"]`` or ``ui://``).++ Advertised capabilities are a promise the server has to keep, so a+ provider that cannot be enumerated synchronously answers ``True``: a+ proxy to a remote server, or a third-party provider, may well be holding+ an app, and hiding the extension from it would leave the host unable to+ render a UI that does exist. A spurious declaration is the lesser error.++ `LocalProvider` answers from its registry, and `AggregateProvider`+ combines its children. Providers with transforms also answer `True`:+ transforms can introduce app metadata or UI resources, and their async+ methods cannot be evaluated during synchronous capability negotiation.+ """+ return True+@propertydef transforms(self) -> list[Transform]:"""All transforms applied to components from this provider."""diff --git a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.pyindex 158158db7..bd4ac2131 100644--- a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py@@ -415,6 +415,11 @@ class FastMCPProvider(Provider):super().__init__()self.server = server+ @property+ def may_serve_apps(self) -> bool:+ """Whether transforms or the wrapped server may serve MCP App UI."""+ return bool(self._transforms) or self.server.may_serve_apps+def required_extensions(self) -> Sequence[ServerExtension]:"""Expose the mounted server's bundled and auto-registerable extensions."""return self.server.required_extensions()diff --git a/fastmcp_slim/fastmcp/server/providers/local_provider/local_provider.py b/fastmcp_slim/fastmcp/server/providers/local_provider/local_provider.pyindex ebb662571..207fe61af 100644--- a/fastmcp_slim/fastmcp/server/providers/local_provider/local_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/local_provider/local_provider.py@@ -340,6 +340,24 @@ class LocalProvider(raise KeyError(f"Prompt {name!r} version {version!r} not found")self._remove_component(key)+ # =========================================================================+ # Capability queries+ # =========================================================================++ @property+ def may_serve_apps(self) -> bool:+ """Whether transforms or registered components may serve MCP App UI.++ Without transforms, the local registry can be inspected synchronously.+ Transforms may introduce apps, so retain the conservative declaration+ without running their asynchronous methods.+ """+ from fastmcp.apps.config import component_serves_app++ return bool(self._transforms) or any(+ component_serves_app(c) for c in self._components.values()+ )+# =========================================================================# Provider interface implementation# =========================================================================diff --git a/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py b/fastmcp_slim/fastmcp/server/providers/wrapped_provider.pyindex b76e2f2d3..55ba1b052 100644--- a/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py@@ -62,6 +62,11 @@ class _WrappedProvider(Provider):def __repr__(self) -> str:return f"_WrappedProvider({self._inner!r}, transforms={self._transforms!r})"+ @property+ def may_serve_apps(self) -> bool:+ """Whether transforms or the wrapped provider may serve MCP App UI."""+ return bool(self._transforms) or self._inner.may_serve_apps+# -------------------------------------------------------------------------# Delegate to inner provider's public methods (which apply inner's transforms)# -------------------------------------------------------------------------diff --git a/tests/test_apps.py b/tests/test_apps.pyindex 375db8e91..8dc189683 100644--- a/tests/test_apps.py+++ b/tests/test_apps.py@@ -6,6 +6,7 @@ extension negotiation, and the ``Context.client_supports_extension`` method.from __future__ import annotations+from collections.abc import Sequencefrom types import SimpleNamespacefrom typing import Any, cast@@ -26,8 +27,15 @@ from fastmcp.apps import (ResourcePermissions,app_config_to_meta_dict,)+from fastmcp.prompts.base import Prompt+from fastmcp.resources import Resource, ResourceTemplatefrom fastmcp.server.context import Context+from fastmcp.server.extensions import ServerExtensionfrom fastmcp.server.low_level import client_supports_extension+from fastmcp.server.providers import AggregateProvider, FastMCPProvider, Provider+from fastmcp.server.providers.local_provider import LocalProvider+from fastmcp.server.transforms import ToolTransform, Transform+from fastmcp.tools.tool_transform import ToolTransformConfig# ---------------------------------------------------------------------------# Model serialization@@ -402,7 +410,7 @@ class TestExtensionAdvertisement:async def test_capabilities_include_ui_extension(self):server = FastMCP("test")- @server.tool+ @server.tool(app=AppConfig(resource_uri="ui://dashboard"))def my_tool() -> str:return "hello"@@ -435,6 +443,258 @@ class TestExtensionAdvertisement:# ---------------------------------------------------------------------------+class TestAppCapabilityGating:+ """The UI extension is advertised only while the server can serve an app.++ Every FastMCP server used to declare it, so a host that reads the+ declaration could offer a UI affordance with no app behind it.+ """++ @staticmethod+ def _computed_extensions(server: FastMCP) -> dict[str, Any]:+ """Extensions the server computes, before the SDK's version sieve."""+ capabilities = server._mcp_server.get_capabilities()+ return dict(capabilities.extensions or {})++ def test_plain_server_does_not_advertise(self):+ server = FastMCP("test")++ @server.tool+ def my_tool() -> str:+ return "hello"++ assert UI_EXTENSION_ID not in self._computed_extensions(server)++ def test_app_tool_advertises(self):+ server = FastMCP("test")++ @server.tool(app=AppConfig(resource_uri="ui://dashboard"))+ def dashboard() -> str:+ return "data"++ assert UI_EXTENSION_ID in self._computed_extensions(server)++ def test_ui_resource_advertises(self):+ server = FastMCP("test")++ @server.resource("ui://my-app/view.html")+ def view() -> str:+ return "<html></html>"++ assert UI_EXTENSION_ID in self._computed_extensions(server)++ def test_ui_resource_template_advertises(self):+ server = FastMCP("test")++ @server.resource("ui://my-app/{name}.html")+ def view(name: str) -> str:+ return f"<html>{name}</html>"++ assert UI_EXTENSION_ID in self._computed_extensions(server)++ def test_ui_resource_with_other_mime_type_advertises(self):+ """The scheme marks the app, not the MIME type.++ An app ships more than its HTML entry point β a stylesheet served from+ ``ui://`` is explicitly ``text/css``, and the server still has an app.+ """+ server = FastMCP("test")++ @server.resource("ui://my-app/view.css", mime_type="text/css")+ def stylesheet() -> str:+ return "body {}"++ assert UI_EXTENSION_ID in self._computed_extensions(server)++ def test_mounted_app_advertises(self):+ parent = FastMCP("parent")++ @parent.tool+ def plain() -> str:+ return "x"++ child = FastMCP("child")++ @child.tool(app=AppConfig(resource_uri="ui://child/app"))+ def child_app() -> str:+ return "y"++ parent.mount(child)++ assert UI_EXTENSION_ID in self._computed_extensions(parent)++ def test_mounted_plain_child_does_not_advertise(self):+ parent = FastMCP("parent")+ child = FastMCP("child")++ @child.tool+ def plain() -> str:+ return "x"++ parent.mount(child)++ assert UI_EXTENSION_ID not in self._computed_extensions(parent)++ def test_unenumerable_provider_stays_conservative(self):+ """A provider whose components we can't enumerate keeps the promise.++ Suppressing the declaration for a proxy, or for a third-party provider,+ could hide an app that does exist β worse than a spurious promise.+ """++ class OpaqueProvider(Provider):+ pass++ server = FastMCP("test")+ server.add_provider(OpaqueProvider())++ assert UI_EXTENSION_ID in self._computed_extensions(server)++ def test_registered_extension_does_not_imply_apps(self):+ """An unrelated extension advertises itself without dragging UI along."""++ class Other(ServerExtension):+ identifier = "com.example/other"++ def settings(self) -> dict[str, Any]:+ return {"version": "1"}++ server = FastMCP("test")+ server.add_extension(Other())++ extensions = self._computed_extensions(server)+ assert extensions["com.example/other"] == {"version": "1"}+ assert UI_EXTENSION_ID not in extensions++ async def test_modern_client_sees_no_ui_extension_without_apps(self):+ """The reporter's observation, on the era that carries extensions."""+ server = FastMCP("test")++ @server.tool+ def my_tool() -> str:+ return "hello"++ async with Client(server, mode="auto") as client:+ extensions = client.server_capabilities.extensions or {}+ assert UI_EXTENSION_ID not in extensions++ @pytest.mark.parametrize(+ "scope", ["server", "local", "wrapped", "aggregate", "fastmcp"]+ )+ async def test_tool_transform_apps_advertised(self, scope: str):+ server = FastMCP("test")+ local = LocalProvider()++ @local.tool+ def plain() -> str:+ return "hello"++ transform = ToolTransform(+ {"plain": ToolTransformConfig(meta={"ui": {"resourceUri": "ui://app"}})}+ )+ if scope == "server":+ server.add_provider(local)+ server.add_transform(transform)+ else:+ provider: Provider = local+ if scope == "aggregate":+ provider = AggregateProvider([local])+ elif scope == "fastmcp":+ child = FastMCP("child")+ child.add_provider(local)+ provider = FastMCPProvider(child)+ if scope == "wrapped":+ provider = provider.wrap_transform(transform)+ else:+ provider.add_transform(transform)+ server.add_provider(provider)++ async with Client(server, mode="auto") as client:+ tools = await client.list_tools()+ assert len(tools) == 1+ assert tools[0].meta is not None+ assert tools[0].meta["ui"]["resourceUri"] == "ui://app"+ assert UI_EXTENSION_ID in (client.server_capabilities.extensions or {})++ async def test_custom_transform_non_tool_apps_advertised(self):+ class AddAppMetadata(Transform):+ async def list_resources(+ self, resources: Sequence[Resource]+ ) -> Sequence[Resource]:+ return [+ r.model_copy(update={"meta": {"ui": {"prefersBorder": True}}})+ for r in resources+ ]++ async def list_resource_templates(+ self, templates: Sequence[ResourceTemplate]+ ) -> Sequence[ResourceTemplate]:+ return [+ t.model_copy(update={"meta": {"ui": {"prefersBorder": True}}})+ for t in templates+ ]++ async def list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt]:+ return [+ p.model_copy(update={"meta": {"ui": {"resourceUri": "ui://app"}}})+ for p in prompts+ ]++ server = FastMCP("test")++ @server.resource("data://plain")+ def plain_resource() -> str:+ return "hello"++ @server.resource("data://plain/{name}")+ def plain_template(name: str) -> str:+ return name++ @server.prompt+ def plain_prompt() -> str:+ return "hello"++ server.add_transform(AddAppMetadata())+ async with Client(server, mode="auto") as client:+ resources = await client.list_resources()+ templates = await client.list_resource_templates()+ prompts = await client.list_prompts()+ for components in (resources, templates, prompts):+ assert len(components) == 1+ assert components[0].meta is not None+ assert "ui" in components[0].meta+ assert UI_EXTENSION_ID in (client.server_capabilities.extensions or {})++ async def test_runtime_app_reaches_only_new_sessions(self):+ """Capabilities are fixed at initialize, so a runtime app waits for a reconnect."""+ server = FastMCP("test")++ def register_app() -> None:+ @server.tool(app=AppConfig(resource_uri="ui://late/app"))+ def late_app() -> str:+ return "late"++ async with Client(server, mode="auto") as client:+ register_app()+ assert "late_app" in {t.name for t in await client.list_tools()}+ assert UI_EXTENSION_ID not in (client.server_capabilities.extensions or {})++ async with Client(server, mode="auto") as client:+ assert UI_EXTENSION_ID in (client.server_capabilities.extensions or {})++ async def test_explicit_extension_advertises_without_apps(self):+ """Servers that add apps at runtime can keep the declaration up front."""++ class AppsExtension(ServerExtension):+ identifier = UI_EXTENSION_ID++ server = FastMCP("test")+ server.add_extension(AppsExtension())++ async with Client(server, mode="auto") as client:+ assert UI_EXTENSION_ID in (client.server_capabilities.extensions or {})++class TestContextClientSupportsExtension:async def test_returns_false_when_no_session(self):server = FastMCP("test")