Skip to content

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

completions: answer only references the caller can list (#5240)

nate nowack0959c275c1e0
diff --git a/docs/servers/completions.mdx b/docs/servers/completions.mdx
index d59a18488..b7383f678 100644
--- a/docs/servers/completions.mdx
+++ b/docs/servers/completions.mdx
@@ -118,6 +118,8 @@ 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.
```python
diff --git a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
index 5e96e37dc..422bfb5cd 100644
--- a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
+++ b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py
@@ -433,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:
+ if handler is None or not await self._completion_ref_is_listed(params.ref):
return mcp_types.CompleteResult(
completion=mcp_types.Completion(values=[])
)
@@ -451,6 +451,20 @@ 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 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())
+
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.py
index 88c0bbceb..6025fc3df 100644
--- a/tests/server/test_completions.py
+++ b/tests/server/test_completions.py
@@ -284,3 +284,100 @@ def test_completion_argument_and_context_types_importable():
context = CompletionContext(arguments={"owner": "prefecthq"})
assert argument.name == "theme"
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 == []
+
+
[email protected]("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 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"]
+
+
+async def test_completion_answers_a_listed_static_resource_uri():
+ mcp = FastMCP("static-completion")
+
+ @mcp.resource("config://app")
+ def config() -> str:
+ return "{}"
+
+ @mcp.completion
+ def complete(ref, argument, context):
+ return ["value"]
+
+ 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 == []