Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

fix(auth): authorize hashed app-tool names and synthesized Prefab resources (#5841)

ε“ˆεŸΊη±³ad5092ac6073
diff --git a/fastmcp_slim/fastmcp/server/middleware/authorization.py b/fastmcp_slim/fastmcp/server/middleware/authorization.py
index 2fd7e9219..83e36a456 100644
--- a/fastmcp_slim/fastmcp/server/middleware/authorization.py
+++ b/fastmcp_slim/fastmcp/server/middleware/authorization.py
@@ -39,6 +39,7 @@ from fastmcp.server.middleware.middleware import (
Middleware,
MiddlewareContext,
)
+from fastmcp.server.providers.addressing import parse_hashed_backend_name
from fastmcp.tools.base import Tool, ToolResult
from fastmcp.utilities.authorization import (
AuthCheck,
@@ -227,6 +228,18 @@ class AuthMiddleware(Middleware):
# disclosing existence of tools the caller is not authorized to see.
version = _requested_version(context.message.meta)
tool = await fastmcp.fastmcp.get_tool(tool_name, version=version)
+ if tool is None:
+ # Core routing retries a failed display-name lookup as a hashed
+ # backend name: backend tools callable by apps are addressed as
+ # `<hash>_<local_name>` and resolved through `get_tool_by_hash`.
+ # Mirror that path so such a tool is authorized as the same
+ # component however it was addressed. `get_tool_by_hash` applies
+ # the transforms, visibility, enabled state, and component auth
+ # a name lookup applies, so a refused tool still resolves to None.
+ hashed = parse_hashed_backend_name(tool_name)
+ if hashed is not None:
+ digest, local_name = hashed
+ tool = await fastmcp.fastmcp.get_tool_by_hash(digest, local_name)
if tool is None:
raise AuthorizationError(
f"Authorization failed for tool '{tool_name}': "
@@ -313,6 +326,20 @@ class AuthMiddleware(Middleware):
str(uri),
version=version,
)
+ if component is None:
+ # Prefab renderer resources (`ui://prefab/renderer/<sha256>/
+ # renderer.html`, plus legacy per-tool hashed URIs) are synthesized
+ # on demand by core `read_resource` rather than stored on a
+ # provider, so neither lookup above can see them. Mirror that path
+ # so the global checks below run against the component core would
+ # actually read.
+ from fastmcp.server.providers.prefab_synthesis import (
+ synthesize_prefab_resource_by_uri,
+ )
+
+ component = await synthesize_prefab_resource_by_uri(
+ fastmcp.fastmcp, str(uri)
+ )
if component is None:
raise AuthorizationError(
f"Authorization failed for resource '{uri}': "
diff --git a/tests/server/auth/test_authorization.py b/tests/server/auth/test_authorization.py
index 132af4d95..16ad2cfb9 100644
--- a/tests/server/auth/test_authorization.py
+++ b/tests/server/auth/test_authorization.py
@@ -8,7 +8,8 @@ from mcp import MCPError
from mcp.server.auth.middleware.auth_context import auth_context_var
from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
-from fastmcp import FastMCP
+from fastmcp import FastMCP, FastMCPApp
+from fastmcp.apps.config import PrefabAppConfig
from fastmcp.client import Client
from fastmcp.exceptions import AuthorizationError, InsufficientScopeError, ToolError
from fastmcp.prompts import Prompt
@@ -23,13 +24,18 @@ from fastmcp.server.auth import (
run_auth_checks,
)
from fastmcp.server.middleware import AuthMiddleware
+from fastmcp.server.providers.addressing import (
+ hashed_backend_name,
+)
from fastmcp.server.transforms import (
GetPromptNext,
GetResourceNext,
GetResourceTemplateNext,
+ GetToolNext,
ToolTransform,
Transform,
)
+from fastmcp.tools.base import Tool
from fastmcp.tools.tool_transform import ToolTransformConfig, TransformedTool
from fastmcp.utilities.authorization import scope_requirements
from fastmcp.utilities.versions import VersionSpec
@@ -1641,3 +1647,191 @@ class TestAuthSeesTransformedComponent:
await client.get_prompt("secret")
finally:
auth_context_var.reset(tok)
+
+
+# =============================================================================
+# Tests for AuthMiddleware on identity-addressed backend tools
+# =============================================================================
+
+
+class _RefuseLookup(Transform):
+ """Lists every tool but refuses to resolve the named ones."""
+
+ def __init__(self, *names: str) -> None:
+ self.names = set(names)
+
+ async def get_tool(
+ self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None
+ ) -> Tool | None:
+ if name in self.names:
+ return None
+ return await call_next(name, version=version)
+
+
+def make_app_server(
+ calls: list[str],
+ *,
+ backend_auth=None,
+) -> FastMCP:
+ """A server whose ``contacts`` app backend tool ``save`` records its calls."""
+ app = FastMCPApp("contacts")
+
+ @app.tool(auth=backend_auth)
+ def save(name: str) -> str:
+ calls.append(name)
+ return f"saved {name}"
+
+ mcp = FastMCP(middleware=[AuthMiddleware(auth=require_scopes("test"))])
+ mcp.add_provider(app)
+ return mcp
+
+
+SAVE_HASHED = hashed_backend_name("contacts", "save")
+
+
+class TestAuthMiddlewareHashedBackendNames:
+ """A backend tool addressed by ``<hash>_<local_name>`` is authorized as the
+ same component as the listed name, so the global and component checks apply
+ identically to both addresses."""
+
+ async def test_hashed_name_call_with_sufficient_scope_executes_tool(self):
+ calls: list[str] = []
+ mcp = make_app_server(calls)
+
+ tok = set_token(make_token(scopes=["test"]))
+ try:
+ result = await mcp.call_tool(SAVE_HASHED, {"name": "alice"})
+ finally:
+ auth_context_var.reset(tok)
+
+ assert result.content[0].text == "saved alice" # type: ignore[union-attr] # ty:ignore[unresolved-attribute]
+ assert calls == ["alice"]
+
+ async def test_hashed_name_call_with_insufficient_scope_is_denied(self):
+ calls: list[str] = []
+ mcp = make_app_server(calls)
+
+ tok = set_token(make_token(scopes=["read"]))
+ try:
+ with pytest.raises(InsufficientScopeError) as exc_info:
+ await mcp.call_tool(SAVE_HASHED, {"name": "alice"})
+ finally:
+ auth_context_var.reset(tok)
+
+ assert exc_info.value.required_scopes == ["test"]
+ assert calls == []
+
+ async def test_hashed_name_call_is_denied_by_backend_component_auth(self):
+ # Component-level auth on the resolved tool still applies: the caller
+ # satisfies the global scope but not the tool's own requirement.
+ calls: list[str] = []
+ mcp = make_app_server(calls, backend_auth=require_scopes("admin"))
+
+ tok = set_token(make_token(scopes=["test"]))
+ try:
+ with pytest.raises(AuthorizationError) as exc_info:
+ await mcp.call_tool(SAVE_HASHED, {"name": "alice"})
+ finally:
+ auth_context_var.reset(tok)
+
+ assert "not found or not authorized" in str(exc_info.value)
+ assert calls == []
+
+ async def test_display_name_call_is_unchanged(self):
+ calls: list[str] = []
+ mcp = make_app_server(calls)
+
+ tok = set_token(make_token(scopes=["test"]))
+ try:
+ result = await mcp.call_tool("save", {"name": "alice"})
+ finally:
+ auth_context_var.reset(tok)
+
+ assert result.content[0].text == "saved alice" # type: ignore[union-attr] # ty:ignore[unresolved-attribute]
+ assert calls == ["alice"]
+
+ async def test_transform_refused_tool_stays_denied_under_hashed_name(self):
+ # The transform refuses to resolve the listed name, so the hashed
+ # fallback must not reach the tool either.
+ calls: list[str] = []
+ mcp = make_app_server(calls)
+ mcp.add_transform(_RefuseLookup("save"))
+
+ tok = set_token(make_token(scopes=["test"]))
+ try:
+ with pytest.raises(AuthorizationError) as exc_info:
+ await mcp.call_tool(SAVE_HASHED, {"name": "alice"})
+ finally:
+ auth_context_var.reset(tok)
+
+ assert "not found or not authorized" in str(exc_info.value)
+ assert calls == []
+
+
+# =============================================================================
+# Tests for AuthMiddleware on synthesized Prefab renderer resources
+# =============================================================================
+
+
+class TestAuthMiddlewareSynthesizedPrefabResources:
+ """Per-tool Prefab renderer resources are synthesized on demand rather than
+ stored, so the middleware must resolve them the same way core read does."""
+
+ @staticmethod
+ def make_server() -> FastMCP:
+ mcp = FastMCP(middleware=[AuthMiddleware(auth=require_scopes("ui"))])
+
+ @mcp.tool(app=PrefabAppConfig())
+ def show_widget() -> str:
+ return "widget"
+
+ return mcp
+
+ @staticmethod
+ async def renderer_uri(mcp: FastMCP) -> str:
+ """Return the renderer URI the server lists to an authorized caller."""
+ tok = set_token(make_token(scopes=["ui"]))
+ try:
+ resources = await mcp.list_resources()
+ finally:
+ auth_context_var.reset(tok)
+ [uri] = [
+ str(resource.uri)
+ for resource in resources
+ if str(resource.uri).startswith("ui://prefab/")
+ ]
+ return uri
+
+ async def test_read_renderer_with_sufficient_scope(self):
+ pytest.importorskip("prefab_ui")
+ mcp = self.make_server()
+ uri = await self.renderer_uri(mcp)
+
+ tok = set_token(make_token(scopes=["ui"]))
+ try:
+ resources = await mcp.list_resources()
+ assert any(str(resource.uri) == uri for resource in resources)
+
+ result = await mcp.read_resource(uri)
+ finally:
+ auth_context_var.reset(tok)
+
+ assert result.contents[0].mime_type == "text/html;profile=mcp-app"
+ assert result.contents[0].content
+
+ async def test_read_renderer_with_insufficient_scope_is_denied(self):
+ pytest.importorskip("prefab_ui")
+ mcp = self.make_server()
+ uri = await self.renderer_uri(mcp)
+
+ tok = set_token(make_token(scopes=["read"]))
+ try:
+ resources = await mcp.list_resources()
+ assert not any(str(resource.uri) == uri for resource in resources)
+
+ with pytest.raises(InsufficientScopeError) as exc_info:
+ await mcp.read_resource(uri)
+ finally:
+ auth_context_var.reset(tok)
+
+ assert exc_info.value.required_scopes == ["ui"]