π The fast, Pythonic way to build MCP servers and clients.
completions: revert the list-based visibility check (#5240, #5244) (#5250)
nate nowack94c346f0b7e7
diff --git a/docs/servers/completions.mdx b/docs/servers/completions.mdxindex b7383f678..d59a18488 100644--- a/docs/servers/completions.mdx+++ b/docs/servers/completions.mdx@@ -118,8 +118,6 @@ A handler may return any of three things:- `None` β treated as an empty completion, for references and arguments the handler does not recognize.- A `Completion` object β when you want to include pagination hints alongside the values.-The handler only runs for references the caller can list. A prompt or template hidden by `disable()`, component auth, or middleware such as `AuthMiddleware` gets an empty completion, as an unknown reference would, so suggestions never reveal what the listing withholds.-The MCP protocol caps a single response at 100 values. When more candidates exist, return a `Completion` and set `total` (how many candidates match in all) and `has_more` (whether values were truncated) so the client can indicate that the list is partial.```pythondiff --git a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.pyindex 41a82177f..5e96e37dc 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 Awaitable, Callable, Sequence+from collections.abc import Sequencefrom typing import TYPE_CHECKING, Any, TypeVar, castimport mcp_types@@ -47,7 +47,6 @@ if TYPE_CHECKING:logger = get_logger(__name__)PaginateT = TypeVar("PaginateT")-T = TypeVar("T")def _apply_pagination(@@ -434,7 +433,7 @@ class MCPOperationsMixin:with bind_request_context(ctx):logger.debug(f"[{self.name}] Handler called: complete %s", params.ref)handler = self._completion_handler- if handler is None or not await self._completion_ref_is_listed(params.ref):+ if handler is None:return mcp_types.CompleteResult(completion=mcp_types.Completion(values=[]))@@ -452,63 +451,6 @@ class MCPOperationsMixin:completion = normalize_completion(cast(CompletionValues, result))return mcp_types.CompleteResult(completion=completion)- async def _completion_ref_is_listed(- self: FastMCP,- 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 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 54e88feba..5ca2df003 100644--- a/tests/server/test_completions.py+++ b/tests/server/test_completions.py@@ -286,106 +286,44 @@ def test_completion_argument_and_context_types_importable():assert context.arguments == {"owner": "prefecthq"}-def _suggesting_server(**kwargs: Any) -> FastMCP:- mcp = FastMCP("hidden-completion", **kwargs)-- @mcp.prompt- def poem(theme: str) -> str:- return f"Write a poem about {theme}"-- @mcp.resource("notes://{path}")- def note(path: str) -> str:- return path-- @mcp.completion- def complete(ref, argument, context):- return ["private/salary.md"]-- return mcp---HIDDEN_REFS = [- PromptReference(name="poem"),- ResourceTemplateReference(uri="notes://{path}"),-]--[email protected]("mode", MODES)[email protected]("ref", HIDDEN_REFS, ids=["prompt", "template"])-async def test_completion_is_empty_for_refs_hidden_by_auth_middleware(ref, mode):- from fastmcp.server.middleware import AuthMiddleware-- mcp = _suggesting_server(middleware=[AuthMiddleware(auth=lambda ctx: False)])- async with Client(mcp, mode=mode) as client:- result = await client.complete(ref, {"name": "path", "value": ""})- assert result.values == []--@pytest.mark.parametrize("mode", MODES)[email protected]("ref", HIDDEN_REFS, ids=["prompt", "template"])-async def test_completion_is_empty_for_disabled_refs(ref, mode):- mcp = _suggesting_server()- mcp.disable(names={"poem"})- mcp.disable(keys={"template:notes://{path}@"})- async with Client(mcp, mode=mode) as client:- result = await client.complete(ref, {"name": "path", "value": ""})- assert result.values == []---async def test_completion_answers_mounted_refs_by_their_namespaced_names():- parent = FastMCP("parent")- child = FastMCP("child")-- @child.prompt- def poem(theme: str) -> str:- return f"Write a poem about {theme}"-- @child.resource("notes://{path}")- def note(path: str) -> str:- return path-- parent.mount(child, namespace="kid")-- @parent.completion- def complete(ref, argument, context):- return ["value"]+async def test_completion_does_not_poison_a_response_cache(mode):+ """A completion must not make a caching layer store a listing that a+ generic-hook filter never saw (4.0.7 served hidden prompts this way)."""+ from fastmcp.server.middleware import Middleware+ from fastmcp.server.middleware.caching import ResponseCachingMiddleware- async with Client(parent) as client:- prompts = [p.name for p in await client.list_prompts()]- templates = [t.uriTemplate for t in await client.list_resource_templates()]- for ref in [- PromptReference(name=prompts[0]),- ResourceTemplateReference(uri=templates[0]),- ]:- result = await client.complete(ref, {"name": "x", "value": ""})- assert result.values == ["value"]+ class HideInternal(Middleware):+ async def on_request(self, context, call_next):+ result = await call_next(context)+ if context.method == "prompts/list":+ return [p for p in result if "internal" not in p.name]+ return result+ mcp = FastMCP(middleware=[ResponseCachingMiddleware(), HideInternal()])-async def test_completion_answers_a_listed_static_resource_uri():- mcp = FastMCP("static-completion")+ @mcp.prompt+ def public(x: str) -> str:+ return x- @mcp.resource("config://app")- def config() -> str:- return "{}"+ @mcp.prompt+ def internal_admin(x: str) -> str:+ return x@mcp.completiondef complete(ref, argument, context):- return ["value"]+ return ["v"]- async with Client(mcp) as client:- listed = await client.complete(- ResourceTemplateReference(uri="config://app"), {"name": "x", "value": ""}- )- unknown = await client.complete(- ResourceTemplateReference(uri="config://other"), {"name": "x", "value": ""}- )- assert listed.values == ["value"]- assert unknown.values == []+ async with Client(mcp, mode=mode) as first, Client(mcp, mode=mode) as second:+ await first.complete(PromptReference(name="public"), {"name": "x", "value": ""})+ listed = [p.name for p in await second.list_prompts()]+ assert listed == ["public"]@pytest.mark.parametrize("mode", MODES)[email protected]("ref", HIDDEN_REFS, ids=["prompt", "template"])-async def test_visibility_check_does_not_run_generic_middleware(ref, mode):+async def test_generic_middleware_sees_one_request_per_completion(mode):+ """Rate limits, logging, and metrics must see a completion as one request+ (4.0.6 charged each completion two or three times)."""from fastmcp.server.middleware import Middlewareseen: list[str] = []@@ -395,26 +333,27 @@ async def test_visibility_check_does_not_run_generic_middleware(ref, mode):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"]+ mcp = FastMCP(middleware=[Recorder()])+ @mcp.prompt+ def poem(theme: str) -> str:+ return theme[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")+ @mcp.resource("notes://{path}")+ def note(path: str) -> str:+ return path- async def on_list_resource_templates(self, context, call_next):- raise RuntimeError("listing is down")+ @mcp.completion+ def complete(ref, argument, context):+ return ["v"]- mcp = _suggesting_server(middleware=[BrokenListing()])- async with Client(mcp) as client:- result = await client.complete(ref, {"name": "path", "value": ""})- assert result.values == []+ async with Client(mcp, mode=mode) as client:+ seen.clear()+ await client.complete(+ PromptReference(name="poem"), {"name": "theme", "value": ""}+ )+ await client.complete(+ ResourceTemplateReference(uri="notes://{path}"),+ {"name": "path", "value": ""},+ )+ assert seen == ["completion/complete", "completion/complete"]