Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/mcp_server_qdrant/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,17 @@ def format_entry(self, entry: Entry) -> str:
f"<metadata>{escape(entry_metadata)}</metadata></entry>"
)

def format_skipped_note(self, skipped: int) -> str:
"""
Tell the model that some matches were left out, so it does not treat
the results as complete.
"""
return (
f"Note: {skipped} matching point(s) were left out because their payloads "
"have no 'document' field. This tool only returns points that store "
"their text in that field."
)

def setup_tools(self):
"""
Register the tools in the server.
Expand Down Expand Up @@ -207,13 +218,15 @@ async def find(
raise ToolError(
f"Error calling tool 'qdrant-find': {_error_types(error)}"
) from error
if not entries:
if not entries and entries.skipped == 0:
return None
content = [
f"Results for the query '{query}'",
]
for entry in entries:
content.append(self.format_entry(entry))
if entries.skipped > 0:
content.append(self.format_skipped_note(entries.skipped))
return content

find_foo = find
Expand Down
111 changes: 99 additions & 12 deletions src/mcp_server_qdrant/qdrant.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
import uuid
from collections.abc import Iterable
from typing import Any

from pydantic import BaseModel
Expand All @@ -24,6 +25,24 @@ class Entry(BaseModel):
metadata: Metadata | None = None


class SearchResults(list[Entry]):
"""
The entries found by a search. It is a plain list of entries, plus the
number of matching points that were skipped because their payload has no
"document" field.
"""

def __init__(self, entries: Iterable[Entry] = (), skipped: int = 0):
super().__init__(entries)
self.skipped = skipped


class IncompatibleCollectionError(ValueError):
"""
The collection's vectors do not match the configured embedding model.
"""


class QdrantConnector:
"""
Encapsulates the connection to a Qdrant server and all the methods to interact with it.
Expand Down Expand Up @@ -98,21 +117,25 @@ async def search(
collection_name: str | None = None,
limit: int = 10,
query_filter: models.Filter | None = None,
) -> list[Entry]:
) -> SearchResults:
"""
Find points in the Qdrant collection. If there are no entries found, an empty list is returned.
Points without a "document" field in their payload are skipped and counted in
``SearchResults.skipped``.
:param query: The query to use for the search.
:param collection_name: The name of the collection to search in, optional. If not provided,
the default collection is used.
:param limit: The maximum number of entries to return.
:param query_filter: The filter to apply to the query, if any.

:return: A list of entries found.
:return: The entries found.
"""
collection_name = collection_name or self._default_collection_name
collection_exists = await self._client.collection_exists(collection_name)
if not collection_exists:
return []
assert collection_name is not None
collection_info = await self._get_collection(collection_name)
if collection_info is None:
return SearchResults()
self._check_vectors(collection_name, collection_info)

# Embed the query
# ToDo: instead of embedding text explicitly, use `models.Document`,
Expand All @@ -130,13 +153,75 @@ async def search(
query_filter=query_filter,
)

return [
Entry(
content=result.payload["document"],
metadata=result.payload.get("metadata"),
results = SearchResults()
for point in search_results.points:
payload = point.payload or {}
if "document" not in payload:
results.skipped += 1
continue
results.append(
Entry(content=payload["document"], metadata=payload.get("metadata"))
)
if results.skipped:
logger.warning(
"Skipped %d point(s) without a 'document' payload field in collection %r",
results.skipped,
collection_name,
)
return results

async def _get_collection(
self, collection_name: str
) -> models.CollectionInfo | None:
"""
Get the collection's info, or None if it does not exist. This replaces a
separate existence check, so validating the collection costs no extra request.
"""
try:
return await self._client.get_collection(collection_name)
except UnexpectedResponse as e:
# Remote mode: the server returns 404 for a missing collection.
if e.status_code == 404:
return None
raise
except ValueError as e:
# Local mode raises ValueError("Collection ... not found").
if "not found" in str(e).lower():
return None
raise

def _check_vectors(
self, collection_name: str, collection_info: models.CollectionInfo
) -> None:
"""
Raise a clear error if the collection has no vector with the name and size
that the embedding model produces. Without this check, Qdrant rejects the
request with a cryptic "Not existing vector name" or dimension error.
"""
expected_name = self._embedding_provider.get_vector_name()
expected_size = self._embedding_provider.get_vector_size()
vectors = collection_info.config.params.vectors

if isinstance(vectors, dict):
params = vectors.get(expected_name)
if params is not None and params.size == expected_size:
return
names = ", ".join(
f"'{name}' (size {p.size})" for name, p in vectors.items()
)
for result in search_results.points
]
found = f"named vectors {names}" if names else "no dense vectors"
elif vectors is not None:
found = f"a single unnamed vector (size {vectors.size})"
else:
found = "no dense vectors"

raise IncompatibleCollectionError(
f"Collection '{collection_name}' does not match the embedding model this "
f"server uses. The server needs a vector named '{expected_name}' with size "
f"{expected_size}, but the collection has {found}. The vector name and size "
"come from EMBEDDING_MODEL: use the model the collection was created with, "
"or use a different collection."
)

async def _ensure_collection_exists(self, collection_name: str):
"""
Expand All @@ -150,7 +235,9 @@ async def _ensure_collection_exists(self, collection_name: str):

:param collection_name: The name of the collection to ensure exists.
"""
if await self._client.collection_exists(collection_name):
collection_info = await self._get_collection(collection_name)
if collection_info is not None:
self._check_vectors(collection_name, collection_info)
return

vector_size = self._embedding_provider.get_vector_size()
Expand Down
85 changes: 85 additions & 0 deletions tests/test_mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import pytest
from fastmcp import Client
from fastmcp.exceptions import ToolError
from qdrant_client import models
from qdrant_client.http.exceptions import ResponseHandlingException

from mcp_server_qdrant.mcp_server import QdrantMCPServer
Expand Down Expand Up @@ -205,6 +206,90 @@ async def test_arbitrary_filter(embedding_provider_settings):
)


VECTOR_NAME = "fast-all-minilm-l6-v2"
COSINE = models.Distance.COSINE


@pytest.mark.parametrize(
"vectors_config, found",
[
(models.VectorParams(size=384, distance=COSINE), "a single unnamed vector"),
(
{"other": models.VectorParams(size=384, distance=COSINE)},
"named vectors 'other' (size 384)",
),
(
{VECTOR_NAME: models.VectorParams(size=768, distance=COSINE)},
f"named vectors '{VECTOR_NAME}' (size 768)",
),
],
ids=["unnamed", "other-name", "wrong-size"],
)
async def test_incompatible_collection_gives_clear_error(
embedding_provider_settings, vectors_config, found
):
server = make_server(embedding_provider_settings, COLLECTION_NAME="foreign")
await server.qdrant_connector._client.create_collection(
"foreign", vectors_config=vectors_config
)
async with Client(server) as client:
for tool, args in [
("qdrant-find", {"query": "asyncio"}),
("qdrant-store", {"information": "asyncio tips"}),
]:
with pytest.raises(ToolError) as error:
await client.call_tool(tool, args)
message = str(error.value)
assert "does not match the embedding model" in message
assert f"a vector named '{VECTOR_NAME}' with size 384" in message
assert found in message


async def test_points_without_document_are_skipped_with_note(
embedding_provider_settings,
):
server = make_server(embedding_provider_settings, COLLECTION_NAME="mixed")
async with Client(server) as client:
await client.call_tool("qdrant-store", {"information": "asyncio tips"})

# A point written by another tool: compatible vector, but no "document".
vector = await server.embedding_provider.embed_documents(["asyncio tricks"])
await server.qdrant_connector._client.upsert(
"mixed",
points=[
models.PointStruct(
id=1, vector={VECTOR_NAME: vector[0]}, payload={"text": "tricks"}
)
],
)

text = text_of(await client.call_tool("qdrant-find", {"query": "asyncio"}))
assert "asyncio tips" in text
assert "tricks" not in text
assert "Note: 1 matching point(s) were left out" in text


async def test_only_points_without_document_returns_note(embedding_provider_settings):
server = make_server(embedding_provider_settings, COLLECTION_NAME="foreign_only")
connector = server.qdrant_connector
await connector._client.create_collection(
"foreign_only",
vectors_config={VECTOR_NAME: models.VectorParams(size=384, distance=COSINE)},
)
vectors = await server.embedding_provider.embed_documents(["one", "two"])
await connector._client.upsert(
"foreign_only",
points=[
models.PointStruct(id=i, vector={VECTOR_NAME: v}, payload={"text": "x"})
for i, v in enumerate(vectors)
],
)
async with Client(server) as client:
text = text_of(await client.call_tool("qdrant-find", {"query": "one"}))
assert "<entry>" not in text
assert "Note: 2 matching point(s) were left out" in text


async def test_read_only_hides_store(embedding_provider_settings):
server = make_server(
embedding_provider_settings, COLLECTION_NAME="ro", QDRANT_READ_ONLY=True
Expand Down
Loading