Skip to content

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

fix(mcp): mark whole-call failures as errors (#5078)

z1gon7abd338e6d3a
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index ade7b8149..5d08a2d2b 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -21,6 +21,7 @@ import contextvars
import os
from contextlib import asynccontextmanager
from datetime import datetime, timezone
+from functools import wraps
from pathlib import PurePosixPath
from typing import Annotated, Any, Dict, List, Literal, Optional, Union
from urllib.parse import quote
@@ -29,6 +30,7 @@ from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
from mcp.types import (
AudioContent,
+ CallToolResult,
ContentBlock,
ImageContent,
TextContent,
@@ -273,6 +275,55 @@ _OPEN_WORLD_DESTRUCTIVE_TOOL_ANNOTATIONS = ToolAnnotations(
)
+class _MCPToolFailure(str):
+ """Mark a returned string as a whole-call tool execution failure."""
+
+
+def _mcp_failure(message: str) -> _MCPToolFailure:
+ return _MCPToolFailure(message)
+
+
+def _mcp_error_results(*, structured_output: bool = True):
+ """Adapt an already registered tool to return explicit MCP errors.
+
+ Apply this above ``@mcp.tool`` so the literal registration remains the
+ authoritative tool list. Direct Python calls keep the existing return value.
+ The registered MCP handler converts only ``_MCPToolFailure`` values to
+ ``CallToolResult(isError=True)``.
+ """
+
+ def decorator(func):
+ registered_tool = mcp._tool_manager.get_tool(func.__name__)
+ if registered_tool is None:
+ raise RuntimeError(f"MCP tool is not registered: {func.__name__}")
+
+ @wraps(func)
+ async def wire_handler(*args, **kwargs):
+ result = await func(*args, **kwargs)
+ if not isinstance(result, _MCPToolFailure):
+ return result
+
+ message = str(result)
+ return CallToolResult(
+ content=[TextContent(type="text", text=message)],
+ structuredContent={"result": message} if structured_output else None,
+ isError=True,
+ )
+
+ # Keep the schema and metadata produced by the literal @mcp.tool
+ # registration. Only replace the callable used at the wire boundary.
+ registered_tool.fn = wire_handler
+
+ @wraps(func)
+ async def direct_handler(*args, **kwargs):
+ result = await func(*args, **kwargs)
+ return str(result) if isinstance(result, _MCPToolFailure) else result
+
+ return direct_handler
+
+ return decorator
+
+
# -- find / search ---------------------------------------------------------
@@ -661,6 +712,7 @@ def _mcp_media_download_hint(uri: str) -> str:
)
+@_mcp_error_results(structured_output=False)
@mcp.tool(annotations=_READ_ONLY_TOOL_ANNOTATIONS, structured_output=False)
async def read(
uris: str | list[str],
@@ -675,7 +727,9 @@ async def read(
uri_list = uris if isinstance(uris, list) else [uris]
semaphore = asyncio.Semaphore(10)
- async def _preflight_one(uri: str) -> tuple[str, Optional[int], Optional[str]]:
+ async def _preflight_one(
+ uri: str,
+ ) -> tuple[str, Optional[int], Optional[_MCPToolFailure]]:
"""Resolve a URI and stat media before any binary bytes are loaded."""
try:
resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)
@@ -691,15 +745,19 @@ async def read(
return (
resolved_uri,
None,
- f"Cannot render {uri}: URI points to a directory. "
- "Use the list tool (or `ov ls` / `ov tree`) to browse its contents.",
+ _mcp_failure(
+ f"Cannot render {uri}: URI points to a directory. "
+ "Use the list tool (or `ov ls` / `ov tree`) to browse its contents."
+ ),
)
if is_video:
return (
resolved_uri,
None,
- f"Cannot render {uri}: MCP has no standard VideoContent block. "
- f"{_mcp_media_download_hint(uri)}",
+ _mcp_failure(
+ f"Cannot render {uri}: MCP has no standard VideoContent block. "
+ f"{_mcp_media_download_hint(uri)}"
+ ),
)
size = stat.get("size") if stat else None
@@ -707,25 +765,27 @@ async def read(
return (
resolved_uri,
None,
- f"Cannot render {uri}: file size is unavailable. "
- f"{_mcp_media_download_hint(uri)}",
+ _mcp_failure(
+ f"Cannot render {uri}: file size is unavailable. "
+ f"{_mcp_media_download_hint(uri)}"
+ ),
)
return resolved_uri, size, None
except OpenVikingError as exc:
- return uri, None, str(exc)
+ return uri, None, _mcp_failure(str(exc))
preflight = await asyncio.gather(*[_preflight_one(uri) for uri in uri_list])
- checked: list[tuple[str, Optional[int], Optional[str]]] = []
+ checked: list[tuple[str, Optional[int], Optional[_MCPToolFailure]]] = []
media_total = 0
for uri, (resolved_uri, size, error) in zip(uri_list, preflight, strict=True):
if error is None and size is not None:
if size > _MCP_MEDIA_MAX_BYTES:
- error = (
+ error = _mcp_failure(
f"Media file is too large to inline through MCP ({size} bytes; limit "
f"{_MCP_MEDIA_MAX_BYTES} bytes). {_mcp_media_download_hint(uri)}"
)
elif media_total + size > _MCP_MEDIA_MAX_BYTES:
- error = (
+ error = _mcp_failure(
f"Cannot inline {uri}: combined media size would exceed the MCP tool-call "
f"limit of {_MCP_MEDIA_MAX_BYTES} bytes. Read fewer media files at once. "
f"{_mcp_media_download_hint(uri)}"
@@ -735,7 +795,7 @@ async def read(
checked.append((resolved_uri, size, error))
async def _read_one(
- uri: str, prepared: tuple[str, Optional[int], Optional[str]]
+ uri: str, prepared: tuple[str, Optional[int], Optional[_MCPToolFailure]]
) -> str | ContentBlock:
async with semaphore:
try:
@@ -747,7 +807,7 @@ async def read(
if is_image or is_audio:
data = await service.fs.read_file_bytes(resolved_uri, ctx=ctx)
if declared_size is None or len(data) > declared_size:
- return (
+ return _mcp_failure(
f"Cannot render {uri}: file changed after its size was checked. "
"Retry the read."
)
@@ -757,7 +817,7 @@ async def read(
else _sniff_mcp_audio_mime_type(data, resolved_uri)
)
if mime_type is None:
- return (
+ return _mcp_failure(
f"Cannot render {uri}: its bytes do not match a supported media "
f"format. {_mcp_media_download_hint(uri)}"
)
@@ -772,7 +832,7 @@ async def read(
)
return content
except OpenVikingError as exc:
- return str(exc)
+ return _mcp_failure(str(exc))
if len(uri_list) == 1:
result = await _read_one(uri_list[0], checked[0])
@@ -796,7 +856,10 @@ async def read(
parts = []
for uri, text in zip(uri_list, results, strict=True):
parts.append(f"=== {uri} ===\n{text}")
- return "\n\n".join(parts)
+ combined = "\n\n".join(parts)
+ if results and all(isinstance(result, _MCPToolFailure) for result in results):
+ return _mcp_failure(combined)
+ return combined
# -- list ------------------------------------------------------------------
@@ -1186,6 +1249,19 @@ async def _maybe_sitemap_hint(path: str) -> str:
return ""
+def _resource_add_error(result: Any) -> _MCPToolFailure | None:
+ if not isinstance(result, dict) or result.get("status") != "error":
+ return None
+ errors = result.get("errors")
+ detail = (
+ result.get("message")
+ or (errors[0] if isinstance(errors, list) and errors else None)
+ or "resource processing failed"
+ )
+ return _mcp_failure(f"Error adding resource: {detail}")
+
+
+@_mcp_error_results()
@mcp.tool(annotations=_OPEN_WORLD_DESTRUCTIVE_TOOL_ANNOTATIONS)
async def add_resource(
path: str = "",
@@ -1272,30 +1348,30 @@ async def add_resource(
field_name="parent",
)
except (InvalidArgumentError, PermissionDeniedError) as exc:
- return f"Error: {exc}"
+ return _mcp_failure(f"Error: {exc}")
try:
mode = normalize_parse_mode((args or {}).get("parse_mode", ParseMode.DEFAULT))
except InvalidArgumentError as exc:
- return f"Error: {exc}"
+ return _mcp_failure(f"Error: {exc}")
if watch_interval < 0:
- return (
+ return _mcp_failure(
"Error: watch_interval must be >= 0. Use 0 for one-shot add (no watch); "
"use a positive number of minutes (>=1440 recommended) to subscribe to auto-refresh."
)
add_type = add_type.strip()
if add_type and temp_file_id:
- return "Error: add_type cannot be combined with temp_file_id."
+ return _mcp_failure("Error: add_type cannot be combined with temp_file_id.")
if add_type and not path:
- return "Error: add_type requires 'path'."
+ return _mcp_failure("Error: add_type requires 'path'.")
if add_type and parent:
- return "Error: add_type cannot be combined with parent."
+ return _mcp_failure("Error: add_type cannot be combined with parent.")
if add_type and not to:
- return "Error: add_type requires an exact 'to' target."
+ return _mcp_failure("Error: add_type requires an exact 'to' target.")
if to and parent:
- return "Error: Cannot specify both 'to' and 'parent' at the same time."
+ return _mcp_failure("Error: Cannot specify both 'to' and 'parent' at the same time.")
# Branch 1: ingest by temp_file_id. Kept for backward compat / REST-style use — the
# signed upload now auto-ingests server-side, so agents no longer need this second leg.
@@ -1318,19 +1394,12 @@ async def add_resource(
tag_mode=tag_mode,
)
except (PermissionDeniedError, InvalidArgumentError) as exc:
- return f"Error: {exc}"
+ return _mcp_failure(f"Error: {exc}")
except Exception as exc:
- return f"Error adding resource: {exc}"
- # add_resource returns a business-error dict (no raise) for parse/finalize failures;
- # surface it instead of reporting a false success.
- if isinstance(result, dict) and result.get("status") == "error":
- errors = result.get("errors")
- detail = (
- result.get("message")
- or (errors[0] if isinstance(errors, list) and errors else None)
- or "resource processing failed"
- )
- return f"Error adding resource: {detail}"
+ return _mcp_failure(f"Error adding resource: {exc}")
+ error = _resource_add_error(result)
+ if error is not None:
+ return error
root_uri = result.get("root_uri", "") if isinstance(result, dict) else ""
return (
f"Resource added: {root_uri}"
@@ -1339,11 +1408,13 @@ async def add_resource(
)
if not path:
- return "Error: provide either 'path' (remote URL or local file) or 'temp_file_id'."
+ return _mcp_failure(
+ "Error: provide either 'path' (remote URL or local file) or 'temp_file_id'."
+ )
# Branch 2: agent passed a temp_file_id-shaped string as `path` — guide them
if TEMP_FILE_ID_RE.match(path):
- return (
+ return _mcp_failure(
f"Error: '{path}' looks like a temp_file_id, not a path. "
f'Pass it as the temp_file_id kwarg: add_resource(temp_file_id="{path}")'
)
@@ -1372,7 +1443,10 @@ async def add_resource(
tag_mode=tag_mode,
)
except Exception as exc:
- return f"Error adding resource: {exc}"
+ return _mcp_failure(f"Error adding resource: {exc}")
+ error = _resource_add_error(result)
+ if error is not None:
+ return error
root_uri = result.get("root_uri", "")
task_id = result.get("task_id", "")
if watch_interval > 0:
@@ -1462,7 +1536,9 @@ async def add_resource(
def _format_skill_install_result(result: Dict[str, Any], *, list_only: bool) -> str:
if result.get("status") == "error":
- return f"Error adding skill: {result.get('message') or 'skill processing failed'}"
+ return _mcp_failure(
+ f"Error adding skill: {result.get('message') or 'skill processing failed'}"
+ )
if list_only:
found = result.get("skills") or []
lines = [f"Skills in the source ({len(found)}); nothing was installed:"]
@@ -1478,6 +1554,7 @@ def _format_skill_install_result(result: Dict[str, Any], *, list_only: bool) ->
return "\n".join(lines)
+@_mcp_error_results()
@mcp.tool(annotations=_OPEN_WORLD_DESTRUCTIVE_TOOL_ANNOTATIONS)
async def add_skill(
data: str = "",
@@ -1521,21 +1598,23 @@ async def add_skill(
ctx = _get_ctx()
path = path.strip()
if data.strip() and path:
- return "Error: pass either 'data' (SKILL.md text) or 'path', not both."
+ return _mcp_failure("Error: pass either 'data' (SKILL.md text) or 'path', not both.")
if not data.strip() and not path:
- return "Error: provide 'data' (full SKILL.md text) or 'path' (Git URL or local path)."
+ return _mcp_failure(
+ "Error: provide 'data' (full SKILL.md text) or 'path' (Git URL or local path)."
+ )
if data.strip() and looks_like_local_path(data.strip()):
- return (
+ return _mcp_failure(
f"Error: 'data' looks like a file path. Pass it as add_skill(path=\"{data.strip()}\")."
)
if path.startswith("viking://"):
- return (
+ return _mcp_failure(
"Error: 'path' must be a Git URL or a local path. To copy a skill already in "
"OpenViking, read its SKILL.md and pass the text as 'data'."
)
is_git = path.startswith(GIT_SKILL_SOURCE_PREFIXES)
if path and not is_git and is_remote_resource_source(path):
- return (
+ return _mcp_failure(
f"Error: unsupported skill source '{path}'. Pass a Git URL "
f"({', '.join(GIT_SKILL_SOURCE_PREFIXES)}) or a local path."
)
@@ -1546,7 +1625,7 @@ async def add_skill(
# Fail here, not after a one-time upload token is spent on a root the installer rejects.
target = SkillProcessor._resolve_skill_root_uri(ctx, target) # noqa: SLF001
except (InvalidArgumentError, PermissionDeniedError) as exc:
- return f"Error: {exc}"
+ return _mcp_failure(f"Error: {exc}")
if data.strip() or is_git:
try:
@@ -1563,9 +1642,9 @@ async def add_skill(
),
)
except (InvalidArgumentError, PermissionDeniedError) as exc:
- return f"Error: {exc}"
+ return _mcp_failure(f"Error: {exc}")
except Exception as exc:
- return f"Error adding skill: {exc}"
+ return _mcp_failure(f"Error adding skill: {exc}")
return _format_skill_install_result(result, list_only=list_only)
server_config = get_server_config()
@@ -1643,6 +1722,7 @@ async def add_skill(
# `resume`, `trigger`, `update --interval`, etc.) for those operations.
+@_mcp_error_results()
@mcp.tool(annotations=_READ_ONLY_TOOL_ANNOTATIONS)
async def list_watches() -> str:
"""List watch tasks (auto-refresh subscriptions) visible to the current user."""
@@ -1650,10 +1730,10 @@ async def list_watches() -> str:
ctx = _get_ctx()
scheduler = getattr(service, "watch_scheduler", None)
if scheduler is None or not scheduler.is_running:
- return "Error: Watch scheduler not running"
+ return _mcp_failure("Error: Watch scheduler not running")
wm = scheduler.watch_manager
if wm is None:
- return "Error: Watch scheduler not running"
+ return _mcp_failure("Error: Watch scheduler not running")
# get_all_tasks does not raise PermissionDeniedError — it silently filters
# tasks the caller cannot see (watch_manager.py:596-624), so we just
# accept the filtered list.
@@ -1675,6 +1755,7 @@ async def list_watches() -> str:
return "\n".join(lines)
+@_mcp_error_results()
@mcp.tool(annotations=_RETRY_SAFE_DESTRUCTIVE_TOOL_ANNOTATIONS)
async def cancel_watch(to_uri: str) -> str:
"""Cancel a watch task by its target URI (e.g. "viking://resources/volcengine/OpenViking")."""
@@ -1685,10 +1766,10 @@ async def cancel_watch(to_uri: str) -> str:
to_uri = _resolve_mcp_workspace_uri(to_uri, ctx)
scheduler = getattr(service, "watch_scheduler", None)
if scheduler is None or not scheduler.is_running:
- return "Error: Watch scheduler not running"
+ return _mcp_failure("Error: Watch scheduler not running")
wm = scheduler.watch_manager
if wm is None:
- return "Error: Watch scheduler not running"
+ return _mcp_failure("Error: Watch scheduler not running")
task = await wm.get_task_by_uri(
to_uri,
ctx.account_id,
@@ -1696,7 +1777,7 @@ async def cancel_watch(to_uri: str) -> str:
str(ctx.role),
)
if task is None:
- return f"No watch task found for {to_uri}"
+ return _mcp_failure(f"No watch task found for {to_uri}")
try:
# Return value (bool) is intentionally ignored: delete_task returns
# False only when the task was removed between our lookup and the
@@ -1711,13 +1792,14 @@ async def cancel_watch(to_uri: str) -> str:
str(ctx.role),
)
except _wm_mod.PermissionDeniedError:
- return f"Permission denied for {to_uri}"
+ return _mcp_failure(f"Permission denied for {to_uri}")
return f"Watch cancelled: {to_uri}"
# -- grep ------------------------------------------------------------------
+@_mcp_error_results()
@mcp.tool(annotations=_READ_ONLY_TOOL_ANNOTATIONS)
async def grep(
uri: str, pattern: str | list[str], case_insensitive: bool = False, node_limit: int = 10
@@ -1766,10 +1848,14 @@ async def grep(
failure_lines = [f" {p}: {error}" for p, error in failures]
if not merged:
+ if failures and len(failures) == len(results):
+ return _mcp_failure("grep failed for every pattern:\n" + "\n".join(failure_lines))
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)
+ successful = [p for p, _, error in results if error is None]
+ return (
+ f"No matches found for successful pattern(s): {', '.join(successful)}\n"
+ "Patterns that could not be searched:\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):"]
@@ -1787,6 +1873,7 @@ async def grep(
# -- glob ------------------------------------------------------------------
+@_mcp_error_results()
@mcp.tool(annotations=_READ_ONLY_TOOL_ANNOTATIONS)
async def glob(pattern: str, uri: str = "viking://", node_limit: int = 100) -> str:
"""Find viking:// files matching a glob pattern (e.g. **/*.md, *.py). Use this for filename matching; use the search tool for content-based retrieval."""
@@ -1797,7 +1884,7 @@ async def glob(pattern: str, uri: str = "viking://", node_limit: int = 100) -> s
try:
result = await service.fs.glob(pattern, ctx=ctx, uri=resolved_uri, node_limit=node_limit)
except Exception as e:
- return f"Error: {e}"
+ return _mcp_failure(f"Error: {e}")
matches = result.get("matches", [])
if not matches:
diff --git a/tests/unit/test_mcp_tool_error_results.py b/tests/unit/test_mcp_tool_error_results.py
new file mode 100644
index 000000000..a9c8a99c2
--- /dev/null
+++ b/tests/unit/test_mcp_tool_error_results.py
@@ -0,0 +1,232 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""MCP wire-result tests for tool execution failures."""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from mcp.types import CallToolRequest, CallToolRequestParams
+
+import openviking.server.mcp_endpoint as mcp_endpoint
+from openviking.server.identity import RequestContext, Role
+from openviking_cli.exceptions import InvalidArgumentError
+from openviking_cli.session.user_id import UserIdentifier
+
+
[email protected](autouse=True)
+def _set_mcp_identity():
+ context = RequestContext(
+ user=UserIdentifier.the_default_user("mcp-error-test"),
+ role=Role.ROOT,
+ )
+ token = mcp_endpoint._mcp_ctx.set(context)
+ yield
+ mcp_endpoint._mcp_ctx.reset(token)
+
+
+async def _call_tool(name: str, arguments: dict) -> dict:
+ handler = mcp_endpoint.mcp._mcp_server.request_handlers[CallToolRequest]
+ request = CallToolRequest(
+ params=CallToolRequestParams(name=name, arguments=arguments),
+ )
+ return (await handler(request)).root.model_dump(by_alias=True, exclude_none=True)
+
+
+ ("name", "arguments", "service", "message"),
+ [
+ pytest.param(
+ "add_resource",
+ {"path": "space:home", "add_type": "feishu"},
+ SimpleNamespace(),
+ "Error: add_type requires an exact 'to' target.",
+ id="validation",
+ ),
+ pytest.param(
+ "list_watches",
+ {},
+ SimpleNamespace(watch_scheduler=None),
+ "Error: Watch scheduler not running",
+ id="watch-list-unavailable",
+ ),
+ pytest.param(
+ "cancel_watch",
+ {"to_uri": "viking://resources/project"},
+ SimpleNamespace(watch_scheduler=None),
+ "Error: Watch scheduler not running",
+ id="watch-cancel-unavailable",
+ ),
+ pytest.param(
+ "glob",
+ {"pattern": "**/*.md"},
+ SimpleNamespace(
+ fs=SimpleNamespace(glob=AsyncMock(side_effect=RuntimeError("storage offline")))
+ ),
+ "Error: storage offline",
+ id="glob-backend",
+ ),
+ pytest.param(
+ "add_skill",
+ {},
+ SimpleNamespace(),
+ "Error: provide 'data' (full SKILL.md text) or 'path' (Git URL or local path).",
+ id="skill-validation",
+ ),
+ pytest.param(
+ "grep",
+ {"uri": "viking://resources", "pattern": "needle"},
+ SimpleNamespace(
+ fs=SimpleNamespace(grep=AsyncMock(side_effect=RuntimeError("storage offline")))
+ ),
+ "grep failed for every pattern:\n needle: RuntimeError: storage offline",
+ id="grep-all-failed",
+ ),
+ ],
+)
+async def test_whole_call_failure_sets_error_result(monkeypatch, name, arguments, service, message):
+ monkeypatch.setattr(mcp_endpoint, "get_service", lambda: service)
+
+ direct_result = await getattr(mcp_endpoint, name)(**arguments)
+ result = await _call_tool(name, arguments)
+
+ assert type(direct_result) is str
+ assert direct_result == message
+ assert result["isError"] is True
+ assert result["content"] == [{"type": "text", "text": message}]
+ assert result["structuredContent"] == {"result": message}
+
+
+async def test_remote_resource_business_failure_sets_error_result(monkeypatch):
+ service = SimpleNamespace(
+ resources=SimpleNamespace(
+ add_resource=AsyncMock(
+ return_value={"status": "error", "message": "processor rejected"}
+ )
+ )
+ )
+ monkeypatch.setattr(mcp_endpoint, "get_service", lambda: service)
+ arguments = {"path": "https://example.com/article"}
+
+ direct_result = await mcp_endpoint.add_resource(**arguments)
+ result = await _call_tool("add_resource", arguments)
+
+ assert direct_result == "Error adding resource: processor rejected"
+ assert type(direct_result) is str
+ assert result["isError"] is True
+ assert result["content"] == [{"type": "text", "text": direct_result}]
+
+
+async def test_skill_install_business_failure_sets_error_result(monkeypatch):
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "install_skills",
+ AsyncMock(return_value={"status": "error", "message": "invalid skill"}),
+ )
+ arguments = {"data": "---\nname: example\ndescription: Example\n---\nBody"}
+
+ direct_result = await mcp_endpoint.add_skill(**arguments)
+ result = await _call_tool("add_skill", arguments)
+
+ assert direct_result == "Error adding skill: invalid skill"
+ assert type(direct_result) is str
+ assert result["isError"] is True
+ assert result["content"] == [{"type": "text", "text": direct_result}]
+
+
+async def test_grep_partial_failure_without_matches_stays_partial(monkeypatch):
+ async def grep(_uri, pattern, **_kwargs):
+ if pattern == "bad":
+ raise RuntimeError("storage offline")
+ return {"matches": []}
+
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(fs=SimpleNamespace(grep=grep)),
+ )
+ arguments = {"uri": "viking://resources", "pattern": ["good", "bad"]}
+
+ direct_result = await mcp_endpoint.grep(**arguments)
+ result = await _call_tool("grep", arguments)
+
+ assert direct_result == (
+ "No matches found for successful pattern(s): good\n"
+ "Patterns that could not be searched:\n bad: RuntimeError: storage offline"
+ )
+ assert result["isError"] is False
+ assert result["content"] == [{"type": "text", "text": direct_result}]
+
+
+async def test_read_all_failures_set_error_result(monkeypatch):
+ read_visible = AsyncMock(side_effect=InvalidArgumentError("not readable"))
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(fs=SimpleNamespace(read_visible=read_visible)),
+ )
+
+ arguments = {
+ "uris": ["viking://resources/a.md", "viking://resources/b.md"],
+ }
+ direct_result = await mcp_endpoint.read(**arguments)
+ result = await _call_tool(
+ "read",
+ arguments,
+ )
+
+ assert type(direct_result) is str
+ assert direct_result == (
+ "=== viking://resources/a.md ===\nnot readable\n\n"
+ "=== viking://resources/b.md ===\nnot readable"
+ )
+ assert result["isError"] is True
+ assert "not readable" in result["content"][0]["text"]
+ assert "structuredContent" not in result
+
+
+async def test_read_partial_failure_remains_a_success_result(monkeypatch):
+ async def read_visible(uri, **kwargs):
+ if uri.endswith("bad.md"):
+ raise InvalidArgumentError("not readable")
+ return "visible content"
+
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(fs=SimpleNamespace(read_visible=read_visible)),
+ )
+
+ arguments = {
+ "uris": [
+ "viking://resources/good.md",
+ "viking://resources/bad.md",
+ ]
+ }
+ direct_result = await mcp_endpoint.read(**arguments)
+ result = await _call_tool(
+ "read",
+ arguments,
+ )
+
+ assert type(direct_result) is str
+ assert "visible content" in direct_result
+ assert "not readable" in direct_result
+ assert result["isError"] is False
+ assert "visible content" in result["content"][0]["text"]
+ assert "not readable" in result["content"][0]["text"]
+
+
+async def test_health_unavailable_remains_diagnostic_data(monkeypatch):
+ def unavailable():
+ raise RuntimeError("not initialized")
+
+ monkeypatch.setattr(mcp_endpoint, "get_service", unavailable)
+
+ result = await _call_tool("health", {})
+
+ assert result["isError"] is False
+ assert result["content"] == [
+ {"type": "text", "text": "OpenViking is unhealthy: not initialized"}
+ ]