π The fast, Pythonic way to build MCP servers and clients.
Delay import of Provider classes until FastMCP Server Creation (#1820)
William Easton4a02c9a563c7
diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.pyindex 170f5d10e..d0d749814 100644--- a/src/fastmcp/server/server.py+++ b/src/fastmcp/server/server.py@@ -208,8 +208,8 @@ class FastMCP(Generic[LifespanResultT]):# if auth is `NotSet`, try to create a provider from the environmentif auth is NotSet:if fastmcp.settings.server_auth is not None:- # ImportString returns the class itself- auth = fastmcp.settings.server_auth()+ # server_auth_class returns the class itself+ auth = fastmcp.settings.server_auth_class()else:auth = Noneself.auth = cast(AuthProvider | None, auth)diff --git a/src/fastmcp/settings.py b/src/fastmcp/settings.pyindex 431b65236..95e9f6290 100644--- a/src/fastmcp/settings.py+++ b/src/fastmcp/settings.py@@ -3,7 +3,7 @@ from __future__ import annotations as _annotationsimport inspectimport warningsfrom pathlib import Path-from typing import Annotated, Any, Literal+from typing import TYPE_CHECKING, Annotated, Any, Literalfrom pydantic import Field, ImportString, field_validatorfrom pydantic.fields import FieldInfo@@ -23,6 +23,9 @@ LOG_LEVEL = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]DuplicateBehavior = Literal["warn", "error", "replace", "ignore"]+if TYPE_CHECKING:+ from fastmcp.server.auth.auth import AuthProvider+class ExtendedEnvSettingsSource(EnvSettingsSource):"""@@ -258,7 +261,7 @@ class Settings(BaseSettings):# Auth settingsserver_auth: Annotated[- ImportString | None,+ str | None,Field(description=inspect.cleandoc("""@@ -266,9 +269,9 @@ class Settings(BaseSettings):the full module path to an AuthProvider class (e.g.,'fastmcp.server.auth.providers.google.GoogleProvider').- The specified class will be imported and instantiated automatically.- Any class that inherits from AuthProvider can be used, including- custom implementations.+ The specified class will be imported and instantiated automatically+ during FastMCP server creation. Any class that inherits from AuthProvider+ can be used, including custom implementations.If None, no automatic configuration will take place.@@ -357,6 +360,25 @@ class Settings(BaseSettings):),] = True+ @property+ def server_auth_class(self) -> AuthProvider | None:+ from fastmcp.utilities.types import get_cached_typeadapter++ if not self.server_auth:+ return None++ # https://github.com/jlowin/fastmcp/issues/1749+ # Pydantic imports the module in an ImportString during model validation, but we don't want the server+ # auth module imported during settings creation as it imports dependencies we aren't ready for yet.+ # To fix this while limiting breaking changes, we delay the import by only creating the ImportString+ # when the class is actually needed++ type_adapter = get_cached_typeadapter(ImportString)++ auth_class = type_adapter.validate_python(self.server_auth)++ return auth_class+def __getattr__(name: str):"""diff --git a/tests/server/test_server.py b/tests/server/test_server.pyindex 0b90622d9..715b8b1a9 100644--- a/tests/server/test_server.py+++ b/tests/server/test_server.py@@ -1,4 +1,7 @@import logging+from pathlib import Path+from tempfile import TemporaryDirectory+from textwrap import dedentfrom typing import Annotated, Anyimport httpx@@ -1578,3 +1581,51 @@ class TestOpenAPIExperimentalFeatureFlag:if "Using legacy OpenAPI parser" in record.message]assert len(legacy_log_messages) == 0+++class TestSettingsFromEnvironment:+ async def test_settings_from_environment_issue_1749(self):+ """Test that when auth is enabled, the server starts."""+ from fastmcp.client.transports import PythonStdioTransport+ from fastmcp.server.auth.providers.azure import AzureProvider+ from fastmcp.settings import Settings++ script = dedent("""+ import os++ os.environ["FASTMCP_SERVER_AUTH"] = "fastmcp.server.auth.providers.azure.AzureProvider"++ os.environ["FASTMCP_SERVER_AUTH_AZURE_TENANT_ID"] = "A_Valid_Value"+ os.environ["FASTMCP_SERVER_AUTH_AZURE_CLIENT_ID"] = "A_Valid_Value"+ os.environ["FASTMCP_SERVER_AUTH_AZURE_CLIENT_SECRET"] = "A_Valid_Value"+ os.environ["FASTMCP_SERVER_AUTH_AZURE_REDIRECT_PATH"] = "/auth/callback"+ os.environ["FASTMCP_SERVER_AUTH_AZURE_BASE_URL"] = "http://localhost:8000"+ os.environ["FASTMCP_SERVER_AUTH_AZURE_REQUIRED_SCOPES"] = "User.Read,email,profile"++ import fastmcp++ mcp = fastmcp.FastMCP("TestServer")++ mcp.run()+ """)++ with TemporaryDirectory() as temp_dir:+ server_file = Path(temp_dir) / "server.py"+ server_file.write_text(script)++ transport: PythonStdioTransport = PythonStdioTransport(+ script_path=server_file+ )++ async with Client[PythonStdioTransport](transport=transport) as client:+ tools = await client.list_tools()++ assert tools == []++ settings = Settings(+ server_auth="fastmcp.server.auth.providers.azure.AzureProvider"+ )++ auth_class = settings.server_auth_class++ assert auth_class is AzureProvider