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
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -515,12 +515,13 @@ collections](https://qdrant.tech/documentation/security/#read-only-api-key). On
[database API keys](https://qdrant.tech/documentation/cloud/authentication/).

- With `QDRANT_READ_ONLY=true`, use a read-only key, so Qdrant itself refuses writes.
- The server creates the payload indexes for `FILTERABLE_FIELDS` itself when its key can write to the collection. With
a read-only key, create an index on `metadata.<field name>` for each field with a key that can write.
- To limit the server to one collection, set `COLLECTION_NAME` and use a key scoped to that collection. A scoped key
can't create collections, so the collection has to exist before the first `qdrant-store`. Either:
- create it yourself, for example in the Qdrant Cloud console, with a vector named `fast-all-minilm-l6-v2`, size
`384`, and cosine distance. These match the default `EMBEDDING_MODEL`; if they don't match, the server's error
says which name and size it needs. If you use `FILTERABLE_FIELDS`, also create a payload index on
`metadata.<field name>` for each field.
says which name and size it needs.
- or let the server create it: run it once with a full-access key and store one entry, then switch to the scoped key.

### Stored text is passed to the model
Expand Down
42 changes: 42 additions & 0 deletions src/mcp_server_qdrant/qdrant.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ def __init__(
location=qdrant_url, api_key=qdrant_api_key, path=qdrant_local_path
)
self._field_indexes = field_indexes
# Local mode ignores payload indexes: it never reports them and warns
# every time one is created.
self._is_local = qdrant_local_path is not None or qdrant_url == ":memory:"

async def get_collection_names(self) -> list[str]:
"""
Expand Down Expand Up @@ -136,6 +139,8 @@ async def search(
if collection_info is None:
return SearchResults()
self._check_vectors(collection_name, collection_info)
# In read-only mode, search is the only call that reaches the collection.
await self._create_missing_indexes(collection_name, collection_info)

# Embed the query
# ToDo: instead of embedding text explicitly, use `models.Document`,
Expand Down Expand Up @@ -223,6 +228,42 @@ def _check_vectors(
"or use a different collection."
)

async def _create_missing_indexes(
self, collection_name: str, collection_info: models.CollectionInfo
) -> None:
"""
Create the payload indexes for the filterable fields that the collection
doesn't have yet. The collection may predate a filterable field, or may have
been created outside this server. Without the index, filtering is slow, and
collections in strict mode, the default on Qdrant Cloud, reject the filter.

If the API key isn't allowed to create indexes, log a warning and carry on.
"""
if not self._field_indexes or self._is_local:
return
existing = collection_info.payload_schema or {}
for field_name, field_type in self._field_indexes.items():
if field_name in existing:
continue
try:
await self._client.create_payload_index(
collection_name=collection_name,
field_name=field_name,
field_schema=field_type,
)
except UnexpectedResponse as e:
if e.status_code != 403:
raise
logger.warning(
"Collection %r has no payload index on %r, and the API key is not "
"allowed to create one. Filters on this field may fail: create the "
"index with a key that has write access to the collection.",
collection_name,
field_name,
)
# Every other index would be refused the same way.
return

async def _ensure_collection_exists(self, collection_name: str):
"""
Ensure that the collection exists, creating it if necessary.
Expand All @@ -238,6 +279,7 @@ async def _ensure_collection_exists(self, collection_name: str):
collection_info = await self._get_collection(collection_name)
if collection_info is not None:
self._check_vectors(collection_name, collection_info)
await self._create_missing_indexes(collection_name, collection_info)
return

vector_size = self._embedding_provider.get_vector_size()
Expand Down
165 changes: 165 additions & 0 deletions tests/test_payload_indexes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
"""
Payload indexes for filterable fields must exist even when the collection already
did before the server first used it. Local mode ignores payload indexes, so these
tests use it with ``_is_local`` turned off and record ``create_payload_index``
calls instead of checking the collection.
"""

import logging
import uuid
from unittest.mock import AsyncMock, patch

import httpx
import pytest
from qdrant_client import models
from qdrant_client.http.exceptions import UnexpectedResponse

from mcp_server_qdrant.embeddings.fastembed import FastEmbedProvider
from mcp_server_qdrant.qdrant import Entry, QdrantConnector

INDEXES = {
"metadata.lang": models.PayloadSchemaType.KEYWORD,
"metadata.year": models.PayloadSchemaType.INTEGER,
}


@pytest.fixture(scope="module")
def embedding_provider():
return FastEmbedProvider(model_name="sentence-transformers/all-MiniLM-L6-v2")


async def make_connector(embedding_provider, *, remote: bool = True):
"""A connector whose collection already exists, created without any index."""
collection_name = f"indexes_{uuid.uuid4().hex}"
connector = QdrantConnector(
qdrant_url=":memory:",
qdrant_api_key=None,
collection_name=collection_name,
embedding_provider=embedding_provider,
field_indexes=INDEXES,
)
connector._is_local = not remote
await connector._client.create_collection(
collection_name,
vectors_config={
embedding_provider.get_vector_name(): models.VectorParams(
size=embedding_provider.get_vector_size(),
distance=models.Distance.COSINE,
)
},
)
return connector


def forbidden() -> UnexpectedResponse:
return UnexpectedResponse(
status_code=403,
reason_phrase="Forbidden",
content=b'{"status":{"error":"Forbidden"}}',
headers=httpx.Headers(),
)


async def test_store_creates_missing_indexes(embedding_provider):
connector = await make_connector(embedding_provider)
with patch.object(
connector._client, "create_payload_index", new=AsyncMock()
) as create_index:
await connector.store(Entry(content="hello"))

created = {call.kwargs["field_name"] for call in create_index.await_args_list}
assert created == set(INDEXES)


async def test_search_creates_missing_indexes(embedding_provider):
"""In read-only mode, search is the only call that reaches the collection."""
connector = await make_connector(embedding_provider)
with patch.object(
connector._client, "create_payload_index", new=AsyncMock()
) as create_index:
await connector.search("hello")

created = {call.kwargs["field_name"] for call in create_index.await_args_list}
assert created == set(INDEXES)


async def test_existing_indexes_are_not_created_again(embedding_provider):
connector = await make_connector(embedding_provider)
info = await connector._client.get_collection(connector._default_collection_name)
info.payload_schema = {
"metadata.lang": models.PayloadIndexInfo(
data_type=models.PayloadSchemaType.KEYWORD, points=0
)
}
with (
patch.object(connector, "_get_collection", new=AsyncMock(return_value=info)),
patch.object(
connector._client, "create_payload_index", new=AsyncMock()
) as create_index,
):
await connector.search("hello")

created = [call.kwargs["field_name"] for call in create_index.await_args_list]
assert created == ["metadata.year"]


async def test_local_mode_does_not_create_indexes(embedding_provider):
"""Local mode never reports indexes, so creating them would warn on every call."""
connector = await make_connector(embedding_provider, remote=False)
with patch.object(
connector._client, "create_payload_index", new=AsyncMock()
) as create_index:
await connector.store(Entry(content="hello"))
await connector.search("hello")

create_index.assert_not_awaited()


async def test_key_without_write_access_logs_a_warning(embedding_provider, caplog):
connector = await make_connector(embedding_provider)
await connector._client.upsert(
connector._default_collection_name,
points=[
models.PointStruct(
id=uuid.uuid4().hex,
vector={
embedding_provider.get_vector_name(): (
await embedding_provider.embed_documents(["hello"])
)[0]
},
payload={"document": "hello"},
)
],
)
with (
patch.object(
connector._client,
"create_payload_index",
new=AsyncMock(side_effect=forbidden()),
) as create_index,
caplog.at_level(logging.WARNING),
):
results = await connector.search("hello")

assert [entry.content for entry in results] == ["hello"]
# The other index would be refused the same way, so it isn't attempted.
assert create_index.await_count == 1
assert "not allowed to create one" in caplog.text
assert "metadata.lang" in caplog.text


async def test_other_index_errors_are_raised(embedding_provider):
connector = await make_connector(embedding_provider)
error = UnexpectedResponse(
status_code=500,
reason_phrase="Internal Server Error",
content=b"{}",
headers=httpx.Headers(),
)
with (
patch.object(
connector._client, "create_payload_index", new=AsyncMock(side_effect=error)
),
pytest.raises(UnexpectedResponse),
):
await connector.search("hello")
Loading