Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(mcp): stop grep reporting every failure as "no matches" (#4896)

alanhuangyooaf2882a7c22c
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index 14b83fc17..966c0c15c 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -1351,7 +1351,7 @@ async def grep(
patterns = [pattern] if isinstance(pattern, str) else pattern
semaphore = asyncio.Semaphore(10)
- async def _grep_one(p: str) -> tuple[str, list[dict]]:
+ async def _grep_one(p: str) -> tuple[str, list[dict], Optional[str]]:
async with semaphore:
try:
result = await service.fs.grep(
@@ -1361,21 +1361,35 @@ async def grep(
case_insensitive=case_insensitive,
node_limit=node_limit,
)
- return (p, result.get("matches", []))
- except Exception:
- return (p, [])
+ return (p, result.get("matches", []), None)
+ except Exception as exc:
+ # One bad pattern must not cost the others their matches -- that is what
+ # the fan-out is for -- but an empty list is indistinguishable from a real
+ # miss, so carry the reason instead of dropping it. POST /search/grep maps
+ # and re-raises these; reporting them is what keeps the two faces agreeing
+ # about whether a failure is a result.
+ return (p, [], f"{type(exc).__name__}: {exc}")
results = await asyncio.gather(*[_grep_one(p) for p in patterns])
merged: dict[str, list[tuple]] = {}
total = 0
- for p, matches in results:
+ failures: list[tuple[str, str]] = []
+ for p, matches, error in results:
+ if error is not None:
+ failures.append((p, error))
total += len(matches)
for m in matches:
m_uri = m.get("uri", "?")
merged.setdefault(m_uri, []).append((m.get("line", "?"), m.get("content", ""), p))
+ failure_lines = [f" {p}: {error}" for p, error in failures]
+
if not merged:
+ if failures:
+ # Nothing was searched successfully, so "no matches" would be an answer to a
+ # question that was never asked.
+ return "grep failed for every pattern:\n" + "\n".join(failure_lines)
return f"No matches found for pattern(s): {', '.join(patterns)}"
lines = [f"Found {total} match(es) across {len(patterns)} pattern(s):"]
@@ -1384,6 +1398,9 @@ async def grep(
lines.append(f"\n{m_uri}")
for line_no, content, p in hits:
lines.append(f" L{line_no} [{p}]: {content}")
+ if failures:
+ lines.append("\nPatterns that could not be searched:")
+ lines.extend(failure_lines)
return "\n".join(lines)
diff --git a/tests/server/test_mcp_grep_failures.py b/tests/server/test_mcp_grep_failures.py
new file mode 100644
index 000000000..ea1312a20
--- /dev/null
+++ b/tests/server/test_mcp_grep_failures.py
@@ -0,0 +1,119 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""``grep`` must not report a failure as "no matches".
+
+The tool fans out over its patterns and used to swallow every per-pattern exception into
+an empty match list, which the tail then rendered as ``No matches found``. A missing URI,
+a permission denial, a malformed regex and an unreachable backend were therefore
+indistinguishable from a search that genuinely found nothing, so the caller concluded the
+content was not there.
+
+``POST /api/v1/search/grep`` maps the exception and re-raises it, so the two faces
+disagreed about whether a failure is a result.
+
+The fan-out is kept: one bad pattern must not cost the others their matches. What changes
+is that the reason travels with the empty list instead of being dropped.
+"""
+
+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 NotFoundError, PermissionDeniedError
+from openviking_cli.session.user_id import UserIdentifier
+
+CTX = RequestContext(user=UserIdentifier.the_default_user("test_user"), role=Role.ROOT)
+URI = "viking://user/test_user/memories"
+
+
+def _install(grep):
+ set_service(SimpleNamespace(fs=SimpleNamespace(grep=grep)))
+
+
[email protected](autouse=True)
+def _identity():
+ token = mcp_endpoint._mcp_ctx.set(CTX)
+ yield
+ mcp_endpoint._mcp_ctx.reset(token)
+ set_service(None)
+
+
+ "exc",
+ [
+ NotFoundError(URI, "file"),
+ PermissionDeniedError("access denied"),
+ RuntimeError("vector store unreachable"),
+ ],
+ ids=["not-found", "permission-denied", "backend-error"],
+)
+async def test_a_failure_is_not_reported_as_no_matches(exc):
+ async def grep(uri, pattern, **kwargs):
+ raise exc
+
+ _install(grep)
+
+ out = await mcp_endpoint.grep(uri=URI, pattern="anything")
+
+ assert "No matches found" not in out
+ assert type(exc).__name__ in out
+
+
+async def test_a_genuine_miss_still_reads_as_no_matches():
+ async def grep(uri, pattern, **kwargs):
+ return {"matches": []}
+
+ _install(grep)
+
+ assert await mcp_endpoint.grep(uri=URI, pattern="anything") == (
+ "No matches found for pattern(s): anything"
+ )
+
+
+async def test_one_failing_pattern_does_not_cost_the_others_their_matches():
+ async def grep(uri, pattern, **kwargs):
+ if pattern == "bad":
+ raise RuntimeError("boom")
+ return {"matches": [{"uri": f"{URI}/a.md", "line": 3, "content": "hit"}]}
+
+ _install(grep)
+
+ out = await mcp_endpoint.grep(uri=URI, pattern=["good", "bad"])
+
+ assert "hit" in out and "L3" in out
+ assert "Patterns that could not be searched:" in out
+ assert "bad: RuntimeError: boom" in out
+
+
+async def test_every_pattern_failing_reports_each_one():
+ async def grep(uri, pattern, **kwargs):
+ raise RuntimeError(f"boom-{pattern}")
+
+ _install(grep)
+
+ out = await mcp_endpoint.grep(uri=URI, pattern=["one", "two"])
+
+ assert out.startswith("grep failed for every pattern:")
+ assert "one: RuntimeError: boom-one" in out
+ assert "two: RuntimeError: boom-two" in out
+
+
+async def test_a_clean_multi_pattern_search_is_unchanged():
+ async def grep(uri, pattern, **kwargs):
+ return {"matches": [{"uri": f"{URI}/a.md", "line": 1, "content": pattern}]}
+
+ _install(grep)
+
+ out = await mcp_endpoint.grep(uri=URI, pattern=["x", "y"])
+
+ assert out.startswith("Found 2 match(es) across 2 pattern(s):")
+ assert "could not be searched" not in out