Skip to content

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

fix(mcp): return read errors from underlying fs (#4093)

zgy868a9600d039
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index 61feca56d..8cab3ccf3 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -52,6 +52,7 @@ from openviking.utils.search_filters import SearchContextTypeInput, merge_search
from openviking_cli.exceptions import (
InvalidArgumentError,
NotFoundError,
+ OpenVikingError,
PermissionDeniedError,
UnauthenticatedError,
)
@@ -423,8 +424,12 @@ async def read(uris: str | list[str]) -> str:
async def _read_one(uri: str) -> str:
async with semaphore:
- resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)
- return await service.fs.read_for_tool(resolved_uri, ctx=ctx, display_uri=uri)
+ try:
+ resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)
+ content = await service.fs.read_visible(resolved_uri, ctx=ctx)
+ return content
+ except OpenVikingError as exc:
+ return str(exc)
if len(uri_list) == 1:
return await _read_one(uri_list[0])
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 14ec64060..52c62e5cd 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -29,7 +29,7 @@ from openviking.telemetry import get_current_telemetry
from openviking.telemetry.request_wait_tracker import get_request_wait_tracker
from openviking.telemetry.resource_summary import build_queue_status_payload
from openviking.utils.embedding_utils import vectorize_directory_meta
-from openviking_cli.exceptions import DeadlineExceededError, NotFoundError, NotInitializedError
+from openviking_cli.exceptions import DeadlineExceededError, NotInitializedError
from openviking_cli.utils import VikingURI, get_logger
logger = get_logger(__name__)
@@ -587,29 +587,6 @@ class FSService:
content = await self.read(uri, ctx=ctx)
return visible_content(content, uri=uri, offset=offset, limit=limit)
- async def read_for_tool(
- self,
- uri: str,
- ctx: RequestContext,
- *,
- display_uri: str | None = None,
- ) -> str:
- """Read content for agent tools, returning recoverable text for common read misses."""
- display_uri = display_uri or uri
- try:
- stat = await self.stat(uri, ctx=ctx)
- except NotFoundError:
- return f"(not found at {display_uri})"
- if stat.get("isDir", stat.get("is_dir", False)):
- return (
- f"Directory URI is not readable as a file: {display_uri}. "
- "Use the list tool on this URI to inspect children, then use read on a file URI."
- )
- content = await self.read_visible(uri, ctx=ctx)
- if isinstance(content, str) and content.strip():
- return content
- return f"(empty file at {display_uri})"
-
async def abstract(self, uri: str, ctx: RequestContext) -> str:
"""Read L0 abstract (.abstract.md)."""
viking_fs = self._ensure_initialized()
diff --git a/openviking/storage/viking_fs/_ops.py b/openviking/storage/viking_fs/_ops.py
index f934c7c00..ec9dcca01 100644
--- a/openviking/storage/viking_fs/_ops.py
+++ b/openviking/storage/viking_fs/_ops.py
@@ -976,7 +976,8 @@ class _OpsMixin:
raise NotFoundError(uri, "file") from last_not_found
if isinstance(stat, dict) and stat.get("isDir", False):
raise InvalidArgumentError(
- f"Cannot read directory as file: {uri}",
+ f"Directory URI is not readable as a file: {uri}. "
+ "List it first, then read a file URI.",
details={"resource": uri, "expected": "file", "actual": "directory"},
)
try:
diff --git a/tests/server/test_api_content.py b/tests/server/test_api_content.py
index c553e639e..a9487a036 100644
--- a/tests/server/test_api_content.py
+++ b/tests/server/test_api_content.py
@@ -113,7 +113,8 @@ async def test_read_directory_uri_returns_invalid_argument(client_with_resource)
body = resp.json()
assert body["status"] == "error"
assert body["error"]["code"] == "INVALID_ARGUMENT"
- assert "Cannot read directory as file" in body["error"]["message"]
+ assert "Directory URI is not readable as a file" in body["error"]["message"]
+ assert "List it first, then read a file URI." in body["error"]["message"]
assert body["error"]["details"] == {
"resource": uri,
"expected": "file",
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index 78afe3813..ba0c15d58 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -540,8 +540,8 @@ async def test_read_directory_uri_returns_recoverable_hint(service):
result = await read(uri)
assert "Directory URI is not readable as a file" in result
- assert "Use the list tool" in result
- assert "then use read on a file URI" in result
+ assert "List it first, then read a file URI." in result
+ assert uri in result
assert "nothing found" not in result.lower()
@@ -556,20 +556,19 @@ async def test_read_batch(service):
assert "not found" in result.lower()
-async def test_read_delegates_to_tool_read(monkeypatch):
- read_for_tool = AsyncMock(return_value="visible memory")
+async def test_read_delegates_to_visible_read(monkeypatch):
+ read_visible = AsyncMock(return_value="visible memory")
monkeypatch.setattr(
mcp_endpoint,
"get_service",
- lambda: SimpleNamespace(fs=SimpleNamespace(read_for_tool=read_for_tool)),
+ lambda: SimpleNamespace(fs=SimpleNamespace(read_visible=read_visible)),
)
uri = "viking://user/project/private.md"
assert await read(uri) == "visible memory"
- read_for_tool.assert_awaited_once_with(
+ read_visible.assert_awaited_once_with(
"viking://user/test_user/project/private.md",
ctx=DEFAULT_CTX,
- display_uri=uri,
)
diff --git a/tests/service/test_fs_service.py b/tests/service/test_fs_service.py
index ed89de4f9..941b31d5e 100644
--- a/tests/service/test_fs_service.py
+++ b/tests/service/test_fs_service.py
@@ -9,7 +9,6 @@ import pytest
from openviking.server.identity import RequestContext, Role
from openviking.service.fs_service import FSService
-from openviking_cli.exceptions import NotFoundError
from openviking_cli.session.user_id import UserIdentifier
@@ -184,46 +183,6 @@ async def test_read_visible_preserves_non_memory_content(request_context):
)
-async def test_read_for_tool_returns_not_found_message(request_context):
- uri = "viking://resources/missing.md"
- viking_fs = SimpleNamespace(stat=AsyncMock(side_effect=NotFoundError(uri)))
- service = FSService(viking_fs=viking_fs)
-
- result = await service.read_for_tool(uri, ctx=request_context, display_uri="viking://alias.md")
-
- assert result == "(not found at viking://alias.md)"
-
-
-async def test_read_for_tool_returns_directory_hint(request_context):
- viking_fs = SimpleNamespace(
- stat=AsyncMock(return_value={"isDir": True}),
- read_file=AsyncMock(),
- )
- service = FSService(viking_fs=viking_fs)
-
- result = await service.read_for_tool("viking://resources/docs", ctx=request_context)
-
- assert "Directory URI is not readable as a file" in result
- assert "Use the list tool" in result
- viking_fs.read_file.assert_not_awaited()
-
-
-async def test_read_for_tool_returns_empty_file_message(request_context):
- uri = "viking://resources/empty.md"
- viking_fs = SimpleNamespace(
- stat=AsyncMock(return_value={"isDir": False}),
- read_file=AsyncMock(return_value=""),
- )
- service = FSService(viking_fs=viking_fs)
-
- result = await service.read_for_tool(uri, ctx=request_context)
-
- assert result == f"(empty file at {uri})"
-
-
@pytest.mark.asyncio
async def test_grep_projects_memory_content_but_keeps_resource_fast_path(request_context):
viking_fs = SimpleNamespace(grep=AsyncMock(return_value={"matches": []}))