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
feat(mcp): add write/edit/tree tools for viking:// as agent working directory (#3936)
Zayn Jarvis4920297ccc9f
diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex 297d9ea90..977d5e95a 100644--- a/docs/en/guides/06-mcp-integration.md+++ b/docs/en/guides/06-mcp-integration.md@@ -129,7 +129,7 @@ If you already have HTTPS configured, just connect to `https://your-server.com/m## Available MCP Tools-Once connected, OpenViking exposes 13 tools:+Once connected, OpenViking exposes 16 tools:| Tool | Description | Key Parameters ||------|-------------|----------------|@@ -138,7 +138,10 @@ Once connected, OpenViking exposes 13 tools:| `recall` | Type-quota recall assembled server-side into flat `<memory>` blocks that always carry their URI | `query`, `quotas` (optional), `max_chars`, `min_score`, `peer_scope`, `other_peer_penalty` (optional), `session_id` (optional), `detail` (optional), `max_tokens` (optional), `rewrite` (optional) || `read` | Read one or more `viking://` URIs | `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}`) |+| `write` | Write text to a `viking://` file (create/overwrite/append). Parent directories are created automatically; use `read` first to see current content before overwriting, and prefer `edit` for changing part of an existing file | `uri`, `content`, `mode` (optional: `replace` default — creates the file if missing, `append`, `create` — fail if it exists), `wait` (optional, block until re-indexed), `timeout` (optional) |+| `edit` | Replace an exact string with new text in an existing `viking://` file — for targeted changes instead of a full rewrite. The file is left unchanged if `old_string` is not found, or matches multiple times while `replace_all` is false | `uri`, `old_string`, `new_string`, `replace_all` (optional), `wait` (optional, block until re-indexed), `timeout` (optional) || `add_resource` | Add a local file or URL as a resource (local files trigger a progressive upload flow) | `path`, `temp_file_id` (optional), `description` (optional), `watch_interval` (optional, minutes — auto-refresh cadence for remote URLs), `processing_mode` (optional: `semantic_and_vectors` default, or `vectors_only` to skip VLM semantic understanding and only vectorize current files), `to` (optional, target `viking://resources/...` URI; if omitted when `watch_interval > 0`, the watch auto-binds to the resource's created URI), `args` (optional parser-specific options, including `{"parse_mode":"no_split"}` to parse each source document into one Markdown body, `{"feishu_access_token":"u-..."}` for one-time Feishu user-token imports, or `{"feishu_access_token":"u-...","feishu_refresh_token":"r-..."}` for Feishu user-token watches) || `list_watches` | List watch tasks (auto-refresh subscriptions) visible to the current agent. Each entry shows target URI, refresh interval (minutes), active/paused status, and next scheduled execution time | none || `cancel_watch` | Cancel (delete) a watch task by its target URI. To change the cadence or pause temporarily, cancel and re-add with a new `watch_interval` | `to_uri` (must match the watch task's `to` value, e.g. `viking://resources/...`) |@@ -147,6 +150,12 @@ Once connected, OpenViking exposes 13 tools:| `forget` | Delete any `viking://` URI (use `search` to find it first; pass `recursive=true` to delete a directory) | `uri`, `recursive` (optional) || `health` | Check OpenViking service health | none |+For MCP tools, `viking://user` is the authenticated user's workspace. For example,+`viking://user/notes/todo.md` resolves to+`viking://user/<current-user>/notes/todo.md`, regardless of the file name or+extension. Canonical URIs containing that exact current user id are also accepted;+MCP does not use this shorthand for cross-user access.+> **Note**: MCP exposes the minimum closure for watch management (`list_watches` + `cancel_watch`). Pause / resume / trigger and the unified `update` verb are intentionally not exposed here — use the REST `/api/v1/watches/*` endpoints or the `ov task watch` CLI for those operations.> Feishu/Lark imports without `args.feishu_access_token` keep the existing app/tenant-token behavior and can be watched. Feishu/Lark one-time user-token imports pass only `args.feishu_access_token`; Feishu/Lark user-token watches must also pass `args.feishu_refresh_token` and require the same Feishu app credentials configured on the OpenViking server.diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex 055d3e99a..eeecb6673 100644--- a/docs/zh/guides/06-mcp-integration.md+++ b/docs/zh/guides/06-mcp-integration.md@@ -121,7 +121,7 @@ claude mcp add --transport http openviking \## 可用的 MCP 工具-连接后,OpenViking MCP 端点暴露 13 个工具:+连接后,OpenViking MCP 端点暴露 16 个工具:| 工具 | 说明 | 主要参数 ||------|------|----------|@@ -130,7 +130,10 @@ claude mcp add --transport http openviking \| `recall` | 按记忆类别配额召回,服务端组装为带 URI 的扁平 `<memory>` 块 | `query`, `quotas`(可选), `max_chars`, `min_score`, `peer_scope`, `other_peer_penalty`(可选), `session_id`(可选), `detail`(可选), `max_tokens`(可选), `rewrite`(可选) || `read` | 读取一个或多个 `viking://` URI 的内容 | `uris`(单个字符串或数组) || `list` | 列出 `viking://` 目录下的条目 | `uri`, `recursive`(可选) |+| `tree` | 以缩进形式展示 `viking://` URI 下的递归目录树——当需要全面了解文件树结构时使用(单层列表用 `list`,按文件名查找用 `glob`) | `uri`(可选), `level_limit`(默认 3), `node_limit`(默认 1000), `include_abstract`(可选——同时展示每个文件的摘要) || `remember` | 存储消息到长期记忆(触发记忆提取) | `messages`(`{role, content}` 列表) |+| `write` | 向 `viking://` 文件写入文本(创建/覆盖/追加)。自动创建缺失的父目录;覆盖前请先用 `read` 查看当前内容;只改文件局部时优先用 `edit` | `uri`, `content`, `mode`(可选:默认 `replace` — 文件不存在时自动创建,`append` 追加,`create` — 已存在则失败), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选) |+| `edit` | 在已有 `viking://` 文件中把精确字符串替换为新文本——用于局部修改,避免整文件重写。若 `old_string` 找不到、或匹配多处且 `replace_all` 为 false,则编辑失败且文件保持不变 | `uri`, `old_string`, `new_string`, `replace_all`(可选), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选) || `add_resource` | 添加本地文件或 URL 作为资源(本地文件触发渐进式上传流) | `path`, `temp_file_id`(可选), `description`(可选), `watch_interval`(可选,分钟数 — 远程 URL 的自动刷新周期), `processing_mode`(可选:默认 `semantic_and_vectors`;传 `vectors_only` 时跳过 VLM 语义理解,只向量化当前文件), `to`(可选,目标 `viking://resources/...` URI;`watch_interval > 0` 时若省略 `to`,watch 将自动绑定到本次 add 创建的资源 URI), `args`(可选,特定 parser 参数,包括 `{"parse_mode":"no_split"}` 用于正常解析但每个源文档只生成一个 Markdown 正文、飞书一次性用户 token 导入使用 `{"feishu_access_token":"u-..."}`,或飞书用户 token watch 使用 `{"feishu_access_token":"u-...","feishu_refresh_token":"r-..."}`) || `list_watches` | 列出当前 Agent 可见的 watch 任务(自动刷新订阅),每行显示目标 URI、刷新间隔(分钟)、active/paused 状态以及下一次调度时间 | 无 || `cancel_watch` | 按目标 URI 取消(删除)watch 任务。若需调整刷新周期或临时暂停,请取消后使用新的 `watch_interval` 重新添加 | `to_uri`(必须匹配 watch 任务的 `to` 值,例如 `viking://resources/...`) |@@ -139,6 +142,11 @@ claude mcp add --transport http openviking \| `forget` | 删除任意 `viking://` URI(先用 `search` 查找;删除目录需 `recursive=true`) | `uri`, `recursive`(可选) || `health` | 检查 OpenViking 服务健康状态 | 无 |+在 MCP 工具中,`viking://user` 表示当前认证用户的工作区。例如,+`viking://user/notes/todo.md` 会解析成+`viking://user/<当前用户>/notes/todo.md`,不依赖文件名或扩展名判断。工具返回的、+包含当前用户 ID 的 canonical URI 也可以直接使用;这套简写不用于跨用户访问。+> **注**:MCP 仅暴露 watch 管理的最小闭包(`list_watches` + `cancel_watch`)。pause / resume / trigger 和统一的 `update` 动作刻意不在此处暴露,请通过 REST `/api/v1/watches/*` 接口或 `ov task watch` CLI 使用上述操作。> 未传 `args.feishu_access_token` 的飞书/Lark 导入保持现有应用/tenant token 行为,也支持 watch。飞书/Lark 一次性用户 token 导入只传 `args.feishu_access_token`;飞书/Lark 用户 token watch 还必须传 `args.feishu_refresh_token`,并要求 OpenViking 服务端配置同一个飞书应用凭证。diff --git a/examples/codex-memory-plugin/scripts/marketplace.test.mjs b/examples/codex-memory-plugin/scripts/marketplace.test.mjsindex 41625fdbc..ed2f95a3e 100644--- a/examples/codex-memory-plugin/scripts/marketplace.test.mjs+++ b/examples/codex-memory-plugin/scripts/marketplace.test.mjs@@ -25,8 +25,8 @@ const mcpEndpointPath = join(repoRoot, "openviking", "server", "mcp_endpoint.py"const PLUGIN_NAME = "openviking-memory";const REAL_MCP_TOOLS = [- "find", "search", "recall", "read", "list", "remember", "add_resource",- "list_watches", "cancel_watch", "grep", "glob", "forget", "health",+ "find", "search", "recall", "read", "list", "tree", "remember", "write", "edit",+ "add_resource", "list_watches", "cancel_watch", "grep", "glob", "forget", "health",];const LEGACY_TOOL_NAMES = ["openviking_recall", "openviking_store", "openviking_forget", "openviking_health"];diff --git a/openviking/server/app.py b/openviking/server/app.pyindex 381925c9d..895011855 100644--- a/openviking/server/app.py+++ b/openviking/server/app.py@@ -779,8 +779,9 @@ def create_app(else:logger.info("Web Studio bundle not found at %s; skipping /studio mount", _studio_dir)- # MCP endpoint — serves 5 tools (search, read, store, forget, health)- # via streamable HTTP for Claude Code and other MCP clients.+ # MCP endpoint — serves 16 tools (find, search, recall, read, write, edit,+ # list, tree, remember, add_resource, list_watches, cancel_watch, grep,+ # glob, forget, health) via streamable HTTP for MCP clients.from starlette.routing import Match, Routefrom openviking.server.mcp_endpoint import create_mcp_appdiff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 63593c249..9dc39a80f 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -3,7 +3,7 @@"""MCP (Model Context Protocol) endpoint for OpenViking server.Exposes tools to Claude Code (or any MCP client) via streamable HTTP:- find, search, read, list, remember, add_resource, grep, glob, forget, health+ find, search, read, write, edit, list, tree, remember, add_resource, grep, glob, forget, healthMounted on the FastAPI app at /mcp. The MCP session manager lifecycle istied to the FastAPI app lifespan (not a sub-app lifespan) so the task group@@ -29,6 +29,7 @@ from starlette.requests import Requestfrom starlette.responses import JSONResponsefrom starlette.types import ASGIApp, Receive, Scope, Send+from openviking.core.namespace import canonical_user_root, canonicalize_uri, uri_partsfrom openviking.parse.mode import ParseMode, normalize_parse_modefrom openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingModefrom openviking.retrieve.context_assembler import assemble_context@@ -47,6 +48,7 @@ from openviking.telemetry.span_models import update_root_span_identityfrom openviking.utils.search_filters import SearchContextTypeInput, merge_search_filterfrom openviking_cli.exceptions import (InvalidArgumentError,+ NotFoundError,PermissionDeniedError,UnauthenticatedError,)@@ -79,6 +81,25 @@ def _get_ctx() -> RequestContext:return ctx+def _resolve_mcp_workspace_uri(uri: str, ctx: RequestContext) -> str:+ """Resolve ``viking://user/...`` as the current user's MCP workspace.++ Generic namespace parsing must preserve canonical cross-user URIs, so it+ cannot infer whether the first segment after ``user`` is a user id or a+ file/directory name. MCP has a narrower contract: its filesystem tools act+ on the authenticated user's workspace. An exact current-user id is already+ canonical; every other suffix is relative to that user's root.+ """+ parts = uri_parts(uri)+ if parts[:1] != ["user"]:+ return uri+ suffix = parts[1:]+ if suffix[:1] == [ctx.user.user_id]:+ return canonicalize_uri(uri, ctx)+ root = canonical_user_root(ctx)+ return root if not suffix else f"{root}/{'/'.join(suffix)}"++def _scope_to_origin(scope: Scope) -> Optional[str]:"""Derive the public-facing origin (scheme://host) from an ASGI scope.@@ -246,9 +267,12 @@ async def find() -> str:"""Fast semantic retrieval without session context. Returns ranked memories, resources, and skills with URI, abstract, and score."""service = get_service()+ ctx = _get_ctx()+ if target_uri:+ target_uri = _resolve_mcp_workspace_uri(target_uri, ctx)result = await service.search.find(query=query,- ctx=_get_ctx(),+ ctx=ctx,target_uri=target_uri,limit=limit,score_threshold=min_score,@@ -271,6 +295,8 @@ async def search("""Deep semantic retrieval with optional session context and intent analysis. Returns ranked memories, resources, and skills with URI, abstract, and score."""service = get_service()ctx = _get_ctx()+ if target_uri:+ target_uri = _resolve_mcp_workspace_uri(target_uri, ctx)session = None# Intent off: skip session.load — SearchService will not scan session either.if session_id and service.search.is_intent_enabled():@@ -373,7 +399,8 @@ async def read(uris: str | list[str]) -> str:async def _read_one(uri: str) -> str:async with semaphore:try:- body = await service.fs.read_visible(uri, ctx=ctx)+ resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)+ body = await service.fs.read_visible(resolved_uri, ctx=ctx)if isinstance(body, str) and body.strip():return bodyexcept Exception:@@ -398,8 +425,9 @@ async def ls(uri: str, recursive: bool = False) -> str:"""List files and subdirectories under a viking:// directory URI. Use recursive=true for deep listing."""service = get_service()ctx = _get_ctx()+ resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)- entries = await service.fs.ls(uri, ctx=ctx, recursive=recursive, output="original")+ entries = await service.fs.ls(resolved_uri, ctx=ctx, recursive=recursive, output="original")if not entries:return f"(no entries under {uri})"@@ -415,6 +443,56 @@ async def ls(uri: str, recursive: bool = False) -> str:return "\n".join(lines)+# -- tree ------------------------------------------------------------------+++async def tree(+ uri: str = "viking://",+ level_limit: int = 3,+ node_limit: int = 1000,+ include_abstract: bool = False,+) -> str:+ """Show the recursive directory tree under a viking:// URI, indented by depth, so you can understand the whole layout at a glance. Use this when you need a full picture of the file tree; use list for a single directory level, glob for filename patterns, and grep for content. level_limit caps the depth (default 3); node_limit caps the total entries. Set include_abstract=true to also see each file's summary (slower, but useful for orientation in unfamiliar directories)."""+ service = get_service()+ ctx = _get_ctx()+ resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)+ output = "agent" if include_abstract else "original"+ try:+ entries = await service.fs.tree(+ resolved_uri,+ ctx=ctx,+ output=output,+ node_limit=node_limit,+ level_limit=level_limit,+ )+ except NotFoundError:+ entries = []+ if not entries:+ return f"(nothing under {uri})"++ lines = [+ f"Tree of {uri} (depth <= {level_limit}, {len(entries)} entr{'y' if len(entries) == 1 else 'ies'}):"+ ]+ for e in entries:+ rel = (e.get("rel_path") or e.get("name") or "?").strip("/")+ name = rel.rsplit("/", 1)[-1]+ depth = len([part for part in rel.split("/") if part])+ indent = " " * max(0, depth - 1)+ if e.get("isDir"):+ lines.append(f"{indent}{name}/")+ continue+ lines.append(f"{indent}{name} ({e.get('size', 0)} B)")+ abstract = (e.get("abstract") or "").strip().replace("\n", " ")+ if include_abstract and abstract:+ lines.append(f"{indent} - {abstract}")+ if len(entries) >= node_limit:+ lines.append(+ f"(truncated at node_limit={node_limit}; narrow the uri or raise node_limit to see more)"+ )+ return "\n".join(lines)++# -- remember --------------------------------------------------------------@@ -445,6 +523,107 @@ async def remember(messages: list[StoreMessage]) -> str:return f"Stored {len(messages)} message(s) and committed for memory extraction."+# -- write -----------------------------------------------------------------+++async def write(+ uri: str,+ content: str,+ mode: Literal["replace", "append", "create"] = "replace",+ wait: bool = False,+ timeout: Optional[float] = None,+) -> str:+ """Write text to a viking:// file. Use this to save files (notes, profiles, knowledge, state) in OpenViking the same way you would use a working directory. To change part of an existing file, prefer the edit tool over a full rewrite.++ - mode="replace" (default): overwrite the file; creates it and any missing parent directories if needed.+ - mode="create": fail if the file already exists.+ - Any new file (whether created by "replace" or "create") must end in one of: .md .txt .json .yaml .yml .toml .py .js .ts+ - mode="append": append to the end of an existing file; fails if the file does not exist.++ Writable scopes: viking://resources/, viking://user/ (all paths are relative to the authenticated user's root unless the URI already contains that exact user id), viking://agent/. The managed user subtrees skills/, peers/, privacy/ and sessions/ are read-only. After a write, semantic search indexes refresh in the background; pass wait=true to block until search reflects the change."""+ service = get_service()+ ctx = _get_ctx()+ uri = _resolve_mcp_workspace_uri(uri, ctx)++ try:+ result = await service.fs.write(+ uri=uri, content=content, ctx=ctx, mode=mode, wait=wait, timeout=timeout+ )+ except NotFoundError:+ if mode != "replace":+ raise+ # Replace doubles as create-or-overwrite so agents can save a new file+ # without first checking whether it exists; strict creation stays+ # available via mode="create".+ result = await service.fs.write(+ uri=uri, content=content, ctx=ctx, mode="create", wait=wait, timeout=timeout+ )+ written = result.get("written_bytes", 0)+ message = (+ f"Wrote {written} bytes to {result.get('uri', uri)} (mode={result.get('mode', mode)})."+ )+ return message + _indexing_hint(result)+++async def edit(+ uri: str,+ old_string: str,+ new_string: str,+ replace_all: bool = False,+ wait: bool = False,+ timeout: Optional[float] = None,+) -> str:+ """Replace an exact string with new text in an existing viking:// file. Use this for targeted changes instead of rewriting the whole file with the write tool. old_string must match the file's current content exactly, including indentation and newlines; use the read tool first to see it. The edit fails and the file is left unchanged if old_string is not found, or if it matches more than once and replace_all is false (pass more surrounding context to make it unique, or set replace_all=true to replace every occurrence). Pass new_string="" to delete old_string.++ Editing a memory file preserves its metadata; after an edit, search indexes refresh in the background (pass wait=true to block until search reflects the change)."""+ service = get_service()+ ctx = _get_ctx()+ uri = _resolve_mcp_workspace_uri(uri, ctx)++ if not old_string:+ raise InvalidArgumentError("old_string must not be empty")+ try:+ current = await service.fs.read_visible(uri, ctx=ctx)+ except (InvalidArgumentError, PermissionDeniedError, UnauthenticatedError):+ raise+ except Exception as exc:+ raise NotFoundError(uri, "file") from exc+ occurrences = current.count(old_string)+ if occurrences == 0:+ raise InvalidArgumentError(+ f"old_string not found in {uri}. "+ "Re-read the file with the read tool to get its current content."+ )+ if occurrences > 1 and not replace_all:+ raise InvalidArgumentError(+ f"old_string matches {occurrences} locations in {uri}. "+ "Include more surrounding context to make it unique, or set replace_all=true."+ )+ updated = current.replace(old_string, new_string)+ if updated == current:+ return f"No changes: {uri} already matches the requested edit."+ result = await service.fs.write(+ uri=uri, content=updated, ctx=ctx, mode="replace", wait=wait, timeout=timeout+ )+ written = result.get("written_bytes", 0)+ message = f"Edited {result.get('uri', uri)} ({written} bytes written)."+ return message + _indexing_hint(result)+++def _indexing_hint(result: Dict[str, Any]) -> str:+ semantic = result.get("semantic_status")+ vector = result.get("vector_status")+ parts = [f"semantic={semantic}", f"vector={vector}"]+ if result.get("overview_status") is not None:+ parts.append(f"overview={result['overview_status']}")+ hint = f"\nIndexing: {', '.join(parts)}."+ if "queued" in (semantic, vector):+ hint += " Search indexes update in the background; pass wait=true if a follow-up search must see this change immediately."+ return hint++# -- add_resource ----------------------------------------------------------@@ -859,6 +1038,7 @@ async def grep(service = get_service()ctx = _get_ctx()+ resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)patterns = [pattern] if isinstance(pattern, str) else patternsemaphore = asyncio.Semaphore(10)@@ -866,7 +1046,7 @@ async def grep(async with semaphore:try:result = await service.fs.grep(- uri,+ resolved_uri,p,ctx=ctx,case_insensitive=case_insensitive,@@ -906,9 +1086,10 @@ async def glob(pattern: str, uri: str = "viking://", node_limit: int = 100) -> s"""Find viking:// files matching a glob pattern (e.g. **/*.md, *.py). Use this for filename matching; use the search tool for content-based retrieval."""service = get_service()ctx = _get_ctx()+ resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)try:- result = await service.fs.glob(pattern, ctx=ctx, uri=uri, node_limit=node_limit)+ result = await service.fs.glob(pattern, ctx=ctx, uri=resolved_uri, node_limit=node_limit)except Exception as e:return f"Error: {e}"@@ -931,8 +1112,9 @@ async def forget(uri: str, recursive: bool = False) -> str:"""Permanently delete a viking:// URI from OpenViking. Irreversible — confirm with user before calling."""service = get_service()ctx = _get_ctx()- await service.fs.rm(uri, ctx=ctx, recursive=recursive)- return f"Deleted: {uri}"+ resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)+ await service.fs.rm(resolved_uri, ctx=ctx, recursive=recursive)+ return f"Deleted: {resolved_uri}"# -- health ----------------------------------------------------------------@@ -1046,8 +1228,8 @@ async def mcp_lifespan():"""Run the MCP session manager. Call this inside the FastAPI lifespan."""async with mcp.session_manager.run():logger.info(- "MCP endpoint ready (13 tools: find, search, recall, read, list, remember, "- "add_resource, list_watches, cancel_watch, grep, glob, forget, health)"+ "MCP endpoint ready (16 tools: find, search, recall, read, write, edit, list, "+ "tree, remember, add_resource, list_watches, cancel_watch, grep, glob, forget, health)")yielddiff --git a/openviking/storage/content_write.py b/openviking/storage/content_write.pyindex 158d4b0c9..5a74a7406 100644--- a/openviking/storage/content_write.py+++ b/openviking/storage/content_write.py@@ -76,6 +76,10 @@ _BATCH_MAX_FILE_BYTES = 8 * 1024 * 1024_BATCH_MAX_TOTAL_BYTES = 16 * 1024 * 1024_SHA256_PREFIX = "sha256:"+# Subtrees directly under a user root that OpenViking manages itself; only+# memories/, resources/, and plain files may be written under a user root.+_USER_MANAGED_SUBTREES = frozenset({"skills", "peers", "privacy", "sessions"})+class ContentWriteCoordinator:"""Write a file (create or modify) and trigger downstream maintenance."""@@ -962,11 +966,14 @@ class ContentWriteCoordinator:returnif mode == "append":+ # Plain concatenation for resource/skill files: MEMORY_FIELDS is a+ # reserved trailer of memory namespaces only (see content_visibility),+ # so non-memory appends must not round-trip through MemoryFileUtils+ # (which strips trailing newlines and injects a metadata trailer).existing_raw = await self._viking_fs.read_file(uri, ctx=ctx)- mf = MemoryFileUtils.read(existing_raw, uri=uri)- mf.content = mf.content + content- updated_raw = MemoryFileUtils.write(mf)- await self._viking_fs.write_file(uri, updated_raw, ctx=ctx, lease_ref=lease_ref)+ await self._viking_fs.write_file(+ uri, existing_raw + content, ctx=ctx, lease_ref=lease_ref+ )returnawait self._viking_fs.write_file(uri, content, ctx=ctx, lease_ref=lease_ref)@@ -1319,18 +1326,25 @@ class ContentWriteCoordinator:root_uri = parent.urielse:root_uri = VikingURI.build(*parts[: resources_idx + 2])- else:- try:- memories_idx = parts.index("memories")- except ValueError as exc:- raise InvalidArgumentError(- f"write only supports memory or resource files under user scope: {uri}"- ) from exc+ elif "memories" in parts:+ memories_idx = parts.index("memories")if len(parts) <= memories_idx + 1:raise InvalidArgumentError(f"memory write target must be inside a memory type directory: {uri}")root_uri = VikingURI.build(*parts[: memories_idx + 2])+ else:+ # Plain files directly under the user root are allowed (e.g. a+ # persona file at viking://user/<user>/persona.md); the managed+ # subtrees (skills/, peers/, privacy/, sessions/) are not.+ if len(parts) <= 2 or parts[2] in _USER_MANAGED_SUBTREES:+ raise InvalidArgumentError(+ "user-scope writes need a file under memories/, resources/, "+ f"or directly at the user root: {uri}"+ )+ parent = parsed.parent+ if parent is not None:+ root_uri = parent.uristat = await self._safe_stat(root_uri, ctx=ctx, allow_not_found=_allow_not_found)if stat.get("not_found") or not stat.get("isDir"):diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.pyindex 0a7949154..424ddfa2d 100644--- a/tests/server/test_content_write_service.py+++ b/tests/server/test_content_write_service.py@@ -98,6 +98,20 @@ async def test_memory_replace_preserves_metadata(service):assert stored_result.extra_fields == expected_mf.extra_fields+async def test_resource_append_is_plain_concatenation(service):+ """Appending to a non-memory file must not inject a MEMORY_FIELDS trailer+ or strip the existing trailing newline (memory namespaces only)."""+ ctx = RequestContext(user=service.user, role=Role.USER)+ uri = "viking://resources/append_plain/journal.md"++ await service.fs.write(uri, content="line1\n", ctx=ctx, mode="create")+ await service.fs.write(uri, content="line2\n", ctx=ctx, mode="append")++ stored = await service.viking_fs.read_file(uri, ctx=ctx)+ assert stored == "line1\nline2\n"++@pytest.mark.asyncioasync def test_memory_append_preserves_metadata(service):ctx = RequestContext(user=service.user, role=Role.USER)diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex c15c34553..94fe7eefd 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -24,8 +24,10 @@ from openviking.server.mcp_endpoint import (_get_ctx,_IdentityASGIMiddleware,_mcp_ctx,+ _resolve_mcp_workspace_uri,add_resource,cancel_watch,+ edit,forget,glob,grep,@@ -35,9 +37,17 @@ from openviking.server.mcp_endpoint import (recall,remember,search,+ tree,+ write,)from openviking.server.mcp_endpoint import ls as list_tool-from openviking_cli.exceptions import FailedPreconditionError, UnauthenticatedError+from openviking_cli.exceptions import (+ AlreadyExistsError,+ FailedPreconditionError,+ InvalidArgumentError,+ NotFoundError,+ UnauthenticatedError,+)from openviking_cli.session.user_id import UserIdentifierDEFAULT_CTX = RequestContext(@@ -74,6 +84,42 @@ def test_get_ctx_raises_when_unset():_mcp_ctx.reset(token)+ ("uri", "expected"),+ [+ ("viking://user", "viking://user/test_user"),+ ("viking://user/notes.md", "viking://user/test_user/notes.md"),+ (+ "viking://user/project/notes.md",+ "viking://user/test_user/project/notes.md",+ ),+ (+ "viking://user/test_user/project/notes.md",+ "viking://user/test_user/project/notes.md",+ ),+ ("viking://resources/project/notes.md", "viking://resources/project/notes.md"),+ ],+)+def test_resolve_mcp_workspace_uri_is_current_user_relative(uri, expected):+ assert _resolve_mcp_workspace_uri(uri, DEFAULT_CTX) == expected+++def test_resolve_mcp_workspace_uri_supports_dotted_current_user_id():+ ctx = RequestContext(+ user=UserIdentifier.the_default_user("[email protected]"),+ role=Role.USER,+ )++ assert (+ _resolve_mcp_workspace_uri("viking://user/[email protected]/notes/todo.md", ctx)+ == "viking://user/[email protected]/notes/todo.md"+ )+ assert (+ _resolve_mcp_workspace_uri("viking://user/notes/todo.md", ctx)+ == "viking://user/[email protected]/notes/todo.md"+ )++# ---------------------------------------------------------------------------# health tool# ---------------------------------------------------------------------------@@ -198,7 +244,7 @@ async def test_find_tool_calls_lightweight_find(service, monkeypatch):result = await mcp_endpoint.find(query="fast lookup",- target_uri="viking://resources",+ target_uri="viking://user/project",limit=2,min_score=0.2,context_type=["memory", "resource"],@@ -207,7 +253,7 @@ async def test_find_tool_calls_lightweight_find(service, monkeypatch):assert result == "No matching context found."assert captured["query"] == "fast lookup"assert captured["ctx"] == DEFAULT_CTX- assert captured["target_uri"] == "viking://resources"+ assert captured["target_uri"] == "viking://user/test_user/project"assert captured["limit"] == 2assert captured["score_threshold"] == 0.2assert captured["filter"] == {@@ -244,7 +290,7 @@ async def test_search_tool_calls_context_aware_search_with_session(service, monkresult = await search(query="deep lookup",- target_uri="viking://resources",+ target_uri="viking://user/project",session_id="session-1",limit=4,min_score=0.1,@@ -257,7 +303,7 @@ async def test_search_tool_calls_context_aware_search_with_session(service, monkassert captured["session_id"] == "session-1"assert captured["query"] == "deep lookup"assert captured["ctx"] == DEFAULT_CTX- assert captured["target_uri"] == "viking://resources"+ assert captured["target_uri"] == "viking://user/test_user/project"assert captured["session"] == sessionassert captured["limit"] == 4assert captured["score_threshold"] == 0.1@@ -397,15 +443,15 @@ async def test_mcp_middleware_rejects_invalid_actor_peer_header():async def test_read_nonexistent_uri(service):- result = await read("viking://user/default/memories/does_not_exist.md")+ result = await read("viking://user/memories/does_not_exist.md")assert "nothing found" in result.lower()async def test_read_batch(service):result = await read([- "viking://user/default/memories/does_not_exist_1.md",- "viking://user/default/memories/does_not_exist_2.md",+ "viking://user/memories/does_not_exist_1.md",+ "viking://user/memories/does_not_exist_2.md",])assert "===" in result@@ -419,10 +465,12 @@ async def test_read_uses_public_content_projection(monkeypatch):"get_service",lambda: SimpleNamespace(fs=SimpleNamespace(read_visible=read_visible)),)- uri = "viking://user/default/memories/private.md"+ uri = "viking://user/project/private.md"assert await read(uri) == "visible memory"- read_visible.assert_awaited_once_with(uri, ctx=DEFAULT_CTX)+ read_visible.assert_awaited_once_with(+ "viking://user/test_user/project/private.md", ctx=DEFAULT_CTX+ )# ---------------------------------------------------------------------------@@ -438,9 +486,9 @@ async def test_list_root(service):async def test_list_empty_dir(service):ctx = DEFAULT_CTXawait service.viking_fs.mkdir(- "viking://user/default/memories/empty_test", ctx=ctx, exist_ok=True+ "viking://user/test_user/memories/empty_test", ctx=ctx, exist_ok=True)- result = await list_tool("viking://user/default/memories/empty_test")+ result = await list_tool("viking://user/memories/empty_test")assert isinstance(result, str)@@ -860,9 +908,10 @@ async def test_cancel_watch_not_found(service):async def test_forget_by_uri_deletes_memory(service):ctx = DEFAULT_CTX- uri = "viking://user/default/memories/test_forget.md"- await service.viking_fs.mkdir("viking://user/default/memories", ctx=ctx, exist_ok=True)- await service.viking_fs.write(uri, "test data", ctx=ctx)+ uri = "viking://user/memories/test_forget.md"+ canonical_uri = "viking://user/test_user/memories/test_forget.md"+ await service.viking_fs.mkdir("viking://user/test_user/memories", ctx=ctx, exist_ok=True)+ await service.viking_fs.write(canonical_uri, "test data", ctx=ctx)result = await forget(uri=uri)assert "deleted" in result.lower()@@ -902,6 +951,208 @@ async def test_forget_directory_with_recursive_succeeds(service):assert "deleted" in result.lower()+# ---------------------------------------------------------------------------+# write tool+# ---------------------------------------------------------------------------+++async def test_write_creates_new_file_with_replace_default(service):+ uri = "viking://resources/test_write/notes.md"+ result = await write(uri=uri, content="# Notes\nhello world\n")+ assert "notes.md" in result+ assert "Wrote" in result+ body = await service.fs.read(uri, ctx=DEFAULT_CTX)+ assert body == "# Notes\nhello world\n"+++async def test_write_replace_overwrites_existing(service):+ uri = "viking://resources/test_write_replace.md"+ await write(uri=uri, content="v1")+ result = await write(uri=uri, content="v2-content")+ assert "mode=replace" in result+ body = await service.fs.read(uri, ctx=DEFAULT_CTX)+ assert body == "v2-content"+++async def test_write_create_fails_when_file_exists(service):+ uri = "viking://resources/test_write_create_exists.md"+ await write(uri=uri, content="v1")+ with pytest.raises(AlreadyExistsError):+ await write(uri=uri, content="v2", mode="create")+++async def test_write_append_appends_to_existing(service):+ uri = "viking://resources/test_write_append.md"+ await write(uri=uri, content="line1\n")+ await write(uri=uri, content="line2\n", mode="append")+ body = await service.fs.read(uri, ctx=DEFAULT_CTX)+ assert body == "line1\nline2\n"+++async def test_write_append_missing_file_fails(service):+ with pytest.raises(NotFoundError):+ await write(+ uri="viking://resources/test_write_append_missing.md", content="x", mode="append"+ )+++async def test_write_create_rejects_disallowed_extension(service):+ with pytest.raises(InvalidArgumentError):+ await write(uri="viking://resources/test_write_ext.csv", content="a,b\n", mode="create")+++async def test_write_rejects_derived_semantic_file(service):+ with pytest.raises(InvalidArgumentError):+ await write(uri="viking://resources/test_write_derived/.abstract.md", content="x")+++async def test_write_read_tool_roundtrip(service):+ uri = "viking://resources/test_write_roundtrip/profile.md"+ await write(uri=uri, content="name: ada\n")+ assert "name: ada" in await read(uris=uri)+++async def test_edit_replaces_unique_occurrence(service):+ uri = "viking://resources/test_edit.md"+ await write(uri=uri, content="alpha\nbeta\ngamma\n")+ result = await edit(uri=uri, old_string="beta", new_string="BETA")+ assert "Edited" in result+ body = await service.fs.read(uri, ctx=DEFAULT_CTX)+ assert body == "alpha\nBETA\ngamma\n"+++async def test_edit_sequential_edits_compose(service):+ uri = "viking://resources/test_edit_order.md"+ await write(uri=uri, content="foo bar baz\n")+ await edit(uri=uri, old_string="bar", new_string="qux")+ await edit(uri=uri, old_string="foo qux", new_string="hello")+ body = await service.fs.read(uri, ctx=DEFAULT_CTX)+ assert body == "hello baz\n"+++async def test_edit_requires_unique_match(service):+ uri = "viking://resources/test_edit_multi.md"+ await write(uri=uri, content="dup\ndup\n")+ with pytest.raises(InvalidArgumentError, match="matches 2 locations"):+ await edit(uri=uri, old_string="dup", new_string="x")+++async def test_edit_replace_all(service):+ uri = "viking://resources/test_edit_all.md"+ await write(uri=uri, content="dup\ndup\n")+ await edit(uri=uri, old_string="dup", new_string="x", replace_all=True)+ body = await service.fs.read(uri, ctx=DEFAULT_CTX)+ assert body == "x\nx\n"+++async def test_edit_missing_old_string_fails(service):+ uri = "viking://resources/test_edit_missing.md"+ await write(uri=uri, content="alpha\n")+ with pytest.raises(InvalidArgumentError, match="not found"):+ await edit(uri=uri, old_string="zzz", new_string="x")+++async def test_edit_empty_old_string_fails(service):+ uri = "viking://resources/test_edit_empty.md"+ await write(uri=uri, content="alpha\n")+ with pytest.raises(InvalidArgumentError, match="must not be empty"):+ await edit(uri=uri, old_string="", new_string="x")+++async def test_edit_on_missing_file_fails(service):+ with pytest.raises(NotFoundError):+ await edit(uri="viking://resources/test_edit_ghost.md", old_string="a", new_string="b")+++async def test_edit_noop_reports_no_changes(service):+ uri = "viking://resources/test_edit_noop.md"+ await write(uri=uri, content="same\n")+ result = await edit(uri=uri, old_string="same", new_string="same")+ assert "No changes" in result+++async def test_edit_memory_file_preserves_metadata(service):+ uri = "viking://user/memories/preferences/test_edit_memory.md"+ await write(uri=uri, content="likes: tea\n")+ raw_before = await service.fs.read(uri, ctx=DEFAULT_CTX)+ assert "MEMORY_FIELDS" in raw_before++ await edit(uri=uri, old_string="tea", new_string="coffee")++ raw_after = await service.fs.read(uri, ctx=DEFAULT_CTX)+ assert "MEMORY_FIELDS" in raw_after+ assert "coffee" in raw_after+ visible = await service.fs.read_visible(uri, ctx=DEFAULT_CTX)+ assert visible.strip() == "likes: coffee"+++async def test_write_user_shorthand_uri(service):+ uri = "viking://user/memories/preferences/shorthand_write.md"+ result = await write(uri=uri, content="x")+ assert "shorthand_write.md" in result+ visible = await service.fs.read_visible(uri, ctx=DEFAULT_CTX)+ assert visible.strip() == "x"+++async def test_write_user_root_file_via_shorthand(service):+ # The first relative segment can be any file or directory name; MCP does+ # not guess from a file-extension allowlist.+ result = await write(uri="viking://user/project/zeus-persona.md", content="# Zeus persona\n")+ assert "viking://user/test_user/project/zeus-persona.md" in result+ body = await service.fs.read("viking://user/test_user/project/zeus-persona.md", ctx=DEFAULT_CTX)+ assert body == "# Zeus persona\n"+++async def test_write_plain_file_directly_at_user_root(service):+ # A file with no intermediate directory: the write coordinator anchors its+ # refresh at the user root itself, which is the shape the shorthand exists for.+ result = await write(uri="viking://user/persona.md", content="# Persona\n")+ assert "viking://user/test_user/persona.md" in result+ assert "# Persona" in await read(uris="viking://user/persona.md")+++async def test_write_user_root_subdirectory_file(service):+ uri = "viking://user/test_user/notes/todo.md"+ await write(uri=uri, content="- buy milk\n")+ assert "- buy milk" in await read(uris=uri)+++async def test_edit_user_root_file_via_same_shorthand(service):+ uri = "viking://user/project/editable.md"+ await write(uri=uri, content="before\n")++ result = await edit(uri=uri, old_string="before", new_string="after")++ assert "viking://user/test_user/project/editable.md" in result+ assert "after" in await read(uris=uri)+++async def test_write_user_managed_subtree_rejected(service):+ with pytest.raises(InvalidArgumentError, match="user root"):+ await write(uri="viking://user/test_user/sessions/fake-session.md", content="x")+ with pytest.raises(InvalidArgumentError, match="user root"):+ await write(uri="viking://user/test_user/skills/demo/SKILL.md", content="x")+++async def test_write_tool_schema_is_portable():+ tools = {tool.name: tool for tool in await mcp_endpoint.mcp.list_tools()}+ props = tools["write"].inputSchema["properties"]+ assert props["uri"]["type"] == "string"+ assert props["content"]["type"] == "string"+ assert props["mode"]["enum"] == ["replace", "append", "create"]+ assert {"uri", "content"} <= set(tools["write"].inputSchema.get("required", []))+++async def test_edit_tool_schema_is_portable():+ tools = {tool.name: tool for tool in await mcp_endpoint.mcp.list_tools()}+ props = tools["edit"].inputSchema["properties"]+ assert props["uri"]["type"] == "string"+ assert props["old_string"]["type"] == "string"+ assert props["new_string"]["type"] == "string"+ assert props["replace_all"]["type"] == "boolean"+ assert {"uri", "old_string", "new_string"} <= set(tools["edit"].inputSchema.get("required", []))++# ---------------------------------------------------------------------------# grep tool# ---------------------------------------------------------------------------@@ -1037,3 +1288,52 @@ async def test_mcp_middleware_stamps_root_span_identity():assert response.status_code == 200assert root_attrs.account_id == "acct-1"assert root_attrs.user_id == "user-1"+++# ---- tree tool ----+++async def test_tree_renders_indented_hierarchy(service):+ await write(uri="viking://resources/test_tree/top.md", content="top\n")+ await write(uri="viking://resources/test_tree/sub/a.md", content="alpha\n")+ await write(uri="viking://resources/test_tree/sub/deeper/b.md", content="beta\n")++ result = await tree(uri="viking://resources/test_tree")++ assert result.startswith("Tree of viking://resources/test_tree")+ assert "\nsub/\n" in result+ assert "\n a.md (6 B)\n" in result+ assert "\n deeper/\n" in result+ assert "\n b.md (5 B)" in result+ assert "\ntop.md (4 B)" in result+++async def test_tree_empty_directory(service):+ result = await tree(uri="viking://resources/test_tree_nope")+ assert result == "(nothing under viking://resources/test_tree_nope)"+++async def test_tree_respects_level_limit(service):+ await write(uri="viking://resources/test_tree_depth/d1/d2/deep.md", content="x\n")++ shallow = await tree(uri="viking://resources/test_tree_depth", level_limit=1)+ assert "d1/" in shallow+ assert "deep.md" not in shallow++ full = await tree(uri="viking://resources/test_tree_depth", level_limit=10)+ assert "\n deep.md (2 B)" in full+++async def test_tree_node_limit_adds_truncation_note(service):+ await write(uri="viking://resources/test_tree_limit/f1.md", content="1\n")+ await write(uri="viking://resources/test_tree_limit/f2.md", content="2\n")++ result = await tree(uri="viking://resources/test_tree_limit", node_limit=1)+ assert "(truncated at node_limit=1" in result+++async def test_tree_include_abstract_still_renders(service):+ await write(uri="viking://resources/test_tree_abs/note.md", content="hello tree\n")++ result = await tree(uri="viking://resources/test_tree_abs", include_abstract=True)+ assert "\nnote.md (11 B)" in resultdiff --git a/tests/unit/test_namespace_uri_classification.py b/tests/unit/test_namespace_uri_classification.pyindex a26210287..dbc3f4acc 100644--- a/tests/unit/test_namespace_uri_classification.py+++ b/tests/unit/test_namespace_uri_classification.py@@ -146,3 +146,37 @@ def test_current_user_short_content_roots_are_canonicalized_from_content_segment"viking://user/alice/resources")assert is_content_root_uri("viking://resources", ctx, kind="resource")+++def test_unreserved_user_root_segment_keeps_canonical_meaning():+ ctx = RequestContext(+ user=UserIdentifier(account_id="acct", user_id="alice"),+ role=Role.USER,+ )++ # The generic namespace parser stays canonical-first. Callers that expose+ # a current-user workspace dialect (such as MCP) must opt into that policy+ # at their boundary instead of guessing from file extensions or server state.+ assert canonicalize_uri("viking://user/notes/todo.md", ctx) == "viking://user/notes/todo.md"+ assert (+ canonicalize_uri("viking://user/bob/zeus-persona.md", ctx)+ == "viking://user/bob/zeus-persona.md"+ )+ # A valid canonical user id may itself end in a common file extension.+ assert (+ canonicalize_uri("viking://user/writer.md/memories/profile.md", ctx)+ == "viking://user/writer.md/memories/profile.md"+ )+ assert (+ canonicalize_uri("viking://user/alice.smith/memories/preferences/p.md", ctx)+ == "viking://user/alice.smith/memories/preferences/p.md"+ )+ assert (+ canonicalize_uri("viking://user/[email protected]/resources/r.md", ctx)+ == "viking://user/[email protected]/resources/r.md"+ )+ # The current user's own canonical form remains unchanged.+ assert (+ canonicalize_uri("viking://user/alice/notes/todo.md", ctx)+ == "viking://user/alice/notes/todo.md"+ )