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
26 changes: 25 additions & 1 deletion src/mcp_server_qdrant/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
from fastmcp.utilities.logging import get_logger
from pydantic import Field
from pydantic import BeforeValidator, Field
from pydantic_core import from_json
from qdrant_client import models

from mcp_server_qdrant.common.filters import make_indexes
Expand Down Expand Up @@ -54,6 +55,28 @@ def _error_types(error: BaseException) -> str:
return " caused by ".join(names)


def _metadata_from_json_string(value: Any) -> Any:
"""Accept `metadata` sent as a JSON string of an object.

Some MCP clients, such as Claude Code and Cursor, sometimes send object
arguments as JSON strings: `'{"lang": "python"}'` instead of
`{"lang": "python"}`. Turn such a string into the object it encodes. Leave
anything else unchanged, so validation still rejects plain text, lists and
other values that aren't objects.
"""
if not isinstance(value, str):
return value
try:
# Pydantic's parser stops at 200 levels of nesting and, with
# allow_inf_nan=False, rejects NaN and Infinity like standard JSON.
decoded = from_json(value, allow_inf_nan=False)
except ValueError:
# Not standard JSON, or nested too deeply: leave the string for
# validation to reject.
return value
return decoded if isinstance(decoded, dict) else value


# FastMCP is an alternative interface for declaring the capabilities
# of the server. Its API is based on FastAPI.
class QdrantMCPServer(FastMCP):
Expand Down Expand Up @@ -152,6 +175,7 @@ async def store(
# handle the optional parameter correctly.
metadata: Annotated[
Metadata | None,
BeforeValidator(_metadata_from_json_string),
Field(
description="Extra metadata stored along with memorised information. Any json is accepted."
),
Expand Down
113 changes: 113 additions & 0 deletions tests/test_metadata_argument.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""
Some MCP clients, such as Claude Code and Cursor, sometimes send the `metadata`
argument of qdrant-store as a JSON string instead of an object. The server
accepts a string that encodes an object and still rejects anything else.
"""

import json
import uuid

import pytest
from fastmcp import Client
from fastmcp.exceptions import ToolError

from mcp_server_qdrant.mcp_server import QdrantMCPServer
from mcp_server_qdrant.settings import (
EmbeddingProviderSettings,
QdrantSettings,
ToolSettings,
)

METADATA = {"lang": "python", "tags": ["a", "b"], "nested": {"year": 2026}}


def nested(levels: int) -> str:
"""A JSON object string nested this many levels deep: {"a":{"a":...1...}}."""
return '{"a":' * levels + "1" + "}" * levels


@pytest.fixture
def server():
return QdrantMCPServer(
tool_settings=ToolSettings(),
qdrant_settings=QdrantSettings(
QDRANT_URL=":memory:", COLLECTION_NAME=f"metadata_{uuid.uuid4().hex}"
),
embedding_provider_settings=EmbeddingProviderSettings(),
)


async def stored_metadata(client: Client) -> dict | None:
found = await client.call_tool("qdrant-find", {"query": "hello"})
# The header line, then one formatted entry.
_, entry = json.loads(found.content[0].text)
raw = entry.split("<metadata>")[1].split("</metadata>")[0]
return json.loads(raw) if raw else None


async def test_schema_still_asks_for_an_object(server):
"""Clients must keep sending objects: the string form is only tolerated."""
async with Client(server) as client:
tools = await client.list_tools()
store = next(tool for tool in tools if tool.name == "qdrant-store")

schema = store.input_schema["properties"]["metadata"]
assert schema["anyOf"] == [
{"additionalProperties": True, "type": "object"},
{"type": "null"},
]


@pytest.mark.parametrize(
"metadata", [METADATA, json.dumps(METADATA)], ids=["object", "json-string"]
)
async def test_object_and_json_string_store_the_same_metadata(server, metadata):
async with Client(server) as client:
await client.call_tool(
"qdrant-store", {"information": "hello", "metadata": metadata}
)
assert await stored_metadata(client) == METADATA


async def test_json_string_nested_200_levels_is_accepted(server):
"""200 levels is the parser's limit, far beyond any real metadata."""
async with Client(server) as client:
await client.call_tool(
"qdrant-store", {"information": "hello", "metadata": nested(200)}
)
assert await stored_metadata(client) == json.loads(nested(200))


async def test_no_metadata_still_works(server):
async with Client(server) as client:
await client.call_tool("qdrant-store", {"information": "hello"})
assert await stored_metadata(client) is None


@pytest.mark.parametrize(
"metadata",
[
"just a note",
"[1, 2]",
'"quoted"',
"42",
"null",
"{not json",
# Python's json accepts these, standard JSON doesn't.
'{"x": NaN}',
'{"x": Infinity}',
'{"x": -Infinity}',
# Nested far beyond the parser's limit of 200 levels.
nested(100_000),
nested(201),
["a"],
42,
],
ids=lambda value: str(value)[:20],
)
async def test_values_that_are_not_objects_are_still_rejected(server, metadata):
async with Client(server) as client:
with pytest.raises(ToolError, match="valid dictionary"):
await client.call_tool(
"qdrant-store", {"information": "hello", "metadata": metadata}
)
Loading