Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(mcp): refuse a context-only search argument instead of ignoring it (#4886)
alanhuangyoo2b351a9c5f4c
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 966c0c15c..535c04cf6 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -76,6 +76,7 @@ from openviking_cli.exceptions import (UnauthenticatedError,)from openviking_cli.utils import get_logger+from openviking.server.routers.search import context_only_fields_errorlogger = get_logger(__name__)@@ -273,6 +274,14 @@ async def find(return await _format_search_result(result, service=service, ctx=ctx, read_content=read_content)+# This tool exposes two of the router's context-only fields as a pair each, so a caller+# that sets either half has set the field the router names.+_MCP_CONTEXT_ONLY_ALIASES = {+ "detail_by_category": "detail",+ "other_peer_penalties": "other_peer_penalty",+}++@mcp.tool()async def search(query: str,@@ -355,6 +364,40 @@ async def search(return result.renderedreturn "No matching context found."+ # POST /search rejects these in list mode and this tool did not, so the two faces of+ # one feature disagreed about whether the request was valid. The list path calls+ # SearchService.search, whose signature has no parameter for any of them, so passing+ # one here did nothing at all -- for exclude_uris that means excluded URIs come back+ # in the results with no error.+ #+ # The names and the wording come from the router rather than being restated here, so+ # a field added to CONTEXT_ONLY_FIELDS reaches both faces at once. This tool splits+ # two of those fields in two, and each half maps back onto the one the router knows.+ supplied_by_caller = {+ name: value+ for name, (value, default) in {+ "query_expansion": (query_expansion, "auto"),+ "max_tokens": (max_tokens, DEFAULT_MAX_TOKENS),+ "quotas": (quotas, None),+ "purpose": (purpose, None),+ "detail": (detail, "auto"),+ "detail_by_category": (detail_by_category, None),+ "dedup_turns": (dedup_turns, 0),+ "exclude_uris": (exclude_uris, None),+ "peer_scope": (peer_scope, "all"),+ "other_peer_penalty": (other_peer_penalty, None),+ "other_peer_penalties": (other_peer_penalties, None),+ "rewrite": (rewrite, "off"),+ "rewrite_max_bullets": (rewrite_max_bullets, 6),+ }.items() if value != default+ }+ as_named_by_caller: Dict[str, set] = {}+ for name in supplied_by_caller:+ as_named_by_caller.setdefault(_MCP_CONTEXT_ONLY_ALIASES.get(name, name), set()).add(name)+ error = context_only_fields_error(as_named_by_caller, as_named_by_caller=as_named_by_caller)+ if error:+ raise InvalidArgumentError(error)+if target_uri:target_uri = _resolve_mcp_workspace_uri(target_uri, ctx)session = Nonediff --git a/openviking/server/routers/search.py b/openviking/server/routers/search.pyindex 309e050ba..1edf20706 100644--- a/openviking/server/routers/search.py+++ b/openviking/server/routers/search.py@@ -172,6 +172,28 @@ CONTEXT_ONLY_FIELDS = ()+def context_only_fields_error(supplied_fields, as_named_by_caller=None) -> Optional[str]:+ """The refusal for context-only arguments in list mode, or None if there is nothing to refuse.++ Both faces of search have to answer the same way here, and both used to carry their+ own copy of the field list and the wording. The MCP tool never builds a+ ``SearchRequest`` -- it calls ``SearchService.search`` directly -- so it cannot inherit+ the validator; it can inherit this.++ ``as_named_by_caller`` maps a field in ``CONTEXT_ONLY_FIELDS`` to the spellings the+ caller actually used, for a face that exposes one of them under more than one name --+ and a caller can set more than one of those at once. Telling somebody who passed+ ``detail_by_category`` that ``detail`` is the problem is not an improvement on having+ no error at all.+ """+ used = sorted(set(CONTEXT_ONLY_FIELDS) & set(supplied_fields))+ if not used:+ return None+ names = sorted({name for field in used for name in ((as_named_by_caller or {}).get(field) or {field})})+ return (f"{', '.join(names)} require mode='context'; "+ "set mode='context' or drop these fields")++class SearchRequest(BaseModel):"""Request model for search with session.@@ -218,12 +240,9 @@ class SearchRequest(BaseModel):@model_validator(mode="after")def _validate_mode(self) -> "SearchRequest":if self.mode == "list":- used = sorted(set(CONTEXT_ONLY_FIELDS) & self.model_fields_set)- if used:- raise ValueError(- f"{', '.join(used)} require mode='context'; "- "set mode='context' or drop these fields"- )+ error = context_only_fields_error(self.model_fields_set)+ if error:+ raise ValueError(error)return selfif self.read_content:diff --git a/tests/server/test_mcp_search_modes.py b/tests/server/test_mcp_search_modes.pynew file mode 100644index 000000000..38c847d2d--- /dev/null+++ b/tests/server/test_mcp_search_modes.py@@ -0,0 +1,177 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++"""``search`` must refuse a context-only argument in ``mode="list"``.++``POST /search`` already does: ``SearchRequest._validate_mode`` rejects any of+``CONTEXT_ONLY_FIELDS`` supplied in list mode. The MCP tool did not, so the two faces of+the same feature disagreed — and the tool refuses the mirror case (``read_content`` and+``target_uri`` in ``mode="context"``), so the gap was only in this direction.++Everything the context path consumes is read only inside that branch, and the list path+calls ``SearchService.search``, whose signature has no parameter for any of them, so+passing one in list mode did nothing and said nothing. For ``exclude_uris`` that is not a+tuning knob going unused: the caller gets back the URIs it asked to exclude.++These tests take no service fixture. A stub service records what the list path forwards,+which is also how the "these never reach the search service" half is pinned.+"""++from types import SimpleNamespace++import pytest++import openviking.server.mcp_endpoint as mcp_endpoint+from openviking.server.dependencies import set_service+from openviking.server.identity import RequestContext, Role+from openviking_cli.exceptions import InvalidArgumentError+from openviking_cli.session.user_id import UserIdentifier++CTX = RequestContext(user=UserIdentifier.the_default_user("test_user"), role=Role.ROOT)++# Every parameter the context path consumes, paired with a non-default value.+CONTEXT_ONLY_ARGS = {+ "query_expansion": "off",+ "max_tokens": 999,+ "quotas": {"events": 5},+ "purpose": "coding",+ "detail": "full",+ "detail_by_category": {"events": "full"},+ "dedup_turns": 3,+ "exclude_uris": ["viking://user/test_user/memories/secret.md"],+ "peer_scope": "actor",+ "other_peer_penalty": 0.5,+ "other_peer_penalties": {"events": 0.5},+ "rewrite": "auto",+ "rewrite_max_bullets": 2,+}+++class _SearchCalled(Exception):+ """Raised by the stub so the list path stops where it hands off to the service."""++ def __init__(self, kwargs: dict):+ super().__init__(sorted(kwargs))+ self.kwargs = kwargs++[email protected](autouse=True)+def _identity_and_stub_service():+ class _Search:+ def is_intent_enabled(self) -> bool:+ return False++ async def search(self, **kwargs):+ raise _SearchCalled(kwargs)++ set_service(SimpleNamespace(search=_Search()))+ token = mcp_endpoint._mcp_ctx.set(CTX)+ yield+ mcp_endpoint._mcp_ctx.reset(token)+ set_service(None)++[email protected]("name,value", sorted(CONTEXT_ONLY_ARGS.items()))+async def test_list_mode_refuses_a_context_only_argument(name, value):+ with pytest.raises(InvalidArgumentError, match=rf"\b{name}\b.*mode='context'"):+ await mcp_endpoint.search(query="anything", **{name: value})+++async def test_list_mode_names_every_context_only_argument_it_refuses():+ # One error listing all of them beats making the caller discover them one call at a+ # time, which is what a per-argument raise would do.+ with pytest.raises(InvalidArgumentError) as excinfo:+ await mcp_endpoint.search(query="anything", **CONTEXT_ONLY_ARGS)++ message = str(excinfo.value)+ assert all(name in message for name in CONTEXT_ONLY_ARGS), message+ assert "require mode='context'" in message+++async def test_list_mode_is_unchanged_without_context_only_arguments():+ with pytest.raises(_SearchCalled) as excinfo:+ await mcp_endpoint.search(query="anything", limit=3)++ forwarded = excinfo.value.kwargs+ assert forwarded["query"] == "anything"+ assert forwarded["limit"] == 3+ # The guard must not have started forwarding them either.+ assert not set(forwarded) & set(CONTEXT_ONLY_ARGS)+++async def test_context_mode_still_accepts_them():+ # The guard is list-mode only; reaching assemble_context (which this stub service+ # cannot satisfy) is enough to show the arguments were not refused up front.+ with pytest.raises(Exception) as excinfo:+ await mcp_endpoint.search(query="anything", mode="context", **CONTEXT_ONLY_ARGS)++ assert "require mode='context'" not in str(excinfo.value)+++async def test_context_mode_still_refuses_list_only_arguments():+ with pytest.raises(InvalidArgumentError, match="only supported in mode='list'"):+ await mcp_endpoint.search(query="anything", mode="context", read_content=True)++ with pytest.raises(InvalidArgumentError, match="not supported in mode='context'"):+ await mcp_endpoint.search(+ query="anything", mode="context", target_uri="viking://user/test_user"+ )+++async def test_the_tool_covers_every_field_the_rest_validator_rejects():+ """The tool's list must not drift from ``POST /search``'s.++ The tool splits two of the REST fields in two — ``detail``/``detail_by_category`` and+ ``other_peer_penalty``/``other_peer_penalties`` — so it carries two more names, not a+ different set. A field added to one face has to reach the other.+ """+ from openviking.server.routers.search import CONTEXT_ONLY_FIELDS++ missing = sorted(set(CONTEXT_ONLY_FIELDS) - set(CONTEXT_ONLY_ARGS))++ assert not missing, (+ "POST /search rejects these in list mode but the MCP tool does not: " + ", ".join(missing)+ )+ assert set(CONTEXT_ONLY_ARGS) - set(CONTEXT_ONLY_FIELDS) == {+ "detail_by_category",+ "other_peer_penalties",+ }+++def test_both_faces_share_one_definition_of_the_refusal():+ """A field added to CONTEXT_ONLY_FIELDS has to reach the MCP tool without a second edit.++ The point of routing this through ``context_only_fields_error`` rather than restating+ the list is that the two faces cannot drift. Pin that by asking the helper directly+ with a field the tool has no parameter for: the router owns the names, so the message+ still names it.+ """+ from openviking.server.routers.search import CONTEXT_ONLY_FIELDS, context_only_fields_error++ for field in CONTEXT_ONLY_FIELDS:+ message = context_only_fields_error({field})+ assert message is not None, f"{field} is context-only but produced no refusal"+ assert field in message++ assert context_only_fields_error(set()) is None+ assert context_only_fields_error({"query", "limit"}) is None+++def test_the_refusal_names_what_the_caller_typed():+ """The tool splits two router fields in two, and the caller has to hear their own name."""+ from openviking.server.routers.search import context_only_fields_error++ message = context_only_fields_error({"detail": {"detail_by_category"}},+ as_named_by_caller={"detail": {"detail_by_category"}})+ assert "detail_by_category" in message++ both = context_only_fields_error({"detail": {"detail", "detail_by_category"}},+ as_named_by_caller={"detail": {"detail", "detail_by_category"}})+ assert "detail_by_category" in both and "detail" in both+