Skip to content

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

feat(mcp): return media as native content blocks (#4257)

Zayn Jarvis0e77cd4eb79e
diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.md
index 145b91c5a..deba945f7 100644
--- a/docs/en/guides/06-mcp-integration.md
+++ b/docs/en/guides/06-mcp-integration.md
@@ -135,7 +135,7 @@ Once connected, OpenViking exposes 15 tools:
|------|-------------|----------------|
| `find` | Fast semantic retrieval without session context | `query`, `target_uri` (optional), `limit`, `min_score`, `level` (optional), `context_type` (optional) |
| `search` | Deep semantic retrieval; `mode="context"` assembles injection-ready context and replaces the former `recall` tool | `query`, `mode` (`list` or `context`), `target_uri` (list mode only), `session_id` (optional), `limit`, `min_score`, `level` (list mode), `context_type` (optional), plus context-mode `quotas`, `purpose`, `max_tokens`, `detail` or `detail_by_category`, `dedup_turns`, `exclude_uris`, `peer_scope`, scalar `other_peer_penalty` or `other_peer_penalties` by category, and `rewrite` (`off` or `auto`) |
-| `read` | Read one or more `viking://` URIs | `uris` (single string or array) |
+| `read` | Read one or more `viking://` URIs. PNG, JPEG, GIF, and WebP return native MCP image content; WAV, MP3, FLAC, OGG, and M4A return native audio content. Video is not supported because MCP has no standard video content block | `uris` (single string or array) |
| `list` | List entries under a `viking://` directory | `uri`, `recursive` (optional) |
| `tree` | Show the recursive directory tree under a `viking://` URI, indented by depth — use when you need a full picture of the file tree (prefer `list` for a single level, `glob` for filename patterns) | `uri` (optional), `level_limit` (default 3), `node_limit` (default 1000), `include_abstract` (optional — also show each file's summary) |
| `remember` | Store messages into long-term memory (triggers extraction) | `messages` (list of `{role, content}`) |
diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.md
index 8d6cdd405..5e8f4c9c2 100644
--- a/docs/zh/guides/06-mcp-integration.md
+++ b/docs/zh/guides/06-mcp-integration.md
@@ -127,7 +127,7 @@ claude mcp add --transport http openviking \
|------|------|----------|
| `find` | 无 session 上下文的快速语义检索 | `query`, `target_uri`(可选), `limit`, `min_score`, `level`(可选), `context_type`(可选) |
| `search` | 深度语义检索;`mode="context"` 组装可直接注入的上下文,并替代原 `recall` 工具 | `query`, `mode`(`list` 或 `context`), `target_uri`(仅 list 模式), `session_id`(可选), `limit`, `min_score`, `level`(list 模式), `context_type`(可选),以及 context 模式的 `quotas`, `purpose`, `max_tokens`, `detail` 或 `detail_by_category`, `dedup_turns`, `exclude_uris`, `peer_scope`, 标量 `other_peer_penalty` 或按类别设置的 `other_peer_penalties`, `rewrite`(`off` 或 `auto`) |
-| `read` | 读取一个或多个 `viking://` URI 的内容 | `uris`(单个字符串或数组) |
+| `read` | 读取一个或多个 `viking://` URI 的内容。PNG、JPEG、GIF、WebP 返回 MCP 原生图片内容;WAV、MP3、FLAC、OGG、M4A 返回原生音频内容。MCP 没有标准视频内容块,因此暂不支持视频 | `uris`(单个字符串或数组) |
| `list` | 列出 `viking://` 目录下的条目 | `uri`, `recursive`(可选) |
| `tree` | 以缩进形式展示 `viking://` URI 下的递归目录树——当需要全面了解文件树结构时使用(单层列表用 `list`,按文件名查找用 `glob`) | `uri`(可选), `level_limit`(默认 3), `node_limit`(默认 1000), `include_abstract`(可选——同时展示每个文件的摘要) |
| `remember` | 存储消息到长期记忆(触发记忆提取) | `messages`(`{role, content}` 列表) |
diff --git a/examples/codex-memory-plugin/scripts/marketplace.test.mjs b/examples/codex-memory-plugin/scripts/marketplace.test.mjs
index 0c27cc64f..1f8ebcf4a 100644
--- a/examples/codex-memory-plugin/scripts/marketplace.test.mjs
+++ b/examples/codex-memory-plugin/scripts/marketplace.test.mjs
@@ -180,7 +180,7 @@ test("Codex MCP entrypoint forwards only native OpenViking tools", () => {
test("canonical MCP tool list matches server registrations", () => {
const source = readFileSync(mcpEndpointPath, "utf-8");
const registered = [
- ...source.matchAll(/@mcp\.tool\((?:name="([a-z_]+)")?\)\s*\nasync def ([a-z_]+)\(/g),
- ].map((match) => match[1] || match[2]);
+ ...source.matchAll(/@mcp\.tool\(([^)]*)\)\s*\nasync def ([a-z_]+)\(/g),
+ ].map((match) => match[1].match(/(?:^|,\s*)name="([a-z_]+)"/)?.[1] || match[2]);
assert.deepEqual(registered, REAL_MCP_TOOLS);
});
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index 2d306aa3f..d89068e2a 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -16,15 +16,23 @@ are extracted from HTTP request scope and propagated via contextvars.
from __future__ import annotations
+import base64
import contextvars
import os
from contextlib import asynccontextmanager
from datetime import datetime, timezone
+from pathlib import PurePosixPath
from typing import Any, Dict, List, Literal, Optional, Union
from urllib.parse import quote
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
+from mcp.types import (
+ AudioContent,
+ ContentBlock,
+ ImageContent,
+ TextContent,
+)
from pydantic import BaseModel, Field
from starlette.requests import Request
from starlette.responses import JSONResponse
@@ -325,8 +333,7 @@ async def search(
)
if other_peer_penalty is not None and other_peer_penalties:
raise InvalidArgumentError(
- "other_peer_penalty cannot be combined with other_peer_penalties "
- "in mode='context'"
+ "other_peer_penalty cannot be combined with other_peer_penalties in mode='context'"
)
# Resolve exclusions with the same strictness as the REST search router,
# so alias URIs match the canonical URIs they are compared against.
@@ -430,9 +437,85 @@ async def _format_search_result(result, *, service, ctx, read_content: bool = Fa
# -- read ------------------------------------------------------------------
-async def read(uris: str | list[str]) -> str:
- """Read full content from one or more viking:// file URIs. Pass a single URI string or a list for batch reads. For directory listing, use the list tool instead."""
+_MCP_IMAGE_EXTENSIONS = {".gif", ".jpeg", ".jpg", ".png", ".webp"}
+_MCP_AUDIO_EXTENSIONS = {".flac", ".m4a", ".mp3", ".oga", ".ogg", ".wav"}
+_MCP_VIDEO_EXTENSIONS = {".avi", ".m4v", ".mkv", ".mov", ".mp4", ".webm"}
+# Common clients cap an inline result at 5 MiB base64, or 3.75 MiB raw.
+# Apply the same limit to one file and to the aggregate media in one tool call.
+_MCP_MEDIA_MAX_BYTES = 3_932_160
+
+
+def _mcp_uri_suffix(uri: str) -> str:
+ """Lowercased file extension of a URI, ignoring any query or fragment."""
+ path = uri.split("#", 1)[0].split("?", 1)[0]
+ return PurePosixPath(path).suffix.lower()
+
+
+def _is_mcp_image_uri(uri: str) -> bool:
+ return _mcp_uri_suffix(uri) in _MCP_IMAGE_EXTENSIONS
+
+
+def _is_mcp_audio_uri(uri: str) -> bool:
+ return _mcp_uri_suffix(uri) in _MCP_AUDIO_EXTENSIONS
+
+
+def _is_mcp_video_uri(uri: str) -> bool:
+ return _mcp_uri_suffix(uri) in _MCP_VIDEO_EXTENSIONS
+
+
+def _sniff_mcp_image_mime_type(data: bytes) -> Optional[str]:
+ """Recognize the raster formats shared by common MCP coding clients."""
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
+ return "image/png"
+ if data.startswith(b"\xff\xd8\xff"):
+ return "image/jpeg"
+ if data.startswith((b"GIF87a", b"GIF89a")):
+ return "image/gif"
+ if len(data) >= 12 and data.startswith(b"RIFF") and data[8:12] == b"WEBP":
+ return "image/webp"
+ return None
+
+
+def _mcp_image_content(data: bytes, mime_type: str) -> ImageContent:
+ encoded = base64.b64encode(data).decode("ascii")
+ return ImageContent(type="image", data=encoded, mimeType=mime_type)
+
+
+def _sniff_mcp_audio_mime_type(data: bytes, uri: str) -> Optional[str]:
+ """Recognize audio formats represented by MCP AudioContent."""
+ suffix = _mcp_uri_suffix(uri)
+ if data.startswith(b"RIFF") and len(data) >= 12 and data[8:12] == b"WAVE":
+ return "audio/wav"
+ if data.startswith(b"fLaC"):
+ return "audio/flac"
+ if data.startswith(b"OggS") and suffix in {".oga", ".ogg"}:
+ return "audio/ogg"
+ if data.startswith(b"ID3") or (len(data) >= 2 and data[0] == 0xFF and data[1] & 0xE0 == 0xE0):
+ return "audio/mpeg"
+ if len(data) >= 12 and data[4:8] == b"ftyp" and suffix == ".m4a":
+ return "audio/mp4"
+ return None
+
+
+def _mcp_audio_content(data: bytes, mime_type: str) -> AudioContent:
+ encoded = base64.b64encode(data).decode("ascii")
+ return AudioContent(type="audio", data=encoded, mimeType=mime_type)
+
+
+def _mcp_media_download_hint(uri: str) -> str:
+ """Return actionable fallbacks when media cannot be inlined."""
+ path = uri.split("#", 1)[0].split("?", 1)[0]
+ filename = PurePosixPath(path).name or "download"
+ encoded_uri = quote(uri, safe="")
+ return (
+ f'Use `ov get "{uri}" "./{filename}"` or GET '
+ f"`/api/v1/content/download?uri={encoded_uri}` to fetch the original file."
+ )
+
+
[email protected](structured_output=False)
+async def read(uris: str | list[str]) -> str | list[ContentBlock]:
+ """Read one or more viking:// file URIs. Raster images and supported audio return native MCP content blocks. For directory listing, use the list tool instead."""
import asyncio
service = get_service()
@@ -440,19 +523,119 @@ async def read(uris: str | list[str]) -> str:
uri_list = uris if isinstance(uris, list) else [uris]
semaphore = asyncio.Semaphore(10)
- async def _read_one(uri: str) -> str:
+ async def _preflight_one(uri: str) -> tuple[str, Optional[int], Optional[str]]:
+ """Resolve a URI and stat media before any binary bytes are loaded."""
+ try:
+ resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)
+ is_image = _is_mcp_image_uri(resolved_uri)
+ is_audio = _is_mcp_audio_uri(resolved_uri)
+ is_video = _is_mcp_video_uri(resolved_uri)
+ if not (is_image or is_audio or is_video):
+ return resolved_uri, None, None
+
+ async with semaphore:
+ stat = await service.fs.stat(resolved_uri, ctx=ctx)
+ if stat.get("isDir"):
+ 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.",
+ )
+ if is_video:
+ return (
+ resolved_uri,
+ None,
+ f"Cannot render {uri}: MCP has no standard VideoContent block. "
+ f"{_mcp_media_download_hint(uri)}",
+ )
+
+ size = stat.get("size") if stat else None
+ if isinstance(size, bool) or not isinstance(size, int) or size < 0:
+ return (
+ resolved_uri,
+ None,
+ 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)
+
+ preflight = await asyncio.gather(*[_preflight_one(uri) for uri in uri_list])
+ checked: list[tuple[str, Optional[int], Optional[str]]] = []
+ 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 = (
+ 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 = (
+ 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)}"
+ )
+ else:
+ media_total += size
+ checked.append((resolved_uri, size, error))
+
+ async def _read_one(
+ uri: str, prepared: tuple[str, Optional[int], Optional[str]]
+ ) -> str | ContentBlock:
async with semaphore:
try:
- resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)
+ resolved_uri, declared_size, error = prepared
+ if error is not None:
+ return error
+ is_image = _is_mcp_image_uri(resolved_uri)
+ is_audio = _is_mcp_audio_uri(resolved_uri)
+ 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 (
+ f"Cannot render {uri}: file changed after its size was checked. "
+ "Retry the read."
+ )
+ mime_type = (
+ _sniff_mcp_image_mime_type(data)
+ if is_image
+ else _sniff_mcp_audio_mime_type(data, resolved_uri)
+ )
+ if mime_type is None:
+ return (
+ f"Cannot render {uri}: its bytes do not match a supported media "
+ f"format. {_mcp_media_download_hint(uri)}"
+ )
+ if is_image:
+ return _mcp_image_content(data, mime_type)
+ return _mcp_audio_content(data, mime_type)
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])
+ result = await _read_one(uri_list[0], checked[0])
+ if isinstance(result, str):
+ return result
+ return [TextContent(type="text", text=f"Source: {uri_list[0]}"), result]
+
+ results = await asyncio.gather(
+ *[_read_one(uri, prepared) for uri, prepared in zip(uri_list, checked, strict=True)]
+ )
+ if any(not isinstance(result, str) for result in results):
+ blocks: list[ContentBlock] = []
+ for uri, result in zip(uri_list, results, strict=True):
+ blocks.append(TextContent(type="text", text=f"=== {uri} ==="))
+ if isinstance(result, str):
+ blocks.append(TextContent(type="text", text=result))
+ else:
+ blocks.append(result)
+ return blocks
- results = await asyncio.gather(*[_read_one(u) for u in uri_list])
parts = []
for uri, text in zip(uri_list, results, strict=True):
parts.append(f"=== {uri} ===\n{text}")
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index 5b03c2545..7361dda45 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -7,6 +7,7 @@ Tests the tool functions directly by setting up the identity contextvar
and service dependency, avoiding MCP protocol complexity.
"""
+import base64
import re
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -14,6 +15,7 @@ from unittest.mock import AsyncMock
import httpx
import pytest
from fastapi import FastAPI
+from mcp.types import AudioContent, ImageContent, TextContent
from starlette.routing import Route
import openviking.server.mcp_endpoint as mcp_endpoint
@@ -429,9 +431,7 @@ async def test_search_context_mode_returns_assembled_context(service, monkeypatc
assert params.max_tokens == 800
assert params.detail == {"events": "overview"}
assert params.dedup_turns == 5
- assert params.exclude_uris == [
- "viking://user/test_user/memories/events/old.md"
- ]
+ assert params.exclude_uris == ["viking://user/test_user/memories/events/old.md"]
assert params.peer_scope == "actor"
assert params.other_peer_penalty == {"events": 0.2}
assert params.rewrite is True
@@ -624,6 +624,271 @@ async def test_read_delegates_to_visible_read(monkeypatch):
)
+ ("uri", "image_bytes", "mime_type"),
+ [
+ ("viking://resources/result.png", b"\x89PNG\r\n\x1a\nimage", "image/png"),
+ ("viking://resources/result.jpg", b"\xff\xd8\xffimage", "image/jpeg"),
+ ("viking://resources/result.gif", b"GIF89aimage", "image/gif"),
+ ("viking://resources/result.webp", b"RIFF\x00\x00\x00\x00WEBPimage", "image/webp"),
+ ],
+)
+async def test_read_image_returns_native_mcp_content(monkeypatch, uri, image_bytes, mime_type):
+ read_file_bytes = AsyncMock(return_value=image_bytes)
+ read_visible = AsyncMock()
+ stat = AsyncMock(return_value={"size": len(image_bytes), "isDir": False})
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(
+ read_file_bytes=read_file_bytes,
+ read_visible=read_visible,
+ stat=stat,
+ )
+ ),
+ )
+ result = await mcp_endpoint.mcp.call_tool("read", {"uris": uri})
+
+ assert isinstance(result, list)
+ assert isinstance(result[0], TextContent)
+ assert result[0].text == f"Source: {uri}"
+ assert isinstance(result[1], ImageContent)
+ assert result[1].mimeType == mime_type
+ assert base64.b64decode(result[1].data) == image_bytes
+ read_file_bytes.assert_awaited_once_with(uri, ctx=DEFAULT_CTX)
+ read_visible.assert_not_awaited()
+
+
+async def test_read_mixed_batch_preserves_source_order(monkeypatch):
+ image_bytes = b"\xff\xd8\xffimage"
+ read_visible = AsyncMock(return_value="notes")
+ read_file_bytes = AsyncMock(return_value=image_bytes)
+ stat = AsyncMock(return_value={"size": len(image_bytes), "isDir": False})
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(
+ read_file_bytes=read_file_bytes,
+ read_visible=read_visible,
+ stat=stat,
+ )
+ ),
+ )
+ text_uri = "viking://resources/notes.md"
+ image_uri = "viking://resources/chart.jpg"
+
+ result = await mcp_endpoint.mcp.call_tool("read", {"uris": [text_uri, image_uri]})
+
+ assert isinstance(result, list)
+ assert [block.type for block in result] == ["text", "text", "text", "image"]
+ assert result[0].text == f"=== {text_uri} ==="
+ assert result[1].text == "notes"
+ assert result[2].text == f"=== {image_uri} ==="
+ assert result[3].mimeType == "image/jpeg"
+
+
+ ("uri", "audio_bytes", "mime_type"),
+ [
+ ("viking://resources/clip.wav", b"RIFF\x00\x00\x00\x00WAVEaudio", "audio/wav"),
+ ("viking://resources/clip.mp3", b"ID3audio", "audio/mpeg"),
+ ("viking://resources/clip.flac", b"fLaCaudio", "audio/flac"),
+ ("viking://resources/clip.ogg", b"OggSaudio", "audio/ogg"),
+ ("viking://resources/clip.m4a", b"\x00\x00\x00\x18ftypM4A audio", "audio/mp4"),
+ # suffix sniffing must ignore a query string, like the extension gate does
+ ("viking://resources/clip.ogg?v=2", b"OggSaudio", "audio/ogg"),
+ ],
+)
+async def test_read_audio_returns_native_mcp_content(monkeypatch, uri, audio_bytes, mime_type):
+ read_file_bytes = AsyncMock(return_value=audio_bytes)
+ stat = AsyncMock(return_value={"size": len(audio_bytes), "isDir": False})
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(
+ read_file_bytes=read_file_bytes,
+ read_visible=AsyncMock(),
+ stat=stat,
+ )
+ ),
+ )
+
+ result = await mcp_endpoint.mcp.call_tool("read", {"uris": uri})
+
+ assert isinstance(result, list)
+ assert isinstance(result[0], TextContent)
+ assert result[0].text == f"Source: {uri}"
+ assert isinstance(result[1], AudioContent)
+ assert result[1].mimeType == mime_type
+ assert base64.b64decode(result[1].data) == audio_bytes
+
+
+async def test_read_video_returns_unsupported_hint(monkeypatch):
+ stat = AsyncMock(return_value={"size": 1024, "isDir": False})
+ read_visible = AsyncMock()
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(
+ read_file_bytes=AsyncMock(),
+ read_visible=read_visible,
+ stat=stat,
+ )
+ ),
+ )
+
+ result = await read("viking://resources/demo.mp4")
+
+ assert "no standard VideoContent" in result
+ assert 'ov get "viking://resources/demo.mp4" "./demo.mp4"' in result
+ stat.assert_awaited_once_with("viking://resources/demo.mp4", ctx=DEFAULT_CTX)
+ read_visible.assert_not_awaited()
+
+
+async def test_read_video_nonexistent_uri_preserves_not_found(monkeypatch):
+ stat = AsyncMock(side_effect=NotFoundError("viking://resources/missing.mp4", "file"))
+ read_visible = AsyncMock()
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(
+ read_file_bytes=AsyncMock(),
+ read_visible=read_visible,
+ stat=stat,
+ )
+ ),
+ )
+
+ result = await read("viking://resources/missing.mp4")
+
+ assert "not found" in result.lower()
+ assert "VideoContent" not in result
+ stat.assert_awaited_once_with("viking://resources/missing.mp4", ctx=DEFAULT_CTX)
+ read_visible.assert_not_awaited()
+
+
+async def test_read_video_directory_uri_preserves_directory_hint(monkeypatch):
+ stat = AsyncMock(return_value={"size": 0, "isDir": True})
+ read_visible = AsyncMock()
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(
+ read_file_bytes=AsyncMock(),
+ read_visible=read_visible,
+ stat=stat,
+ )
+ ),
+ )
+
+ result = await read("viking://resources/archive.mp4")
+
+ assert "URI points to a directory" in result
+ assert "VideoContent" not in result
+ stat.assert_awaited_once_with("viking://resources/archive.mp4", ctx=DEFAULT_CTX)
+ read_visible.assert_not_awaited()
+
+
+async def test_read_rejects_spoofed_image_extension(monkeypatch):
+ read_file_bytes = AsyncMock(return_value=b"not an image")
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(
+ read_file_bytes=read_file_bytes,
+ read_visible=AsyncMock(),
+ stat=AsyncMock(return_value={"size": 12, "isDir": False}),
+ )
+ ),
+ )
+
+ result = await read("viking://resources/not-really.png")
+
+ assert "bytes do not match" in result
+
+
+async def test_read_rejects_images_too_large_for_common_clients(monkeypatch):
+ read_file_bytes = AsyncMock()
+ oversized = mcp_endpoint._MCP_MEDIA_MAX_BYTES + 1
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(
+ read_file_bytes=read_file_bytes,
+ read_visible=AsyncMock(),
+ stat=AsyncMock(return_value={"size": oversized, "isDir": False}),
+ )
+ ),
+ )
+
+ result = await read("viking://resources/huge.png")
+
+ assert "too large to inline" in result
+ assert 'ov get "viking://resources/huge.png" "./huge.png"' in result
+ assert "/api/v1/content/download?uri=viking%3A%2F%2Fresources%2Fhuge.png" in result
+ read_file_bytes.assert_not_awaited()
+
+
+async def test_read_rejects_media_batch_over_aggregate_limit_before_read(monkeypatch):
+ first_uri = "viking://resources/first.png"
+ second_uri = "viking://resources/second.png"
+ declared_size = mcp_endpoint._MCP_MEDIA_MAX_BYTES // 2 + 1
+ read_file_bytes = AsyncMock(return_value=b"\x89PNG\r\n\x1a\n")
+ stat = AsyncMock(return_value={"size": declared_size, "isDir": False})
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(
+ read_file_bytes=read_file_bytes,
+ read_visible=AsyncMock(),
+ stat=stat,
+ )
+ ),
+ )
+
+ result = await mcp_endpoint.mcp.call_tool("read", {"uris": [first_uri, second_uri]})
+
+ assert isinstance(result, list)
+ assert "combined media size" in result[3].text
+ assert f'ov get "{second_uri}" "./second.png"' in result[3].text
+ read_file_bytes.assert_awaited_once_with(first_uri, ctx=DEFAULT_CTX)
+
+
+async def test_read_svg_remains_text(monkeypatch):
+ read_visible = AsyncMock(return_value="<svg></svg>")
+ read_file_bytes = AsyncMock()
+ monkeypatch.setattr(
+ mcp_endpoint,
+ "get_service",
+ lambda: SimpleNamespace(
+ fs=SimpleNamespace(
+ read_file_bytes=read_file_bytes,
+ read_visible=read_visible,
+ )
+ ),
+ )
+ uri = "viking://resources/diagram.svg"
+
+ assert await read(uri) == "<svg></svg>"
+ read_visible.assert_awaited_once_with(uri, ctx=DEFAULT_CTX)
+ read_file_bytes.assert_not_awaited()
+
+
+async def test_read_tool_has_no_structured_output_schema():
+ tools = {tool.name: tool for tool in await mcp_endpoint.mcp.list_tools()}
+
+ assert tools["read"].outputSchema is None
+
+
# ---------------------------------------------------------------------------
# list tool
# ---------------------------------------------------------------------------