π The fast, Pythonic way to build MCP servers and clients.
fix(server): fall back to the highest authorized version on direct lookup (#5169)
Gregory Shklovskib45f579a3942
diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.pyindex 7d4632314..c37bf7e0a 100644--- a/fastmcp_slim/fastmcp/server/server.py+++ b/fastmcp_slim/fastmcp/server/server.py@@ -7,6 +7,7 @@ import loggingimport secretsfrom collections.abc import (AsyncGenerator,+ Awaitable,Callable,Sequence,)@@ -217,6 +218,31 @@ logging.getLogger("mcp.server.lowlevel.server").addFilter()F = TypeVar("F", bound=Callable[..., Any])+ComponentT = TypeVar("ComponentT", bound=FastMCPComponent)+++async def _highest_available_version(+ candidates: Sequence[FastMCPComponent],+ lookup: Callable[[VersionSpec], Awaitable[ComponentT | None]],+) -> ComponentT | None:+ """Look up each candidate version, highest first, until one is returned.++ Each version goes through `lookup`, the same path an explicit version+ request takes, so transforms, `get_*` overrides, and auth decide the+ fallback exactly as they would decide a direct request for that version.+ Unversioned candidates are skipped: they have no lower version to fall+ back to.+ """+ tried: set[str] = set()+ for candidate in sorted(candidates, key=version_sort_key, reverse=True):+ if candidate.version is None or candidate.version in tried:+ continue+ tried.add(candidate.version)+ found = await lookup(VersionSpec(eq=candidate.version))+ if found is not None:+ return found+ return None+DuplicateBehavior = Literal["warn", "error", "replace", "ignore"]@@ -1039,8 +1065,9 @@ class FastMCP(transforms (including session-level) have been applied. This ensuressession transforms can override provider-level disables.- When the highest version is disabled and no explicit version was- requested, falls back to the next-highest enabled version.+ When the highest version is disabled or unauthorized and no explicit+ version was requested, falls back to the highest version that is+ both enabled and authorized, matching what the list methods expose.A tool from `ToolInjectionMiddleware` takes precedence over a providertool with the same name. It is matched by name alone, so a requested@@ -1064,37 +1091,35 @@ class FastMCP(return injected if await _component_auth_allows(injected) else Nonetool = await super().get_tool(name, version)- if tool is None:- return None-- # Apply session transforms to single item- tools = await apply_session_transforms([tool])- # Transforms can change what `auth` sees (a tag, for one), so the check made- # on the pre-transform component is not enough.- if tools and is_enabled(tools[0]) and await _component_auth_allows(tools[0]):- return tools[0]+ if tool is not None:+ # Apply session transforms to single item+ tools = await apply_session_transforms([tool])+ # Transforms can change what `auth` sees (a tag, for one), so the+ # check made on the pre-transform component is not enough.+ if (+ tools+ and is_enabled(tools[0])+ and await _component_auth_allows(tools[0])+ ):+ return tools[0]- # The highest version is disabled. If an explicit version was- # requested, respect that. Otherwise fall back to the next-highest- # enabled version.+ # The highest version is disabled or unauthorized (provider lookups+ # return None for an unauthorized tool). If an explicit version was+ # requested, respect that. Otherwise fall back to the highest version+ # that is both enabled and authorized, consistent with list_tools.if version is not None:return None- all_tools = [t for t in await super().list_tools() if t.name == name]+ candidates = [t for t in await super().list_tools() if t.name == name]# During a hashed lookup, only versions of the identity being looked# up qualify; another tool listed under the same name does not.found = hashed_lookup_target(self)if found is not None:identity = tool_identity(found)- all_tools = [t for t in all_tools if tool_identity(t) == identity]- all_tools = list(await apply_session_transforms(all_tools))- enabled = [t for t in all_tools if is_enabled(t)]-- authorized = [t for t in enabled if await _component_auth_allows(t)]-- if not authorized:- return None- return max(authorized, key=version_sort_key)+ candidates = [t for t in candidates if tool_identity(t) == identity]+ return await _highest_available_version(+ candidates, lambda spec: self.get_tool(name, spec)+ )async def list_resources(self, *, run_middleware: bool = True@@ -1190,8 +1215,9 @@ class FastMCP(Overrides Provider.get_resource() to add visibility filtering after alltransforms (including session-level) have been applied.- When the highest version is disabled and no explicit version was- requested, falls back to the next-highest enabled version.+ When the highest version is disabled or unauthorized and no explicit+ version was requested, falls back to the highest version that is+ both enabled and authorized, matching what the list methods expose.Args:uri: The resource URI.@@ -1214,41 +1240,29 @@ class FastMCP(try:resource = await super().get_resource(uri, version)except AuthorizationError:- return None, True- if resource is None:- return None, False-- # Apply session transforms to single item- resources = await apply_session_transforms([resource])- if (- resources- and is_enabled(resources[0])- and await _component_auth_allows(resources[0])- ):- return resources[0], True+ # The highest version exists but is unauthorized; fall back below.+ pass+ else:+ if resource is None:+ return None, False++ # Apply session transforms to single item+ resources = await apply_session_transforms([resource])+ if (+ resources+ and is_enabled(resources[0])+ and await _component_auth_allows(resources[0])+ ):+ return resources[0], Trueif version is not None:return None, True- all_resources = [r for r in await super().list_resources() if str(r.uri) == uri]- all_resources = list(await apply_session_transforms(all_resources))- enabled = [r for r in all_resources if is_enabled(r)]-- skip_auth, token = _get_auth_context()- authorized: list[Resource] = []- for r in enabled:- if not skip_auth and r.auth is not None:- ctx = AuthContext(token=token, component=r)- try:- if not await run_auth_checks(r.auth, ctx):- continue- except AuthorizationError:- continue- authorized.append(r)-- if not authorized:- return None, True- return max(authorized, key=version_sort_key), True+ candidates = [r for r in await super().list_resources() if str(r.uri) == uri]+ resource = await _highest_available_version(+ candidates, lambda spec: self.get_resource(uri, spec)+ )+ return resource, Trueasync def list_resource_templates(self, *, run_middleware: bool = True@@ -1345,8 +1359,9 @@ class FastMCP(Overrides Provider.get_resource_template() to add visibility filtering afterall transforms (including session-level) have been applied.- When the highest version is disabled and no explicit version was- requested, falls back to the next-highest enabled version.+ When the highest version is disabled or unauthorized and no explicit+ version was requested, falls back to the highest version that is+ both enabled and authorized, matching what the list methods expose.Args:uri: The template URI.@@ -1356,46 +1371,32 @@ class FastMCP(The template if found and enabled, None otherwise."""template = await super().get_resource_template(uri, version)- if template is None:- return None+ if template is not None:+ # Apply session transforms to single item+ templates = await apply_session_transforms([template])+ # Transforms can change what `auth` sees (a tag, for one), so the+ # check made on the pre-transform component is not enough.+ if (+ templates+ and is_enabled(templates[0])+ and await _component_auth_allows(templates[0])+ ):+ return templates[0]- # Apply session transforms to single item- templates = await apply_session_transforms([template])- # Transforms can change what `auth` sees (a tag, for one), so the check made- # on the pre-transform component is not enough.- if (- templates- and is_enabled(templates[0])- and await _component_auth_allows(templates[0])- ):- return templates[0]+ # The highest version is disabled or unauthorized (provider lookups+ # return None for an unauthorized template).if version is not None:return None- all_templates = [+ candidates = [tfor t in await super().list_resource_templates()if t.matches(uri) is not None]- all_templates = list(await apply_session_transforms(all_templates))- enabled = [t for t in all_templates if is_enabled(t)]-- skip_auth, token = _get_auth_context()- authorized: list[ResourceTemplate] = []- for t in enabled:- if not skip_auth and t.auth is not None:- ctx = AuthContext(token=token, component=t)- try:- if not await run_auth_checks(t.auth, ctx):- continue- except AuthorizationError:- continue- authorized.append(t)-- if not authorized:- return None- return max(authorized, key=version_sort_key)+ return await _highest_available_version(+ candidates, lambda spec: self.get_resource_template(uri, spec)+ )async def list_prompts(self, *, run_middleware: bool = True) -> Sequence[Prompt]:"""List all enabled prompts from providers.@@ -1480,8 +1481,9 @@ class FastMCP(Overrides Provider.get_prompt() to add visibility filtering after alltransforms (including session-level) have been applied.- When the highest version is disabled and no explicit version was- requested, falls back to the next-highest enabled version.+ When the highest version is disabled or unauthorized and no explicit+ version was requested, falls back to the highest version that is+ both enabled and authorized, matching what the list methods expose.Args:name: The prompt name.@@ -1491,42 +1493,28 @@ class FastMCP(The prompt if found and enabled, None otherwise."""prompt = await super().get_prompt(name, version)- if prompt is None:- return None+ if prompt is not None:+ # Apply session transforms to single item+ prompts = await apply_session_transforms([prompt])+ # Transforms can change what `auth` sees (a tag, for one), so the+ # check made on the pre-transform component is not enough.+ if (+ prompts+ and is_enabled(prompts[0])+ and await _component_auth_allows(prompts[0])+ ):+ return prompts[0]- # Apply session transforms to single item- prompts = await apply_session_transforms([prompt])- # Transforms can change what `auth` sees (a tag, for one), so the check made- # on the pre-transform component is not enough.- if (- prompts- and is_enabled(prompts[0])- and await _component_auth_allows(prompts[0])- ):- return prompts[0]+ # The highest version is disabled or unauthorized (provider lookups+ # return None for an unauthorized prompt).if version is not None:return None- all_prompts = [p for p in await super().list_prompts() if p.name == name]- all_prompts = list(await apply_session_transforms(all_prompts))- enabled = [p for p in all_prompts if is_enabled(p)]-- skip_auth, token = _get_auth_context()- authorized: list[Prompt] = []- for p in enabled:- if not skip_auth and p.auth is not None:- ctx = AuthContext(token=token, component=p)- try:- if not await run_auth_checks(p.auth, ctx):- continue- except AuthorizationError:- continue- authorized.append(p)-- if not authorized:- return None- return max(authorized, key=version_sort_key)+ candidates = [p for p in await super().list_prompts() if p.name == name]+ return await _highest_available_version(+ candidates, lambda spec: self.get_prompt(name, spec)+ )async def call_tool(self,diff --git a/tests/server/versioning/test_auth_version_fallback.py b/tests/server/versioning/test_auth_version_fallback.pynew file mode 100644index 000000000..eeeb40f34--- /dev/null+++ b/tests/server/versioning/test_auth_version_fallback.py@@ -0,0 +1,212 @@+"""Tests for version fallback when the highest version is unauthorized.++Regression tests for https://github.com/jlowin/fastmcp/issues/4950:+When the highest version of a component fails component-level auth, get_*+methods should fall back to the highest authorized version instead of+returning None, matching what list_* already exposes.+"""+# ruff: noqa: F811 # Intentional function redefinition for version testing++from __future__ import annotations++from mcp.server.auth.middleware.auth_context import auth_context_var+from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser+from mcp_types import TextContent++from fastmcp import FastMCP+from fastmcp.server.auth import AccessToken, require_scopes+from fastmcp.utilities.versions import VersionSpec+++def _make_token(scopes: list[str] | None = None) -> AccessToken:+ """Create a test access token."""+ return AccessToken(+ token="test-token",+ client_id="test-client",+ scopes=scopes or [],+ expires_at=None,+ claims={},+ )+++def _set_token(token: AccessToken | None):+ """Set the access token in the auth context var."""+ if token is None:+ return auth_context_var.set(None)+ return auth_context_var.set(AuthenticatedUser(token))+++def _server_with_protected_v2() -> FastMCP:+ mcp = FastMCP()++ @mcp.tool(version="1.0")+ def calc() -> int:+ return 1++ @mcp.tool(version="2.0", auth=require_scopes("admin"))+ def calc() -> int:+ return 2++ return mcp+++class TestToolAuthVersionFallback:+ """Direct tool lookups must agree with list_tools under auth filtering."""++ async def test_list_tools_shows_v1_when_v2_unauthorized(self):+ mcp = _server_with_protected_v2()++ tools = await mcp.list_tools()+ assert [(t.name, t.version) for t in tools] == [("calc", "1.0")]++ async def test_get_tool_returns_v1_when_v2_unauthorized(self):+ mcp = _server_with_protected_v2()++ tool = await mcp.get_tool("calc")+ assert tool is not None+ assert tool.version == "1.0"++ async def test_call_tool_uses_v1_when_v2_unauthorized(self):+ mcp = _server_with_protected_v2()++ result = await mcp.call_tool("calc", {})+ assert isinstance(result.content[0], TextContent)+ assert result.content[0].text == "1"++ async def test_get_tool_explicit_unauthorized_version_returns_none(self):+ """An explicitly requested version is still authorized on its own."""+ mcp = _server_with_protected_v2()++ tool = await mcp.get_tool("calc", VersionSpec(eq="2.0"))+ assert tool is None++ async def test_get_tool_returns_v2_for_authorized_user(self):+ mcp = _server_with_protected_v2()++ tok = _set_token(_make_token(scopes=["admin"]))+ try:+ tool = await mcp.get_tool("calc")+ assert tool is not None+ assert tool.version == "2.0"+ finally:+ auth_context_var.reset(tok)++ async def test_get_tool_all_versions_unauthorized_returns_none(self):+ mcp = FastMCP()++ @mcp.tool(version="1.0", auth=require_scopes("admin"))+ def calc() -> int:+ return 1++ @mcp.tool(version="2.0", auth=require_scopes("admin"))+ def calc() -> int:+ return 2++ tool = await mcp.get_tool("calc")+ assert tool is None++ async def test_get_tool_skips_disabled_and_unauthorized_versions(self):+ """Fallback picks the highest version that is both enabled and authorized."""+ mcp = FastMCP()++ @mcp.tool(version="1.0")+ def calc() -> int:+ return 1++ @mcp.tool(version="2.0")+ def calc() -> int:+ return 2++ @mcp.tool(version="3.0", auth=require_scopes("admin"))+ def calc() -> int:+ return 3++ mcp.disable(version=VersionSpec(eq="2.0"))++ tool = await mcp.get_tool("calc")+ assert tool is not None+ assert tool.version == "1.0"++ async def test_get_unknown_tool_returns_none(self):+ mcp = _server_with_protected_v2()++ assert await mcp.get_tool("missing") is None+++class TestResourceAuthVersionFallback:+ async def test_get_resource_returns_v1_when_v2_unauthorized(self):+ mcp = FastMCP()++ @mcp.resource("data://info", version="1.0")+ def info() -> str:+ return "v1"++ @mcp.resource("data://info", version="2.0", auth=require_scopes("admin"))+ def info() -> str:+ return "v2"++ resource = await mcp.get_resource("data://info")+ assert resource is not None+ assert resource.version == "1.0"++ async def test_get_resource_explicit_unauthorized_version_returns_none(self):+ mcp = FastMCP()++ @mcp.resource("data://info", version="1.0")+ def info() -> str:+ return "v1"++ @mcp.resource("data://info", version="2.0", auth=require_scopes("admin"))+ def info() -> str:+ return "v2"++ resource = await mcp.get_resource("data://info", VersionSpec(eq="2.0"))+ assert resource is None+++class TestResourceTemplateAuthVersionFallback:+ async def test_get_resource_template_returns_v1_when_v2_unauthorized(self):+ mcp = FastMCP()++ @mcp.resource("data://items/{id}", version="1.0")+ def item(id: str) -> str:+ return f"v1-{id}"++ @mcp.resource("data://items/{id}", version="2.0", auth=require_scopes("admin"))+ def item(id: str) -> str:+ return f"v2-{id}"++ template = await mcp.get_resource_template("data://items/{id}")+ assert template is not None+ assert template.version == "1.0"+++class TestPromptAuthVersionFallback:+ async def test_get_prompt_returns_v1_when_v2_unauthorized(self):+ mcp = FastMCP()++ @mcp.prompt(version="1.0")+ def greet() -> str:+ return "hello v1"++ @mcp.prompt(version="2.0", auth=require_scopes("admin"))+ def greet() -> str:+ return "hello v2"++ prompt = await mcp.get_prompt("greet")+ assert prompt is not None+ assert prompt.version == "1.0"++ async def test_get_prompt_explicit_unauthorized_version_returns_none(self):+ mcp = FastMCP()++ @mcp.prompt(version="1.0")+ def greet() -> str:+ return "hello v1"++ @mcp.prompt(version="2.0", auth=require_scopes("admin"))+ def greet() -> str:+ return "hello v2"++ prompt = await mcp.get_prompt("greet", VersionSpec(eq="2.0"))+ assert prompt is Nonediff --git a/tests/test_fastmcp_app.py b/tests/test_fastmcp_app.pyindex ce762810d..200282625 100644--- a/tests/test_fastmcp_app.py+++ b/tests/test_fastmcp_app.py@@ -547,6 +547,28 @@ class TestCallToolAppRouting:finally:_current_transport.reset(token)+ async def test_display_name_shaped_like_hashed_address_wins(self):+ """A display tool whose name parses as a hashed address resolves by+ display name before hashed dispatch is tried."""+ from fastmcp.server.providers.addressing import hashed_backend_name++ app = FastMCPApp("contacts")++ @app.tool()+ def save() -> str:+ return "backend"++ address = hashed_backend_name("contacts", "save")+ server = FastMCP("Platform")+ server.add_provider(app)++ @server.tool(name=address)+ def display() -> str:+ return "display"++ result = await server.call_tool(address, {})+ assert result.content[0].text == "display" # type: ignore[union-attr] # ty:ignore[unresolved-attribute]+async def test_two_apps_same_tool_name_routed_by_address(self):"""Two FastMCPApps each with a `save` tool live at distinctaddresses, so they hash differently and the dispatcher routes