π The fast, Pythonic way to build MCP servers and clients.
completions: check reference visibility through typed list hooks only (#5244)
nate nowack94c5a21229a6
diff --git a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.pyindex 422bfb5cd..41a82177f 100644--- a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py+++ b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py@@ -3,7 +3,7 @@from __future__ import annotationsimport inspect-from collections.abc import Sequence+from collections.abc import Awaitable, Callable, Sequencefrom typing import TYPE_CHECKING, Any, TypeVar, castimport mcp_types@@ -47,6 +47,7 @@ if TYPE_CHECKING:logger = get_logger(__name__)PaginateT = TypeVar("PaginateT")+T = TypeVar("T")def _apply_pagination(@@ -456,14 +457,57 @@ class MCPOperationsMixin:ref: mcp_types.PromptReference | mcp_types.ResourceTemplateReference,) -> bool:"""Whether the caller can list the prompt or template a completion- refers to, after visibility, component auth, and middleware. A hidden- reference completes like an unknown one, so suggestions cannot- disclose what the listing withholds."""- if isinstance(ref, mcp_types.PromptReference):- return any(p.name == ref.name for p in await self.list_prompts())- if any(t.uri_template == ref.uri for t in await self.list_resource_templates()):- return True- return any(str(r.uri) == ref.uri for r in await self.list_resources())+ refers to, after visibility, component auth, and the typed ``on_list_*``+ middleware hooks. A hidden reference completes like an unknown one, so+ suggestions cannot disclose what the listing withholds.++ Only the typed hooks run: generic ``on_request``/``on_message``+ middleware (rate limits, logging, metrics) must see one+ ``completion/complete``, not the listings behind it. A listing that+ fails hides the reference.+ """+ try:+ if isinstance(ref, mcp_types.PromptReference):+ prompts = await self._list_for_completion(+ "prompts/list", self.list_prompts+ )+ return any(p.name == ref.name for p in prompts)+ templates = await self._list_for_completion(+ "resources/templates/list", self.list_resource_templates+ )+ if any(t.uri_template == ref.uri for t in templates):+ return True+ resources = await self._list_for_completion(+ "resources/list", self.list_resources+ )+ return any(str(r.uri) == ref.uri for r in resources)+ except Exception:+ logger.warning(+ "Listing failed while checking completion reference %s",+ ref,+ exc_info=True,+ )+ return False++ async def _list_for_completion(+ self: FastMCP, method: str, list_fn: Callable[..., Awaitable[Sequence[T]]]+ ) -> Sequence[T]:+ from fastmcp.server.context import Context+ from fastmcp.server.middleware import MiddlewareContext++ async with Context(fastmcp=self) as ctx:+ mw_context = MiddlewareContext(+ message={},+ source="client",+ type="request",+ method=method,+ fastmcp_context=ctx,+ )+ return await self._run_middleware(+ mw_context,+ lambda context: list_fn(run_middleware=False),+ phase="typed",+ )def _register_completion_handler(self: FastMCP) -> None:"""Register the low-level ``completion/complete`` handler.diff --git a/tests/server/test_completions.py b/tests/server/test_completions.pyindex 6025fc3df..54e88feba 100644--- a/tests/server/test_completions.py+++ b/tests/server/test_completions.py@@ -381,3 +381,40 @@ async def test_completion_answers_a_listed_static_resource_uri():)assert listed.values == ["value"]assert unknown.values == []++[email protected]("mode", MODES)[email protected]("ref", HIDDEN_REFS, ids=["prompt", "template"])+async def test_visibility_check_does_not_run_generic_middleware(ref, mode):+ from fastmcp.server.middleware import Middleware++ seen: list[str] = []++ class Recorder(Middleware):+ async def on_request(self, context, call_next):+ seen.append(context.method)+ return await call_next(context)++ mcp = _suggesting_server(middleware=[Recorder()])+ async with Client(mcp, mode=mode) as client:+ seen.clear()+ result = await client.complete(ref, {"name": "path", "value": ""})+ assert result.values == ["private/salary.md"]+ assert seen == ["completion/complete"]++[email protected]("ref", HIDDEN_REFS, ids=["prompt", "template"])+async def test_raising_list_hook_fails_completion_closed(ref):+ from fastmcp.server.middleware import Middleware++ class BrokenListing(Middleware):+ async def on_list_prompts(self, context, call_next):+ raise RuntimeError("listing is down")++ async def on_list_resource_templates(self, context, call_next):+ raise RuntimeError("listing is down")++ mcp = _suggesting_server(middleware=[BrokenListing()])+ async with Client(mcp) as client:+ result = await client.complete(ref, {"name": "path", "value": ""})+ assert result.values == []