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): 补齐 ACL 操作与安全的用户目录查询 (#5466)
Qin Haojiefd9e69232cc5
diff --git a/.github/scripts/check-plugin-version-bumps.sh b/.github/scripts/check-plugin-version-bumps.shindex 0a2cae63b..f2a62728b 100755--- a/.github/scripts/check-plugin-version-bumps.sh+++ b/.github/scripts/check-plugin-version-bumps.sh@@ -80,7 +80,9 @@ for entry in "${PLUGINS[@]}"; dodir="${entry%%:*}"manifest="${entry#*:}"- changed="$(git diff --name-only "$BASE_REF...HEAD" -- "$dir" "$SHARED_LIB" | grep -v '/node_modules/' || true)"+ # Test-only edits do not change the distributed plugin runtime.+ changed="$(git diff --name-only "$BASE_REF...HEAD" -- "$dir" "$SHARED_LIB" \+ ':(exclude)**/*.test.mjs' | grep -v '/node_modules/' || true)"[ -n "$changed" ] || continue# A plugin added in this branch has no baseline version to compare against.diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex 467294894..89da37b3a 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 16 tools:+Once connected, OpenViking exposes 20 tools:| Tool | Description | Key Parameters ||------|-------------|----------------|@@ -139,9 +139,9 @@ Once connected, OpenViking exposes 16 tools:| `list` | List entries under a `viking://` directory | `uri`, `recursive`, `offset`, `limit`, `sort_by`, `sort_order` (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), `offset`, `limit`, `include_abstract` (optional — also show each directory's summary; for a skill directory that is its name and description) || `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. Skill packages are not maintained this way: the caller's own `skills/` subtree is refused, and a write under `viking://agent/skills` produces a plain file that skips skill installation — use `add_skill` | `uri`, `content`, `mode` (optional: `replace` default — overwrites or creates if missing; `append` — appends or creates if missing; `create` — fails if it exists), `wait` (optional, block until re-indexed), `timeout` (optional) |+| `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. Skill packages are not maintained this way: the caller's own `skills/` subtree is refused, and a write under `viking://agent/skills` produces a plain file that skips skill installation — use `add_skill` | `uri`, `content`, `mode` (optional: `replace` default — overwrites or creates if missing; `append` — appends or creates if missing; `create` — fails if it exists), `wait` (optional, block until re-indexed), `timeout` (optional), `acl` (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. Editing a file inside a skill package does not re-run skill installation — use `add_skill` | `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 access/refresh tokens plus an optional `feishu_app_id` / `feishu_app_secret` pair for Feishu user-token watches) |+| `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 access/refresh tokens plus an optional `feishu_app_id` / `feishu_app_secret` pair for Feishu user-token watches), `acl` (optional) || `add_skill` | Create, install, or replace an agent skill. New skills pass the full SKILL.md text; Git and GitHub tree URLs install every skill in the source unless `skills` names some; a local SKILL.md, directory, or zip returns a signed upload URL like `add_resource` | `data` (SKILL.md text) or `path` (Git URL or local path), `skills` (optional), `target_uri` (optional; `viking://agent/skills` shares with the account), `list_only` (optional) || `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/...`) |@@ -149,6 +149,10 @@ Once connected, OpenViking exposes 16 tools:| `glob` | Find files matching a glob pattern | `pattern`, `uri` (optional scope), `node_limit` || `forget` | Delete any `viking://` URI (use `search` to find it first; pass `recursive=true` to delete a directory). Deleting a skill directory this way leaves the skill's privacy configuration behind; remove a skill with `ov skills remove` or `DELETE /api/v1/skills/{name}` | `uri`, `recursive` (optional) || `health` | Check OpenViking service health | none |+| `list_users` | Find user IDs in the caller's account; credentials are excluded by default, including for administrators | `query` (ID substring), `limit` (100), `page` (1), `include_credentials` (false; true requires ADMIN/ROOT) |+| `list_groups` | List group IDs in the caller's account without membership | None |+| `get_acl` | Read direct, inherited and effective ACL; requires resource manage or account ADMIN | `uri` |+| `set_acl` | Update a shared resource ACL; authorize against the permissions before the change | `uri`, `acl` |To address your own workspace from an MCP tool, use the home alias `viking://~`. Itexpands to `viking://user/<current-user>` on every control plane (REST API, `ov` CLI,@@ -168,12 +172,49 @@ user spaces, not a shortcut to yours. See> `processing_mode=vectors_only` skips the VLM semantic-understanding stage. It does not generate or refresh `.abstract.md` / `.overview.md`; it only vectorizes current non-hidden resource files, preserving any older semantic artifacts that already exist.+### Resource permissions and sharing++All account users may call `list_users` and `list_groups`; neither tool accepts a different account.+The default output contains only user IDs and a matching total, or group IDs. Even administrators+must explicitly set `include_credentials=true` to include available credentials. A USER requesting+credentials receives `PERMISSION_DENIED`, even when the query matches no users. Trusted auth mode+forbids credential disclosure. Group membership remains available through the admin API.++`get_acl` and `set_acl` require resource `manage` permission. A resource manager does not gain+account administrator privileges. `write` and `add_resource` accept an optional `acl` object;+explicit ACL changes require manage on an existing target or inherited from the parent for a new target.+Omitting ACL preserves an existing target's permissions or inherits on creation. Remote imports,+temp-file imports and signed local uploads all carry ACL to the kernel's authorization checks.++For example, `set_acl` accepts:++```json+{+ "uri": "viking://resources/project-a",+ "acl": {+ "acl_mode": "restricted",+ "entries": [{"principal": "user:bob", "level": "read"}]+ }+}+```++`entries` replaces direct grants; omit it to preserve them. `inherit` includes parent grants;+`restricted` uses only direct grants. Reset with `{"acl_mode":"inherit","entries":[]}`.+A restricted ACL can remove the caller's own access; account ADMIN retains implicit management access.++Failed tool calls set MCP `isError=true` and retain business codes such as `PERMISSION_DENIED` in+text. Tools supporting structured output also include `error.code/message/details` alongside the+existing `result` text. Partial batch reads or searches preserve successful results and report+failed items separately.+### Adding local-file resources (single-step upload)The `add_resource` tool accepts both **remote URLs** and **local file paths**, handled differently:- **Remote URL** (`http(s)://`, `git@`, `ssh://`, `git://`): single round-trip — the server fetches and ingests directly.-- **Local file path**: the tool returns an **upload instruction** (plain prose). The agent POSTs the file as `multipart/form-data` (field name `file`) to the `temp_upload` URL given in the response. The URL embeds a one-shot token (10-minute TTL by default) that authorizes the upload, so no API key is needed. The server then ingests the file **automatically in the same request** and returns the final result — the agent does **not** call `add_resource` again.+- **Local file path**: the tool returns an **upload instruction** (plain prose). The agent POSTs the file as `multipart/form-data` (field name `file`) to the `temp_upload` URL given in the response. The URL embeds a one-shot token (10-minute TTL by default) that authorizes the upload, so no API key is needed. The server automatically submits ingestion and returns the acceptance result; processing can continue in the background. The agent does **not** call `add_resource` again.++In `api_key` auth mode, the token retains the role of the issuing MCP call, for both API-key and OAuth callers. Uploads are rejected if the user no longer exists, the identity is being deleted, or the role has been downgraded. A later promotion does not expand an existing token's permissions. Trusted-mode upload tokens continue to use the USER role.This lets any MCP client — including sandboxed environments without a local filesystem (Claude web, Manus, etc.) — push files into OpenViking without pre-installing the `ov` CLI. The token upload reuses the authenticated `temp_upload` route (API key first, otherwise the one-shot `?token=`) and its `TempUploadStore` persistence, so the same `local` / `shared` upload modes apply. Note: the one-shot token is held in-process, so in a multi-worker deployment the `add_resource` call and the follow-up upload POST must reach the same worker (or run single-worker) for the token to resolve.diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex fd411ece4..cd465b954 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 端点暴露 16 个工具:+连接后,OpenViking MCP 端点暴露 20 个工具:| 工具 | 说明 | 主要参数 ||------|------|----------|@@ -131,9 +131,9 @@ claude mcp add --transport http openviking \| `list` | 列出 `viking://` 目录下的条目 | `uri`, `recursive`(可选) || `tree` | 以缩进形式展示 `viking://` URI 下的递归目录树——当需要全面了解文件树结构时使用(单层列表用 `list`,按文件名查找用 `glob`) | `uri`(可选), `level_limit`(默认 3), `node_limit`(默认 1000), `include_abstract`(可选——同时展示每个目录的摘要;skill 目录的摘要就是它的名字和描述) || `remember` | 存储消息到长期记忆(触发记忆提取) | `messages`(`{role, content}` 列表) |-| `write` | 向 `viking://` 文件写入文本(创建/覆盖/追加)。自动创建缺失的父目录;覆盖前请先用 `read` 查看当前内容;只改文件局部时优先用 `edit`。skill 包不要用它维护:调用方自己的 `skills/` 子树会被拒绝,写 `viking://agent/skills` 则生成绕过安装流程的普通文件,请改用 `add_skill` | `uri`, `content`, `mode`(可选:默认 `replace` — 覆盖或在缺失时创建,`append` — 追加或在缺失时创建,`create` — 已存在则失败), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选) |+| `write` | 向 `viking://` 文件写入文本(创建/覆盖/追加)。自动创建缺失的父目录;覆盖前请先用 `read` 查看当前内容;只改文件局部时优先用 `edit`。skill 包不要用它维护:调用方自己的 `skills/` 子树会被拒绝,写 `viking://agent/skills` 则生成绕过安装流程的普通文件,请改用 `add_skill` | `uri`, `content`, `mode`(可选:默认 `replace` — 覆盖或在缺失时创建,`append` — 追加或在缺失时创建,`create` — 已存在则失败), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选), `acl`(可选) || `edit` | 在已有 `viking://` 文件中把精确字符串替换为新文本——用于局部修改,避免整文件重写。若 `old_string` 找不到、或匹配多处且 `replace_all` 为 false,则编辑失败且文件保持不变。编辑 skill 包内的文件不会重新触发 skill 安装流程,请改用 `add_skill` | `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 使用 access/refresh token,并可选传入 `feishu_app_id` / `feishu_app_secret`) |+| `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 使用 access/refresh token,并可选传入 `feishu_app_id` / `feishu_app_secret`), `acl`(可选) || `add_skill` | 新建、安装或替换 agent skill。新 skill 直接传完整 SKILL.md 文本;Git 与 GitHub tree URL 默认安装源里的全部 skill,可用 `skills` 挑选;本地 SKILL.md、目录或 zip 会和 `add_resource` 一样返回签名上传 URL | `data`(SKILL.md 文本)或 `path`(Git URL 或本地路径), `skills`(可选), `target_uri`(可选;`viking://agent/skills` 表示账户共享), `list_only`(可选) || `list_watches` | 列出当前 Agent 可见的 watch 任务(自动刷新订阅),每行显示目标 URI、刷新间隔(分钟)、active/paused 状态以及下一次调度时间 | 无 || `cancel_watch` | 按目标 URI 取消(删除)watch 任务。若需调整刷新周期或临时暂停,请取消后使用新的 `watch_interval` 重新添加 | `to_uri`(必须匹配 watch 任务的 `to` 值,例如 `viking://resources/...`) |@@ -141,6 +141,10 @@ claude mcp add --transport http openviking \| `glob` | 按 glob 模式匹配文件 | `pattern`, `uri`(可选范围), `node_limit` || `forget` | 删除任意 `viking://` URI(先用 `search` 查找;删除目录需 `recursive=true`)。用它删 skill 目录会残留该 skill 的 privacy 配置,请改用 `ov skills remove` 或 `DELETE /api/v1/skills/{name}` | `uri`, `recursive`(可选) || `health` | 检查 OpenViking 服务健康状态 | 无 |+| `list_users` | 查询当前 account 的用户 ID;默认不返回凭证,管理员也一样 | `query`(可选,ID 子串), `limit`(默认 100), `page`(默认 1), `include_credentials`(默认 false,仅 ADMIN/ROOT 可设为 true) |+| `list_groups` | 查询当前 account 的组 ID,不返回成员名单 | 无 |+| `get_acl` | 查看共享资源的直接、继承和有效 ACL;要求该节点的 manage 或账号 ADMIN | `uri` |+| `set_acl` | 设置共享资源 ACL;按修改前的权限校验 manage | `uri`, `acl` |在 MCP 工具中访问自己的工作区,请使用家目录别名 `viking://~`。它在所有控制面(REST API、`ov` CLI、SDK 和 MCP)上都会展开为 `viking://user/<当前用户>`,因此@@ -158,12 +162,47 @@ claude mcp add --transport http openviking \> `processing_mode=vectors_only` 会跳过 VLM 语义理解阶段,不生成或刷新 `.abstract.md` / `.overview.md`;它只向量化当前非隐藏资源文件,并保留已存在的旧语义产物。+### 资源权限与授权对象++`list_users`、`list_groups` 对当前 account 的普通用户开放,不接受跨 account 查询参数。+`list_users` 默认仅返回 `user_id` 和匹配总数,`list_groups` 仅返回 `group_id`。+管理员也必须显式传 `include_credentials=true` 才会返回可用的凭证字段;普通用户传该参数会得到+`PERMISSION_DENIED`,即使查询结果为空也一样。trusted 鉴权模式禁止返回凭证。+组成员管理和成员名单查询仍使用管理员接口。++完整 ACL 的查询和修改都要求资源的 `manage` 权限;普通用户即使是资源 manager,也不会因此获得+读取账号凭证的权限。`write` 和 `add_resource` 接受可选的 `acl` 参数,复用内核的权限校验:+已有目标要求自身 manage,新目标要求从父目录继承 manage。不传 ACL 时,已有目标保留原权限,新目标继承父目录。+`add_resource` 的远程导入、临时文件导入、本地文件上传后自动导入均保留这个参数。++例如,将已有共享资料只授权给 Bob 读取:++```json+{+ "uri": "viking://resources/project-a",+ "acl": {+ "acl_mode": "restricted",+ "entries": [{"principal": "user:bob", "level": "read"}]+ }+}+```++以上为 `set_acl` 的参数。`entries` 完整替换直接授权,省略则保留;`acl_mode=inherit` 合并父级授权,+`restricted` 只使用直接授权。重置为继承使用 `{"acl_mode":"inherit","entries":[]}`。+受限 ACL 可能移除操作者自身的访问权限;账号 ADMIN 始终保留治理权限。++工具执行失败会标记 MCP `isError=true`,业务错误文本保留 `PERMISSION_DENIED` 等错误码;+支持结构化输出的工具还返回 `error.code/message/details`,同时保留原有 `result` 文本。+批量读取或搜索部分失败时保留成功结果,并在失败项中显示原因。+### 添加本地文件资源(单步上传)`add_resource` 工具同时接受**远程 URL** 和**本地文件路径**。两者的处理路径不同:- **远程 URL**(`http(s)://`、`git@`、`ssh://`、`git://`):一次调用即完成,server 直接拉取并入库。-- **本地文件路径**:返回**上传指令**(纯文本)。agent 把文件以 `multipart/form-data`(字段名 `file`)POST 到响应里给出的 `temp_upload` URL。该 URL 内嵌一次性 token(默认 10 分钟过期)作为鉴权凭证,无需 API Key。Server 随后在**同一次请求内自动入库**并返回最终结果,agent **无需**再次调用 `add_resource`。+- **本地文件路径**:返回**上传指令**(纯文本)。agent 把文件以 `multipart/form-data`(字段名 `file`)POST 到响应里给出的 `temp_upload` URL。该 URL 内嵌一次性 token(默认 10 分钟过期)作为鉴权凭证,无需 API Key。Server 随后自动提交导入并返回受理结果,后台处理可以继续进行;agent **无需**再次调用 `add_resource`。++在 `api_key` 鉴权模式下,token 保留发起 MCP 调用时的角色,API Key 和 OAuth 调用均适用。上传时会检查用户是否仍存在、是否正在删除,以及角色是否已降级;不满足条件时拒绝上传。角色后来被提升也不会扩大旧 token 的权限。trusted 模式的 token 仍按 USER 身份处理。这样设计是为了让任何 MCP 客户端(包括无本地文件系统的 Claude web、Manus 等沙箱环境)都能往 OpenViking 灌文件,而不需要客户端预装 `ov` CLI。token 上传复用认证版的 `temp_upload` 路由(API Key 优先,否则走一次性 `?token=`)及其 `TempUploadStore` 持久化,所以 `local` / `shared` 上传模式行为一致。注意:一次性 token 保存在进程内,因此多 worker 部署下 `add_resource` 调用与后续的上传 POST 必须落到同一个 worker(或以单 worker 运行),token 才能被解析。diff --git a/examples/codex-memory-plugin/scripts/marketplace.test.mjs b/examples/codex-memory-plugin/scripts/marketplace.test.mjsindex 6bf68cd2b..5a2eec886 100644--- a/examples/codex-memory-plugin/scripts/marketplace.test.mjs+++ b/examples/codex-memory-plugin/scripts/marketplace.test.mjs@@ -23,15 +23,10 @@ const pluginDir = resolve(scriptsDir, "..");const repoRoot = resolve(scriptsDir, "..", "..", "..");const catalogPath = join(repoRoot, ".agents", "plugins", "marketplace.json");const manifestPath = join(pluginDir, ".codex-plugin", "plugin.json");-const mcpEndpointPath = join(repoRoot, "openviking", "server", "mcp_endpoint.py");const canonicalExperienceSkillPath = join(repoRoot, "examples", "skills", "ov-experience-memory", "SKILL.md");const packagedExperienceSkillPath = join(pluginDir, "skills", "ov-experience-memory", "SKILL.md");const PLUGIN_NAME = "openviking-memory";-const REAL_MCP_TOOLS = [- "find", "search", "read", "list", "tree", "remember", "write", "edit",- "add_resource", "add_skill", "list_watches", "cancel_watch", "grep", "glob", "forget", "health",-];const LEGACY_TOOL_NAMES = ["openviking_recall", "openviking_store", "openviking_forget", "openviking_health"];function readJson(path) {@@ -232,14 +227,6 @@ test("Codex MCP entrypoint forwards only native OpenViking tools", () => {assert.doesNotMatch(entrypoint, /resolveEffectivePeerId|process\.cwd\(\)/);});-test("canonical MCP tool list matches server registrations", () => {- const source = readFileSync(mcpEndpointPath, "utf-8");- const registered = [- ...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);-});-test("plugin.json declares the skills directory so Codex loads bundled skills", () => {const manifest = readJson(manifestPath);assert.equal(manifest.skills, "./skills/");diff --git a/openviking/server/auth/__init__.py b/openviking/server/auth/__init__.pyindex 7598ecbe8..4a03f696c 100644--- a/openviking/server/auth/__init__.py+++ b/openviking/server/auth/__init__.py@@ -215,9 +215,10 @@ async def get_upload_request_context(When an API key (``X-API-Key`` / ``Authorization: Bearer``) is present, resolve identitynormally — an authenticated caller is never downgraded to the token path. Otherwise, if a``?token=`` is present, consume it (single-use) and rebuild the bound identity/business- params; the token itself is the authorization, so no auth-plugin identity checks run and- any spoofed ``X-OpenViking-Account/User`` headers are ignored. The consumed token is- stashed on ``request.state.signed_upload`` so the handler can finish ingestion.+ params. In API-key mode the issuing role is retained only while the account user+ exists and has not been downgraded. Other auth modes retain their USER token context.+ Spoofed identity headers are ignored. The consumed token is stashed on+ ``request.state.signed_upload`` so the handler can finish ingestion."""api_key = _extract_api_key(x_api_key, authorization)if token and not api_key:@@ -226,6 +227,25 @@ async def get_upload_request_context(except UploadTokenError as exc:raise HTTPException(status_code=401, detail=str(exc)) from excrequest.state.signed_upload = consumed+ if _auth_mode(request) == AuthMode.API_KEY:+ manager = get_api_key_manager_or_raise(request)+ if not manager.has_user(consumed.account_id, consumed.user_id):+ raise UnauthenticatedError("Upload token's user no longer exists")+ current_role = Role(manager.get_user_role(consumed.account_id, consumed.user_id))+ if Role(consumed.role).rank > current_role.rank:+ raise UnauthenticatedError(+ "Upload token's role exceeds the user's current role; request a new upload"+ )+ return _build_request_context(+ request,+ ResolvedIdentity(+ role=consumed.role,+ account_id=consumed.account_id,+ user_id=consumed.user_id,+ from_oauth=consumed.from_oauth,+ ),+ actor_peer_id=consumed.actor_peer_id or None,+ )try:ctx = RequestContext(user=UserIdentifier(consumed.account_id, consumed.user_id),@@ -364,3 +384,19 @@ def get_api_key_manager_or_raise(request: Request):if manager is None:raise PermissionDeniedError(_DEV_MODE_ADMIN_API_MESSAGE)return manager+++def should_expose_user_key(request: Request) -> bool:+ """Trusted gateways own credentials; never expose server keys in that mode."""+ from openviking.server.config import ServerConfig++ config = getattr(request.app.state, "config", None)+ if not isinstance(config, ServerConfig):+ return True+ return config.get_effective_auth_mode() != "trusted"+++def registry_watcher_running(request: Request) -> bool:+ plugin = getattr(request.app.state, "auth_plugin", None)+ watch_task = getattr(plugin, "_watch_task", None)+ return watch_task is not None and not watch_task.done()diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 948a83cec..c130634a8 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -26,7 +26,7 @@ from pathlib import PurePosixPathfrom typing import Annotated, Any, Dict, List, Literal, Optional, Unionfrom urllib.parse import quote-from mcp.server.fastmcp import FastMCP+from mcp.server.fastmcp import Context, FastMCPfrom mcp.server.transport_security import TransportSecuritySettingsfrom mcp.types import (AudioContent,@@ -60,11 +60,14 @@ from openviking.retrieve.skill_results import skill_root_urifrom openviking.server.auth import (_build_request_context,_extract_api_key,+ get_api_key_manager_or_raise,normalize_actor_peer_header,+ registry_watcher_running,resolve_identity,+ should_expose_user_key,)from openviking.server.dependencies import get_server_config, get_service-from openviking.server.identity import RequestContext+from openviking.server.identity import RequestContext, Rolefrom openviking.server.local_input_guard import (TEMP_FILE_ID_RE,is_remote_resource_source,@@ -76,6 +79,7 @@ from openviking.server.skill_ingest import install_skillsfrom openviking.server.temp_upload_store import TempUploadStorefrom openviking.server.upload_token_store import upload_token_storefrom openviking.service.skill_sources import GIT_SKILL_SOURCE_PREFIXES+from openviking.storage.acl import AclSpecfrom openviking.utils.media_limits import MAX_INLINE_TOOL_RESULT_MEDIA_BYTESfrom openviking.utils.search_filters import (SearchContextTypeInput,@@ -280,8 +284,14 @@ _OPEN_WORLD_DESTRUCTIVE_TOOL_ANNOTATIONS = ToolAnnotations(class _MCPToolFailure(str):"""Mark a returned string as a whole-call tool execution failure."""+ error: OpenVikingError | None = None-def _mcp_failure(message: str) -> _MCPToolFailure:++def _mcp_failure(message: str | OpenVikingError) -> _MCPToolFailure:+ if isinstance(message, OpenVikingError):+ result = _MCPToolFailure(f"{message.code}: {message.message}")+ result.error = message+ return resultreturn _MCPToolFailure(message)@@ -290,25 +300,37 @@ def _mcp_error_results(*, structured_output: bool = True):Apply this above ``@mcp.tool`` so the literal registration remains theauthoritative tool list. Direct Python calls keep the existing return value.- The registered MCP handler converts only ``_MCPToolFailure`` values to- ``CallToolResult(isError=True)``.+ The registered MCP handler preserves business error codes and details and+ converts failures to ``CallToolResult(isError=True)``."""def decorator(func):- registered_tool = mcp._tool_manager.get_tool(func.__name__)+ registered_tool = next(+ (tool for tool in mcp._tool_manager.list_tools() if tool.fn is func), None+ )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)+ try:+ result = await func(*args, **kwargs)+ except OpenVikingError as exc:+ result = _mcp_failure(exc)if not isinstance(result, _MCPToolFailure):return resultmessage = str(result)+ structured = {"result": message}+ if result.error is not None:+ structured["error"] = {+ "code": result.error.code,+ "message": result.error.message,+ "details": result.error.details,+ }return CallToolResult(content=[TextContent(type="text", text=message)],- structuredContent={"result": message} if structured_output else None,+ structuredContent=structured if structured_output else None,isError=True,)@@ -326,6 +348,90 @@ def _mcp_error_results(*, structured_output: bool = True):return decorator+# -- account directory and resource ACL ------------------------------------+++@_mcp_error_results()[email protected](annotations=_READ_ONLY_TOOL_ANNOTATIONS)+async def list_users(+ context: Context,+ query: str = "",+ limit: Annotated[int, Field(ge=1)] = 100,+ page: Annotated[int, Field(ge=1)] = 1,+ include_credentials: bool = False,+) -> dict[str, Any]:+ """Find users to grant access to in the caller's account. Returns user_id and+ matching total by default, including for administrators. query matches a+ substring of user_id. include_credentials=true requires ADMIN or ROOT and+ returns available credentials; it is forbidden in trusted auth mode.+ Resource manage permission does not grant account administrator privileges.+ """+ ctx = _get_ctx()+ if include_credentials and ctx.role not in (Role.ADMIN, Role.ROOT):+ raise PermissionDeniedError("include_credentials requires ADMIN or ROOT role")+ request = context.request_context.request+ if include_credentials and not should_expose_user_key(request):+ raise PermissionDeniedError("Credential disclosure is disabled in trusted auth mode")+ manager = get_api_key_manager_or_raise(request)+ if not registry_watcher_running(request):+ await manager.refresh_account_users_from_store(ctx.account_id)+ result = manager.get_users_page(+ ctx.account_id,+ limit=limit,+ page=page,+ query_filter=query,+ expose_key=include_credentials,+ )+ fields = ("user_id", "role", "api_key", "key_prefix") if include_credentials else ("user_id",)+ return {+ "users": [{key: user[key] for key in fields if key in user} for user in result["users"]],+ "total": result["total"],+ }+++@_mcp_error_results()[email protected](annotations=_READ_ONLY_TOOL_ANNOTATIONS)+async def list_groups(context: Context) -> dict[str, Any]:+ """List group IDs that can be granted resource access in the caller's account.+ Available to all account users; does not disclose group membership.+ """+ ctx = _get_ctx()+ manager = get_api_key_manager_or_raise(context.request_context.request)+ await manager.ensure_account_groups_loaded(ctx.account_id)+ return {+ "groups": [{"group_id": group["group_id"]} for group in manager.get_groups(ctx.account_id)]+ }+++@_mcp_error_results()[email protected](annotations=_READ_ONLY_TOOL_ANNOTATIONS)+async def get_acl(uri: str) -> dict[str, Any]:+ """Read a shared resource's full ACL (direct, inherited, effective grants).+ Requires manage permission on that resource, or account ADMIN role.+ """+ ctx = _get_ctx()+ return await get_service().fs.get_acl(_resolve_mcp_workspace_uri(uri, ctx), ctx=ctx)+++@_mcp_error_results()[email protected](annotations=_RETRY_SAFE_DESTRUCTIVE_TOOL_ANNOTATIONS)+async def set_acl(uri: str, acl: AclSpec) -> dict[str, Any]:+ """Set a shared resource's ACL; requires manage permission before the change.+ entries replaces direct grants; omitted entries preserves them. Each entry+ has principal (user:<id>, group:<id>, or user:*) and level (read/write/manage).+ acl_mode=inherit adds parent grants; restricted uses only direct grants.+ Reset with acl={"acl_mode":"inherit","entries":[]}. A restricted ACL can+ remove your own access. Account ADMIN retains implicit management access.+ """+ ctx = _get_ctx()+ return await get_service().fs.set_acl(+ _resolve_mcp_workspace_uri(uri, ctx),+ [entry.to_dict() for entry in acl.entries] if acl.entries is not None else None,+ ctx=ctx,+ acl_mode=acl.acl_mode,+ )++# -- find / search ---------------------------------------------------------@@ -338,6 +444,7 @@ def _resolve_context_type_filter(raise InvalidArgumentError(str(exc)) from exc+@_mcp_error_results()@mcp.tool(annotations=_READ_ONLY_TOOL_ANNOTATIONS)async def find(query: str,@@ -397,6 +504,7 @@ _MCP_CONTEXT_ONLY_ALIASES = {}+@_mcp_error_results()@mcp.tool(annotations=_DESTRUCTIVE_TOOL_ANNOTATIONS)async def search(query: str,@@ -798,7 +906,7 @@ async def read()return resolved_uri, size, Noneexcept OpenVikingError as exc:- return uri, None, _mcp_failure(str(exc))+ return uri, None, _mcp_failure(exc)preflight = await asyncio.gather(*[_preflight_one(uri) for uri in uri_list])checked: list[tuple[str, Optional[int], Optional[_MCPToolFailure]]] = []@@ -858,7 +966,7 @@ async def read()return contentexcept OpenVikingError as exc:- return _mcp_failure(str(exc))+ return _mcp_failure(exc)if len(uri_list) == 1:result = await _read_one(uri_list[0], checked[0])@@ -891,6 +999,7 @@ async def read(# -- list ------------------------------------------------------------------+@_mcp_error_results()@mcp.tool(name="list", annotations=_READ_ONLY_TOOL_ANNOTATIONS)async def ls(uri: str = "viking://",@@ -972,6 +1081,7 @@ def _tree_abstract(entry: Dict[str, Any]) -> str:return " ".join(abstract.split())+@_mcp_error_results()@mcp.tool(annotations=_READ_ONLY_TOOL_ANNOTATIONS)async def tree(uri: str = "viking://",@@ -1051,6 +1161,7 @@ class StoreMessage(BaseModel):content: str = Field(description="Message text content")+@_mcp_error_results()@mcp.tool(annotations=_DESTRUCTIVE_TOOL_ANNOTATIONS)async def remember(messages: list[StoreMessage]) -> str:"""Store information into OpenViking long-term memory. Use when the user says 'remember this', shares preferences, important facts, or decisions worth persisting."""@@ -1076,6 +1187,7 @@ async def remember(messages: list[StoreMessage]) -> str:# -- write -----------------------------------------------------------------+@_mcp_error_results()@mcp.tool(annotations=_DESTRUCTIVE_TOOL_ANNOTATIONS)async def write(uri: str,@@ -1083,6 +1195,7 @@ async def write(mode: Literal["replace", "append", "create"] = "replace",wait: bool = False,timeout: Optional[float] = None,+ acl: Optional[AclSpec] = 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.@@ -1090,15 +1203,20 @@ async def write(- 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.+ - acl: optional shared-resource ACL with acl_mode (inherit/restricted) and entries+ (principal=user:<id>/group:<id>/user:*, level=read/write/manage). Explicit ACL+ requires manage on the target, or its parent for a new file. Omit to preserve+ existing ACL or inherit on creation.Writable scopes: viking://resources/, viking://user/{user_id}/, viking://agent/. The viking://~ home alias expands to the caller's user root. The managed user subtrees skills/, peers/, privacy/ and sessions/ are read-only. Do not write inside a skill package under viking://agent/skills/ either: a plain write skips installation, so the skill's abstract, overview and source metadata go stale. Change a skill with the add_skill tool. After a write, semantic search indexes refresh in the background; pass wait=true to block until search reflects the change."""+ # An explicit ACL uses the kernel's manage check before any content is written.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+ uri=uri, content=content, ctx=ctx, mode=mode, wait=wait, timeout=timeout, acl=acl)except NotFoundError:if mode != "replace":@@ -1107,7 +1225,7 @@ async def write(# 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+ uri=uri, content=content, ctx=ctx, mode="create", wait=wait, timeout=timeout, acl=acl)written = result.get("written_bytes", 0)message = (@@ -1116,6 +1234,7 @@ async def write(return message + _indexing_hint(result)+@_mcp_error_results()@mcp.tool(annotations=_DESTRUCTIVE_TOOL_ANNOTATIONS)async def edit(uri: str,@@ -1301,6 +1420,7 @@ async def add_resource(tags: Optional[list[str]] = None,tag_mode: str = "replace",args: Optional[dict[str, Any]] = None,+ acl: Optional[AclSpec] = None,) -> str:"""Add a resource to OpenViking. Asynchronous — processing happens in the background.@@ -1351,6 +1471,10 @@ async def add_resource(tags: Optional explicit k=v retrieval tags to apply after ingestion.tag_mode: Tag update mode: "replace", "append", or "clear". Clear removesexisting tags without requiring ``tags``. Defaults to "replace".+ acl: Optional ACL on the final import root. Uses acl_mode (inherit/restricted)+ and entries with principal (user:<id>, group:<id>, user:*) and level+ (read/write/manage). Requires manage on the existing target or parent+ for a new target. Omit to preserve existing ACL or inherit on creation.args: Parser-specific options, e.g. {"auth_config": {"token": "..."}}for native HTTPS Git imports and watches, {"feishu_access_token": "..."}for Feishu imports, {"site": true} for whole-site ingestion, or@@ -1374,7 +1498,7 @@ async def add_resource(field_name="parent",)except (InvalidArgumentError, PermissionDeniedError) as exc:- return _mcp_failure(f"Error: {exc}")+ return _mcp_failure(exc)try:mode = normalize_parse_mode((args or {}).get("parse_mode", ParseMode.DEFAULT))@@ -1418,9 +1542,10 @@ async def add_resource(processing_mode=processing_mode,tags=tags,tag_mode=tag_mode,+ acl=acl,)- except (PermissionDeniedError, InvalidArgumentError) as exc:- return _mcp_failure(f"Error: {exc}")+ except OpenVikingError as exc:+ return _mcp_failure(exc)except Exception as exc:return _mcp_failure(f"Error adding resource: {exc}")error = _resource_add_error(result)@@ -1467,7 +1592,10 @@ async def add_resource(args=args,tags=tags,tag_mode=tag_mode,+ acl=acl,)+ except OpenVikingError as exc:+ return _mcp_failure(exc)except Exception as exc:return _mcp_failure(f"Error adding resource: {exc}")error = _resource_add_error(result)@@ -1508,6 +1636,8 @@ async def add_resource(ctx.user.account_id,ctx.user.user_id,ttl_seconds=ttl_seconds,+ role=ctx.role,+ from_oauth=ctx.from_oauth,to=to,parent=parent,reason=description,@@ -1516,6 +1646,7 @@ async def add_resource(tags=tags,tag_mode=tag_mode,parse_mode=mode.value,+ acl=acl,)base_url, url_source = _resolve_public_base_url()upload_url = f"{base_url}/api/v1/resources/temp_upload?token={quote(token, safe='')}"@@ -1651,7 +1782,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: SLF001except (InvalidArgumentError, PermissionDeniedError) as exc:- return _mcp_failure(f"Error: {exc}")+ return _mcp_failure(exc)if data.strip() or is_git:try:@@ -1667,8 +1798,8 @@ async def add_skill(else None),)- except (InvalidArgumentError, PermissionDeniedError) as exc:- return _mcp_failure(f"Error: {exc}")+ except OpenVikingError as exc:+ return _mcp_failure(exc)except Exception as exc:return _mcp_failure(f"Error adding skill: {exc}")return _format_skill_install_result(result, list_only=list_only)@@ -1683,6 +1814,8 @@ async def add_skill(ctx.user.account_id,ctx.user.user_id,ttl_seconds=ttl_seconds,+ role=ctx.role,+ from_oauth=ctx.from_oauth,actor_peer_id=ctx.actor_peer_id or "",kind="skill",skill_target_uri=target,@@ -1817,8 +1950,8 @@ async def cancel_watch(to_uri: str) -> str:ctx.user.user_id,str(ctx.role),)- except _wm_mod.PermissionDeniedError:- return _mcp_failure(f"Permission denied for {to_uri}")+ except _wm_mod.PermissionDeniedError as exc:+ return _mcp_failure(PermissionDeniedError(str(exc), resource=to_uri))return f"Watch cancelled: {to_uri}"@@ -1856,7 +1989,8 @@ async def grep(# miss, so carry the reason instead of dropping it. POST /search/grep maps# and re-raises these; reporting them is what keeps the two faces agreeing# about whether a failure is a result.- return (p, [], f"{type(exc).__name__}: {exc}")+ code = exc.code if isinstance(exc, OpenVikingError) else type(exc).__name__+ return (p, [], f"{code}: {exc}")results = await asyncio.gather(*[_grep_one(p) for p in patterns])@@ -1909,6 +2043,8 @@ async def glob(pattern: str, uri: str = "viking://", node_limit: int = 100) -> stry:result = await service.fs.glob(pattern, ctx=ctx, uri=resolved_uri, node_limit=node_limit)+ except OpenVikingError as exc:+ return _mcp_failure(exc)except Exception as e:return _mcp_failure(f"Error: {e}")@@ -1926,6 +2062,7 @@ async def glob(pattern: str, uri: str = "viking://", node_limit: int = 100) -> s# -- forget ----------------------------------------------------------------+@_mcp_error_results()@mcp.tool(annotations=_RETRY_SAFE_DESTRUCTIVE_TOOL_ANNOTATIONS)async def forget(uri: str, recursive: bool = False) -> str:"""Permanently delete a viking:// URI from OpenViking. Irreversible — confirm with user before calling.@@ -2049,10 +2186,9 @@ _apply_portable_schemas()async def mcp_lifespan():"""Run the MCP session manager. Call this inside the FastAPI lifespan."""async with mcp.session_manager.run():+ tools = mcp._tool_manager.list_tools()logger.info(- "MCP endpoint ready (16 tools: find, search, read, write, edit, list, tree, "- "remember, add_resource, add_skill, list_watches, cancel_watch, grep, glob, forget, "- "health)"+ "MCP endpoint ready (%d tools: %s)", len(tools), ", ".join(tool.name for tool in tools))yielddiff --git a/openviking/server/resource_ingest.py b/openviking/server/resource_ingest.pyindex 992baba29..d284783a4 100644--- a/openviking/server/resource_ingest.py+++ b/openviking/server/resource_ingest.py@@ -17,6 +17,7 @@ from openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, Processfrom openviking.server.dependencies import get_servicefrom openviking.server.identity import RequestContextfrom openviking.server.temp_upload_store import TempUploadStore+from openviking.storage.acl import AclSpecasync def ingest_temp_upload(@@ -32,6 +33,7 @@ async def ingest_temp_upload(tags: Optional[list[str]] = None,tag_mode: str = "replace",parse_mode: ParseMode | str = ParseMode.DEFAULT,+ acl: AclSpec | None = None,) -> dict[str, Any]:"""Resolve a temp upload and ingest it as a resource; return the raw add_resource result.@@ -67,6 +69,7 @@ async def ingest_temp_upload(args=ingest_args,tags=tags,tag_mode=tag_mode,+ acl=acl,)except Exception:raisediff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.pyindex 5b779c165..467905952 100644--- a/openviking/server/routers/admin.py+++ b/openviking/server/routers/admin.py@@ -15,10 +15,12 @@ from openviking.server.api_keys.models import validate_account_user_rolefrom openviking.server.auth import (get_api_key_manager_or_raise,get_request_context,+ registry_watcher_running,require_auth_root,require_auth_root_or_admin,+ should_expose_user_key,)-from openviking.server.config import ServerConfig, UserConfig+from openviking.server.config import UserConfigfrom openviking.server.dependencies import get_servicefrom openviking.server.identity import RequestContext, Rolefrom openviking.server.models import Response@@ -235,19 +237,6 @@ def _get_runtime_config_manager():return manager-def _should_expose_user_key(request: Request) -> bool:- config = getattr(request.app.state, "config", None)- if not isinstance(config, ServerConfig):- return True- return config.get_effective_auth_mode() != "trusted"---def _registry_watcher_running(request: Request) -> bool:- plugin = getattr(request.app.state, "auth_plugin", None)- watch_task = getattr(plugin, "_watch_task", None)- return watch_task is not None and not watch_task.done()--def _check_account_access(ctx: RequestContext, account_id: str) -> None:"""ADMIN can only operate on their own account."""if ctx.role == Role.ADMIN and ctx.account_id != account_id:@@ -260,7 +249,7 @@ async def _check_account_exists(manager = getattr(request.app.state, "api_key_manager", None)if manager is None:return None- watcher_running = _registry_watcher_running(request)+ watcher_running = registry_watcher_running(request)if not watcher_running:await manager.refresh_accounts_from_store()accounts = manager.get_accounts()@@ -511,7 +500,7 @@ async def create_account("account_id": body.account_id,"admin_user_id": body.admin_user_id,}- if _should_expose_user_key(request):+ if should_expose_user_key(request):result["user_key"] = user_keyreturn Response(status="ok", result=result)@@ -528,7 +517,7 @@ async def list_accounts():"""List accounts in creation order. `name` supports wildcard (* and ?) matching."""manager = _get_api_key_manager(request)- if not _registry_watcher_running(request):+ if not registry_watcher_running(request):await manager.refresh_accounts_from_store()accounts = manager.get_accounts(name_filter=name, limit=limit, page=page, query_filter=query)return Response(status="ok", result=accounts)@@ -873,7 +862,7 @@ async def register_user("account_id": account_id,"user_id": body.user_id,}- if _should_expose_user_key(request):+ if should_expose_user_key(request):result["user_key"] = user_keyreturn Response(status="ok", result=result)@@ -900,9 +889,9 @@ async def list_users("""List users in an account, in creation order. `name` supports wildcard (* and ?) matching."""_check_account_access(ctx, account_id)manager = _get_api_key_manager(request)- if not _registry_watcher_running(request):+ if not registry_watcher_running(request):await manager.refresh_account_users_from_store(account_id)- expose_key = _should_expose_user_key(request)+ expose_key = should_expose_user_key(request)users = manager.get_users_page(account_id,limit=limit,diff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.pyindex e1d06f1ad..b4f1612fb 100644--- a/openviking/server/routers/resources.py+++ b/openviking/server/routers/resources.py@@ -214,6 +214,7 @@ async def temp_upload(tags=signed.tags,tag_mode=signed.tag_mode,parse_mode=signed.parse_mode,+ acl=signed.acl,)try:diff --git a/openviking/server/upload_token_store.py b/openviking/server/upload_token_store.pyindex c2420c96d..648b7356f 100644--- a/openviking/server/upload_token_store.py+++ b/openviking/server/upload_token_store.py@@ -8,8 +8,9 @@ API key. Tokens are 6-character base62 strings indexed in a process-local dictkey, no on-disk state, no replay-set bookkeeping. ``dict.pop`` doubles as theconsume-and-burn primitive.-The token carries the identity bound at issue time (account/user), the caller's actor peer-scope (``actor_peer_id``), and the business params (``to``/``parent``/``reason``/``parse_mode``) so the server can+The token carries the identity bound at issue time (account/user/role and OAuth origin),+the caller's actor peer scope (``actor_peer_id``), and the business params+(``to``/``parent``/``reason``/``parse_mode``) so the server canfinish ingestion automatically once the file lands — the caller does not re-invoke``add_resource``, and the ingest keeps the original peer scope. Tokens minted by the MCP``add_skill`` tool carry ``kind="skill"`` plus the skill install params instead, and the upload@@ -32,6 +33,8 @@ from dataclasses import dataclassfrom typing import Optional, Tuplefrom openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingMode+from openviking.server.identity import Role+from openviking.storage.acl import AclSpec_TOKEN_ALPHABET = string.ascii_letters + string.digits # base62_TOKEN_LENGTH = 6@@ -45,6 +48,7 @@ class UploadTokenError(Exception):class _TokenInfo:account_id: struser_id: str+ role: Roleto: strparent: strreason: str@@ -58,6 +62,8 @@ class _TokenInfo:skill_target_uri: str = ""skill_names: Optional[list[str]] = Nonelist_only: bool = False+ acl: AclSpec | None = None+ from_oauth: bool = False@dataclass(frozen=True)@@ -66,6 +72,7 @@ class ConsumedUploadToken:account_id: struser_id: str+ role: Roleto: strreason: stractor_peer_id: str@@ -78,6 +85,8 @@ class ConsumedUploadToken:skill_target_uri: str = ""skill_names: Optional[list[str]] = Nonelist_only: bool = False+ acl: AclSpec | None = None+ from_oauth: bool = Falseclass UploadTokenStore:@@ -90,6 +99,7 @@ class UploadTokenStore:user_id: str,ttl_seconds: int,*,+ role: Role,to: str = "",parent: str = "",reason: str = "",@@ -102,6 +112,8 @@ class UploadTokenStore:skill_target_uri: str = "",skill_names: Optional[list[str]] = None,list_only: bool = False,+ acl: AclSpec | None = None,+ from_oauth: bool = False,) -> Tuple[str, float]:"""Mint a fresh token bound to the caller identity and ingestion parameters.@@ -115,6 +127,7 @@ class UploadTokenStore:info = _TokenInfo(account_id,user_id,+ role,to,parent,reason,@@ -128,6 +141,8 @@ class UploadTokenStore:skill_target_uri,skill_names,list_only,+ acl,+ from_oauth,)for _ in range(8):token = "".join(secrets.choice(_TOKEN_ALPHABET) for _ in range(_TOKEN_LENGTH))@@ -148,6 +163,7 @@ class UploadTokenStore:return ConsumedUploadToken(account_id=info.account_id,user_id=info.user_id,+ role=info.role,to=info.to,parent=info.parent,reason=info.reason,@@ -160,6 +176,8 @@ class UploadTokenStore:skill_target_uri=info.skill_target_uri,skill_names=info.skill_names,list_only=info.list_only,+ acl=info.acl,+ from_oauth=info.from_oauth,)def peek(self, token: str) -> Optional[_TokenInfo]:diff --git a/openviking/storage/viking_fs/_access.py b/openviking/storage/viking_fs/_access.pyindex efee53ada..cd92c946f 100644--- a/openviking/storage/viking_fs/_access.py+++ b/openviking/storage/viking_fs/_access.py@@ -229,7 +229,10 @@ class _AccessMixin:access = await self._can_access_many(uris, real_ctx, action=action)denied = next((uri for uri in uris if not access.get(uri, False)), None)if denied is not None:- raise PermissionDeniedError(f"Access denied for {denied}", resource=denied)+ raise PermissionDeniedError(+ f"Access denied for {denied}: {action.value} permission required",+ resource=denied,+ )if action is AclAction.READ:return@@ -289,7 +292,9 @@ class _AccessMixin:effective = await self.acl_manager.resolve(uri, real_ctx)if acl_allows(effective, real_ctx, AclAction.MANAGE):return real_ctx- raise PermissionDeniedError(f"ACL management denied for {uri}", resource=uri)+ raise PermissionDeniedError(+ f"ACL management denied for {uri}: manage permission required", resource=uri+ )async def _ensure_acl_target_exists(self, uri: str, ctx: RequestContext) -> bool:"""Return whether the ACL target is a directory; raise if it is missing."""diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.pyindex 5508615fc..e38cdd64f 100644--- a/tests/server/test_admin_api.py+++ b/tests/server/test_admin_api.py@@ -3316,6 +3316,47 @@ async def test_user_page_summary_and_search_preserve_legacy_response(assert "api_key" not in hidden["users"][0]assert "key_prefix" not in hidden["users"][0]+ # MCP exposes an account directory, not the admin response or credentials.+ from types import SimpleNamespace++ import openviking.server.mcp_endpoint as mcp_endpoint+ from openviking_cli.exceptions import PermissionDeniedError++ await manager.create_group(acct, "engineering")+ await manager.add_group_member(acct, "engineering", "user-1")+ request = FastAPIRequest({"type": "http", "app": lightweight_admin_app})+ context = SimpleNamespace(request_context=SimpleNamespace(request=request))+ for role in (Role.USER, Role.ADMIN, Role.ROOT):+ identity = RequestContext(UserIdentifier(acct, "user-1"), role)+ token = mcp_endpoint._mcp_ctx.set(identity)+ try:+ directory = await mcp_endpoint.list_users(context, query="user-2832")+ assert directory == {"users": [{"user_id": "user-2832"}], "total": 1}+ assert await mcp_endpoint.list_groups(context) == {+ "groups": [{"group_id": "engineering"}]+ }+ if role == Role.USER:+ # Explicit opt-in is rejected even for an empty search result.+ with pytest.raises(PermissionDeniedError, match="ADMIN or ROOT"):+ await mcp_endpoint.list_users(+ context, query="missing", include_credentials=True+ )+ else:+ credentials = await mcp_endpoint.list_users(+ context, query="user-2832", include_credentials=True+ )+ assert credentials["users"][0]["api_key"] == "test-key-2832"+ original_config = lightweight_admin_app.state.config+ lightweight_admin_app.state.config = ServerConfig(auth_mode="trusted")+ try:+ with pytest.raises(PermissionDeniedError, match="trusted"):+ await mcp_endpoint.list_users(context, include_credentials=True)+ assert await mcp_endpoint.list_users(context, query="user-2832") == directory+ finally:+ lightweight_admin_app.state.config = original_config+ finally:+ mcp_endpoint._mcp_ctx.reset(token)+async def test_user_page_summary_respects_account_access(lightweight_admin_client):acct = _uid()diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.pyindex 32fc479ff..1fd4b3c37 100644--- a/tests/server/test_content_write_service.py+++ b/tests/server/test_content_write_service.py@@ -105,7 +105,7 @@ async def test_memory_replace_preserves_metadata(service):@pytest.mark.asyncioasync def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(- service, sample_markdown_file+ service, sample_markdown_file, monkeypatch):"""Shared content inherits permissions without granting its creator extra access."""writer = RequestContext(user=service.user, role=Role.USER, group_ids=("writers",))@@ -177,6 +177,31 @@ async def test_shared_resource_creation_inherits_acl_and_preserves_plain_append(with pytest.raises(PermissionDeniedError):await service.fs.set_acl(uri, [], ctx=writer)+ # MCP keeps full ACL access manage-only and preserves permission errors.+ import openviking.server.mcp_endpoint as mcp_endpoint+ from openviking.storage.acl import AclSpec++ monkeypatch.setattr(mcp_endpoint, "get_service", lambda: service)+ token = mcp_endpoint._mcp_ctx.set(reader)+ try:+ with pytest.raises(PermissionDeniedError):+ await mcp_endpoint.get_acl(uri)+ with pytest.raises(PermissionDeniedError):+ await mcp_endpoint.set_acl(uri, AclSpec(acl_mode="inherit"))+ with pytest.raises(PermissionDeniedError, match="write permission required"):+ await mcp_endpoint.write(uri, "denied")+ finally:+ mcp_endpoint._mcp_ctx.reset(token)+ token = mcp_endpoint._mcp_ctx.set(admin)+ try:+ await mcp_endpoint.write(+ uri, "line1\n", wait=True, acl=AclSpec(acl_mode="restricted", entries=inherited_entries)+ )+ assert (await mcp_endpoint.get_acl(uri))["direct_entries"] == inherited_entries+ await mcp_endpoint.set_acl(uri, AclSpec(acl_mode="inherit", entries=[]))+ finally:+ mcp_endpoint._mcp_ctx.reset(token)+imported = await service.resources.add_resource(path=str(sample_markdown_file),parent=parent_uri,diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 05696567d..efc16f6be 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -1460,7 +1460,7 @@ async def test_add_skill_rejects_a_target_below_a_skill_root_before_minting_a_tofinally:_mcp_ctx.reset(token)- assert result.startswith("Error: Unsupported skill root URI")+ assert result.startswith("INVALID_ARGUMENT: Unsupported skill root URI")assert "viking://agent/skills" in resultassert upload_token_store._store == {}@@ -1496,12 +1496,11 @@ async def test_add_skill_list_only_upload_says_nothing_is_installed(service):({"data": _skill_md("x"), "path": "/tmp/x"}, "not both"),({"data": "/tmp/skills/pdf/SKILL.md"}, 'add_skill(path="/tmp/skills/pdf/SKILL.md")'),({"path": "viking://agent/skills/pdf"}, "read its SKILL.md"),- ({"data": _skill_md("x"), "target_uri": "viking://resources/x"}, "Error:"),+ ({"data": _skill_md("x"), "target_uri": "viking://resources/x"}, "INVALID_URI:"),],)async def test_add_skill_rejects_invalid_arguments(kwargs, expected):result = await add_skill(**kwargs)- assert result.startswith("Error:")assert expected in resultdiff --git a/tests/server/test_mcp_grep_failures.py b/tests/server/test_mcp_grep_failures.pyindex ea1312a20..4b62a7664 100644--- a/tests/server/test_mcp_grep_failures.py+++ b/tests/server/test_mcp_grep_failures.py@@ -44,15 +44,15 @@ def _identity():@pytest.mark.asyncio@pytest.mark.parametrize(- "exc",+ ("exc", "code"),[- NotFoundError(URI, "file"),- PermissionDeniedError("access denied"),- RuntimeError("vector store unreachable"),+ (NotFoundError(URI, "file"), "NOT_FOUND"),+ (PermissionDeniedError("access denied"), "PERMISSION_DENIED"),+ (RuntimeError("vector store unreachable"), "RuntimeError"),],ids=["not-found", "permission-denied", "backend-error"],)-async def test_a_failure_is_not_reported_as_no_matches(exc):+async def test_a_failure_is_not_reported_as_no_matches(exc, code):async def grep(uri, pattern, **kwargs):raise exc@@ -61,7 +61,7 @@ async def test_a_failure_is_not_reported_as_no_matches(exc):out = await mcp_endpoint.grep(uri=URI, pattern="anything")assert "No matches found" not in out- assert type(exc).__name__ in out+ assert code in out@pytest.mark.asynciodiff --git a/tests/server/test_mcp_search_bounds.py b/tests/server/test_mcp_search_bounds.pyindex 2b16bcaee..da061fdb0 100644--- a/tests/server/test_mcp_search_bounds.py+++ b/tests/server/test_mcp_search_bounds.py@@ -91,10 +91,12 @@ async def test_rest_and_mcp_reject_invalid_search_requests():with pytest.raises(ValidationError, match="events_time_decay_protection"):SearchRequest(query="q", events_time_decay_protection="-1d")- with pytest.raises(Exception, match="events_time_decay_protection"):- await mcp_endpoint.mcp.call_tool(- "search", {"query": "q", "events_time_decay_protection": "-1d"}- )+ result = await mcp_endpoint.mcp.call_tool(+ "search", {"query": "q", "events_time_decay_protection": "-1d"}+ )+ assert result.isError is True+ assert result.structuredContent["error"]["code"] == "INVALID_ARGUMENT"+ assert "events_time_decay_protection" in result.structuredContent["error"]["message"]with pytest.raises(ValidationError, match="semantic query or image"):FindRequest(filter={"op": "must", "field": "level", "conds": [2]}, events_time_decay_protection="0"diff --git a/tests/server/test_resource_parse_mode_request.py b/tests/server/test_resource_parse_mode_request.pyindex 2dddab6ef..70c7d6574 100644--- a/tests/server/test_resource_parse_mode_request.py+++ b/tests/server/test_resource_parse_mode_request.py@@ -57,6 +57,7 @@ async def test_signed_temp_upload_forwards_token_bound_parse_mode(signed = ConsumedUploadToken(account_id="test_account",user_id="test_user",+ role=Role.USER,to="",parent="viking://user/test_user/resources/team",reason="",diff --git a/tests/server/test_resources_temp_upload_token.py b/tests/server/test_resources_temp_upload_token.pyindex 794ca7f8f..fea356870 100644--- a/tests/server/test_resources_temp_upload_token.py+++ b/tests/server/test_resources_temp_upload_token.py@@ -17,6 +17,7 @@ from pathlib import Pathimport httpximport pytest+from openviking.server.identity import Rolefrom openviking.server.upload_token_store import upload_token_store@@ -27,149 +28,119 @@ def _reset_token_store():upload_token_store.clear()-def _issue(- account_id: str = "acct",- user_id: str = "user",- *,- to: str = "",- parent: str = "",- reason: str = "",- actor_peer_id: str = "",- tags: list[str] | None = None,- tag_mode: str = "replace",-):- token, _ = upload_token_store.issue(- account_id,- user_id,- ttl_seconds=600,- to=to,- parent=parent,- reason=reason,- actor_peer_id=actor_peer_id,- tags=tags,- tag_mode=tag_mode,- )- return token---def _stub_ingest(service, monkeypatch, root_uri: str = "viking://resources/uploaded") -> dict:- """Stub add_resource so token-path uploads don't run the full ingest pipeline."""- captured: dict = {}-- async def fake_add_resource(*, path, ctx, **kwargs):- captured["path"] = path- captured["content"] = Path(path).read_bytes()- captured["ctx"] = ctx- captured["to"] = kwargs.get("to")- captured["parent"] = kwargs.get("parent")- captured["reason"] = kwargs.get("reason")- captured["tags"] = kwargs.get("tags")- captured["tag_mode"] = kwargs.get("tag_mode")- captured["allow_local_path_resolution"] = kwargs.get("allow_local_path_resolution")- return {"root_uri": root_uri}-- monkeypatch.setattr(service.resources, "add_resource", fake_add_resource)- return captured---async def test_token_upload_auto_ingests_and_returns_result(- client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch-):- captured = _stub_ingest(service, monkeypatch)- token = _issue()- resp = await client.post(- "/api/v1/resources/temp_upload",- params={"token": token},- files={"file": ("hello.md", b"hello world", "text/markdown")},- )- assert resp.status_code == 200, resp.text- result = resp.json()["result"]- # Auto-ingest returns the final resource, not a temp_file_id handshake.- assert result["root_uri"] == "viking://resources/uploaded"- assert "temp_file_id" not in result- # The stored file was resolved and handed to add_resource as a local path.- assert captured["allow_local_path_resolution"] is True- assert captured["content"] == b"hello world"---async def test_token_upload_forwards_to_and_reason(- client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch-):- captured = _stub_ingest(service, monkeypatch)- token = _issue(to="viking://resources/team/proj", reason="quarterly report")- resp = await client.post(- "/api/v1/resources/temp_upload",- params={"token": token},- files={"file": ("r.md", b"data", "text/markdown")},- )- assert resp.status_code == 200, resp.text- assert captured["to"] == "viking://resources/team/proj"- assert captured["reason"] == "quarterly report"---async def test_token_upload_forwards_parent(- client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch-):- captured = _stub_ingest(service, monkeypatch)- token = _issue(parent="viking://user/user/resources/team")- resp = await client.post(- "/api/v1/resources/temp_upload",- params={"token": token},- files={"file": ("r.md", b"data", "text/markdown")},- )-- assert resp.status_code == 200, resp.text- assert captured["parent"] == "viking://user/user/resources/team"---async def test_token_upload_forwards_tags_and_tag_mode(- client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch-):- captured = _stub_ingest(service, monkeypatch)- token = _issue(tags=["team=search"], tag_mode="append")- resp = await client.post(- "/api/v1/resources/temp_upload",- params={"token": token},- files={"file": ("r.md", b"data", "text/markdown")},- )+async def test_token_upload_auto_ingests_and_returns_result(upload_temp_dir: Path, monkeypatch):+ """An upload keeps the issuing authority, but cannot outlive a role downgrade."""+ from types import SimpleNamespace+ from unittest.mock import AsyncMock+ from urllib.parse import parse_qs, urlparse++ from fastapi import FastAPI+ from fastapi.responses import JSONResponse++ from openviking.server import mcp_endpoint, resource_ingest+ from openviking.server.auth.plugins import ApiKeyAuthPlugin+ from openviking.server.config import ServerConfig+ from openviking.server.identity import RequestContext+ from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS+ from openviking.server.routers.resources import router+ from openviking.storage.acl import AclSpec+ from openviking.storage.viking_fs._access import _AccessMixin+ from openviking_cli.exceptions import OpenVikingError+ from openviking_cli.session.user_id import UserIdentifier++ current_role = Role.ADMIN+ config = ServerConfig(auth_mode="api_key", root_api_key="test-root")+ app = FastAPI()+ app.state.config = config+ app.state.auth_plugin = ApiKeyAuthPlugin()+ app.state.api_key_manager = SimpleNamespace(+ has_user=lambda *_: current_role is not None,+ get_user_role=lambda *_: current_role,+ get_user_group_ids=lambda *_: (),+ is_deleting=lambda *_: False,+ )+ app.include_router(router)++ @app.exception_handler(OpenVikingError)+ async def handle_error(_request, exc):+ return JSONResponse(+ status_code=ERROR_CODE_TO_HTTP_STATUS[exc.code], content={"error": exc.code}+ )- assert resp.status_code == 200, resp.text- assert captured["tags"] == ["team=search"]- assert captured["tag_mode"] == "append"---async def test_token_upload_uses_token_identity_ignoring_spoofed_headers(- client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch-):- captured = _stub_ingest(service, monkeypatch)- token = _issue(account_id="real_acct", user_id="real_user")- resp = await client.post(- "/api/v1/resources/temp_upload",- params={"token": token},- files={"file": ("r.md", b"data", "text/markdown")},- headers={"X-OpenViking-Account": "evil", "X-OpenViking-User": "attacker"},- )- assert resp.status_code == 200, resp.text- ctx = captured["ctx"]- assert ctx.user.account_id == "real_acct"- assert ctx.user.user_id == "real_user"---async def test_token_upload_preserves_actor_peer_from_token(- client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch-):- """Actor peer scope comes from the token (bound at mint), not the upload headers."""- captured = _stub_ingest(service, monkeypatch)- token = _issue(actor_peer_id="bot-a")- resp = await client.post(- "/api/v1/resources/temp_upload",- params={"token": token},- files={"file": ("r.md", b"data", "text/markdown")},- # A spoofed actor-peer header must be ignored; the token's peer wins.- headers={"X-OpenViking-Actor-Peer": "evil-bot"},- )- assert resp.status_code == 200, resp.text- assert captured["ctx"].actor_peer_id == "bot-a"+ fs = _AccessMixin()+ fs.acl_manager = SimpleNamespace(is_enabled=AsyncMock(return_value=False))+ acl = AclSpec(acl_mode="restricted", entries=[{"principal": "user:bob", "level": "read"}])+ target = "viking://resources/hello.md"+ imported = []++ async def ingest(*, path, ctx, acl, to, **_kwargs):+ # Exercise the actual kernel authorization, without an embedding/native stack.+ assert ctx.user == UserIdentifier("acct", "user")+ assert ctx.actor_peer_id == "bot-a"+ await fs.prepare_acl_update(to, acl, ctx)+ imported.append(Path(path).read_bytes())+ return {"root_uri": to}++ service = SimpleNamespace(resources=SimpleNamespace(add_resource=ingest))+ monkeypatch.setattr(mcp_endpoint, "get_service", lambda: service)+ monkeypatch.setattr(mcp_endpoint, "get_server_config", lambda: config)+ monkeypatch.setattr(resource_ingest, "get_service", lambda: service)+ identity = RequestContext(+ UserIdentifier("acct", "user"), Role.ADMIN, actor_peer_id="bot-a", from_oauth=True+ )++ async def issue():+ identity_token = mcp_endpoint._mcp_ctx.set(identity)+ try:+ instruction = await mcp_endpoint.add_resource(path="/tmp/hello.md", to=target, acl=acl)+ finally:+ mcp_endpoint._mcp_ctx.reset(identity_token)+ upload_url = next(line.strip() for line in instruction.splitlines() if "?token=" in line)+ return parse_qs(urlparse(upload_url).query)["token"][0]++ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://test"+ ) as client:++ async def upload(token):+ return await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": token},+ headers={+ "X-OpenViking-Account": "other-account",+ "X-OpenViking-User": "spoofed",+ "X-OpenViking-Role": "admin",+ "X-OpenViking-Actor-Peer": "other-peer",+ },+ files={"file": ("hello.md", b"hello world", "text/markdown")},+ )++ token = await issue()+ response = await upload(token)+ assert response.status_code == 200, response.text+ assert response.json()["result"]["root_uri"] == target+ assert "temp_file_id" not in response.json()["result"]+ assert (await upload(token)).status_code == 401++ # An outstanding token loses authority when its user is downgraded.+ identity.from_oauth = False+ token = await issue()+ current_role = Role.USER+ assert (await upload(token)).status_code == 401++ # A token issued as USER does not gain ADMIN authority after promotion.+ identity.role = Role.USER+ token = await issue()+ current_role = Role.ADMIN+ assert (await upload(token)).status_code == 403++ # Removing the user also invalidates an outstanding token.+ identity.role = Role.ADMIN+ token = await issue()+ current_role = None+ assert (await upload(token)).status_code == 401++ assert imported == [b"hello world"]async def test_token_upload_ingest_error_is_not_reported_as_success(@@ -181,7 +152,7 @@ async def test_token_upload_ingest_error_is_not_reported_as_success(return {"status": "error", "code": "PROCESSING_ERROR", "errors": ["parse failed"]}monkeypatch.setattr(service.resources, "add_resource", failing_add_resource)- token = _issue()+ token, _ = upload_token_store.issue("acct", "user", role=Role.USER, ttl_seconds=600)resp = await client.post("/api/v1/resources/temp_upload",params={"token": token},@@ -191,41 +162,12 @@ async def test_token_upload_ingest_error_is_not_reported_as_success(assert resp.json().get("status") == "error"-async def test_token_upload_burns_token_on_use(- client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch-):- _stub_ingest(service, monkeypatch)- token = _issue()- resp1 = await client.post(- "/api/v1/resources/temp_upload",- params={"token": token},- files={"file": ("a.txt", b"first", "text/plain")},- )- assert resp1.status_code == 200, resp1.text-- resp2 = await client.post(- "/api/v1/resources/temp_upload",- params={"token": token},- files={"file": ("a.txt", b"second", "text/plain")},- )- assert resp2.status_code == 401---async def test_token_upload_unknown_token(client: httpx.AsyncClient, upload_temp_dir: Path):- resp = await client.post(- "/api/v1/resources/temp_upload",- params={"token": "ZZZZZZ"},- files={"file": ("upload_abc.md", b"x", "text/plain")},- )- assert resp.status_code == 401--async def test_token_upload_oversize_rejected(client: httpx.AsyncClient, upload_temp_dir: Path, app):"""Size cap is enforced by TempUploadStore before ingestion; oversize maps to 413."""app.state.config.temp_upload.shared_max_size_bytes = 16- token = _issue()+ token, _ = upload_token_store.issue("acct", "user", role=Role.USER, ttl_seconds=600)big = b"x" * 64resp = await client.post("/api/v1/resources/temp_upload",@@ -262,7 +204,9 @@ def _skill_zip(name: str) -> bytes:async def test_skill_token_upload_installs_zipped_skill_directory(client: httpx.AsyncClient, service, upload_temp_dir: Path):- token, _ = upload_token_store.issue("acct", "user", ttl_seconds=600, kind="skill")+ token, _ = upload_token_store.issue(+ "acct", "user", role=Role.USER, ttl_seconds=600, kind="skill"+ )resp = await client.post("/api/v1/resources/temp_upload",params={"token": token},@@ -282,7 +226,7 @@ async def test_skill_token_upload_list_only_does_not_install(monkeypatch.setattr(service.resources, "add_skill", fail_add_skill)token, _ = upload_token_store.issue(- "acct", "user", ttl_seconds=600, kind="skill", list_only=True+ "acct", "user", role=Role.USER, ttl_seconds=600, kind="skill", list_only=True)resp = await client.post("/api/v1/resources/temp_upload",diff --git a/tests/server/test_upload_token_store.py b/tests/server/test_upload_token_store.pyindex 168e9644a..40b31b453 100644--- a/tests/server/test_upload_token_store.py+++ b/tests/server/test_upload_token_store.py@@ -6,9 +6,8 @@ from __future__ import annotationsimport pytest+from openviking.server.identity import Rolefrom openviking.server.upload_token_store import (- _TOKEN_ALPHABET,- _TOKEN_LENGTH,UploadTokenError,UploadTokenStore,)@@ -19,102 +18,20 @@ def store() -> UploadTokenStore:return UploadTokenStore()-def test_issue_returns_token_of_expected_length(store):- token, expires_at = store.issue("acct", "user", ttl_seconds=60)- assert len(token) == _TOKEN_LENGTH- assert all(c in _TOKEN_ALPHABET for c in token)- assert expires_at > 0---def test_consume_roundtrip(store):- token, _ = store.issue("acct", "user", ttl_seconds=60)- consumed = store.consume(token)- assert (consumed.account_id, consumed.user_id) == ("acct", "user")- # Business params default to empty when not supplied at issue time.- assert (consumed.to, consumed.parent, consumed.reason, consumed.actor_peer_id) == (- "",- "",- "",- "",- )- assert consumed.parse_mode == "default"---def test_consume_defaults_to_resource_kind(store):- token, _ = store.issue("acct", "user", ttl_seconds=60)- consumed = store.consume(token)- assert consumed.kind == "resource"- assert (consumed.skill_target_uri, consumed.skill_names, consumed.list_only) == (- "",- None,- False,- )---def test_consume_returns_skill_install_params(store):- token, _ = store.issue(- "acct",- "user",- ttl_seconds=60,- actor_peer_id="bot-a",- kind="skill",- skill_target_uri="viking://agent/skills",- skill_names=["pdf", "xlsx"],- list_only=True,- )- consumed = store.consume(token)- assert consumed.kind == "skill"- assert consumed.skill_target_uri == "viking://agent/skills"- assert consumed.skill_names == ["pdf", "xlsx"]- assert consumed.list_only is True- assert consumed.actor_peer_id == "bot-a"---def test_consume_returns_bound_business_params(store):- token, _ = store.issue(- "acct",- "user",- ttl_seconds=60,- to="viking://resources/team/proj",- parent="viking://user/user/resources/team",- reason="quarterly",- actor_peer_id="bot-a",- processing_mode="vectors_only",- parse_mode="no_split",- )- consumed = store.consume(token)- assert consumed.to == "viking://resources/team/proj"- assert consumed.parent == "viking://user/user/resources/team"- assert consumed.reason == "quarterly"- assert consumed.actor_peer_id == "bot-a"- assert consumed.processing_mode == "vectors_only"- assert consumed.parse_mode == "no_split"--def test_consume_burns_token(store):- token, _ = store.issue("acct", "user", ttl_seconds=60)+ token, _ = store.issue("acct", "user", role=Role.USER, ttl_seconds=60)store.consume(token)with pytest.raises(UploadTokenError, match="unknown or already-consumed"):store.consume(token)-def test_consume_unknown_token(store):- with pytest.raises(UploadTokenError, match="unknown or already-consumed"):- store.consume("ZZZZZZ")---def test_consume_missing_token(store):- with pytest.raises(UploadTokenError, match="missing"):- store.consume("")--def test_consume_expired_token(store, monkeypatch):import openviking.server.upload_token_store as modfake_now = [1000.0]monkeypatch.setattr(mod.time, "time", lambda: fake_now[0])- token, _ = store.issue("acct", "user", ttl_seconds=60)+ token, _ = store.issue("acct", "user", role=Role.USER, ttl_seconds=60)fake_now[0] += 61with pytest.raises(UploadTokenError, match="expired"):store.consume(token)@@ -126,38 +43,12 @@ def test_purge_expired_drops_stale_tokens(store, monkeypatch):fake_now = [1000.0]monkeypatch.setattr(mod.time, "time", lambda: fake_now[0])- t1, _ = store.issue("a", "u", ttl_seconds=10)- t2, _ = store.issue("a", "u", ttl_seconds=600)+ t1, _ = store.issue("a", "u", role=Role.USER, ttl_seconds=10)+ t2, _ = store.issue("a", "u", role=Role.USER, ttl_seconds=600)fake_now[0] += 30 # t1 expired, t2 still alive# Issuing a new token implicitly purges; t1 should be gone afterward- store.issue("a", "u", ttl_seconds=600)+ store.issue("a", "u", role=Role.USER, ttl_seconds=600)assert store.peek(t1) is Noneassert store.peek(t2) is not None---def test_issue_handles_dense_alphabet_collisions(store, monkeypatch):- """Force collisions to verify the retry loop still terminates."""- import openviking.server.upload_token_store as mod-- call_count = [0]- real_choice = mod.secrets.choice-- def fake_choice(seq):- call_count[0] += 1- if call_count[0] <= 42:- return seq[0]- return real_choice(seq)-- monkeypatch.setattr(mod.secrets, "choice", fake_choice)-- t1, _ = store.issue("a", "u", ttl_seconds=60)- t2, _ = store.issue("a", "u", ttl_seconds=60)- assert t1 != t2---def test_clear_resets_state(store):- store.issue("a", "u", ttl_seconds=60)- store.clear()- assert store._store == {}diff --git a/tests/unit/test_mcp_tool_annotations.py b/tests/unit/test_mcp_tool_annotations.pydeleted file mode 100644index 83674c72c..000000000--- a/tests/unit/test_mcp_tool_annotations.py+++ /dev/null@@ -1,38 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: AGPL-3.0--"""Contract tests for MCP tool behavior annotations."""--import openviking.server.mcp_endpoint as mcp_endpoint---async def test_mcp_tools_advertise_behavior_annotations():- tools = {tool.name: tool for tool in await mcp_endpoint.mcp.list_tools()}- expected = {- "find": (True, False, True, False),- # Context mode can persist and prune the per-session recall ledger.- "search": (False, True, False, False),- "read": (True, False, True, False),- "list": (True, False, True, False),- "tree": (True, False, True, False),- "remember": (False, True, False, False),- "write": (False, True, False, False),- "edit": (False, True, False, False),- "add_resource": (False, True, False, True),- "add_skill": (False, True, False, True),- "list_watches": (True, False, True, False),- "cancel_watch": (False, True, True, False),- "grep": (True, False, True, False),- "glob": (True, False, True, False),- "forget": (False, True, True, False),- "health": (True, False, True, False),- }- fields = ("readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint")-- observed = {}- for name, tool in tools.items():- assert tool.annotations is not None- annotations = tool.annotations.model_dump(by_alias=True, exclude_none=True)- observed[name] = tuple(annotations[field] for field in fields)-- assert observed == expecteddiff --git a/tests/unit/test_mcp_tool_error_results.py b/tests/unit/test_mcp_tool_error_results.pyindex a9c8a99c2..dea39a2d8 100644--- a/tests/unit/test_mcp_tool_error_results.py+++ b/tests/unit/test_mcp_tool_error_results.py@@ -11,7 +11,7 @@ from mcp.types import CallToolRequest, CallToolRequestParamsimport openviking.server.mcp_endpoint as mcp_endpointfrom openviking.server.identity import RequestContext, Role-from openviking_cli.exceptions import InvalidArgumentError+from openviking_cli.exceptions import InvalidArgumentError, PermissionDeniedErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -34,68 +34,26 @@ async def _call_tool(name: str, arguments: dict) -> dict: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):+async def test_whole_call_failure_sets_error_result(monkeypatch):+ uri = "viking://resources/a.md"+ service = SimpleNamespace(+ fs=SimpleNamespace(+ write=AsyncMock(+ side_effect=PermissionDeniedError("write permission required", resource=uri)+ )+ )+ )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+ result = await _call_tool("write", {"uri": uri, "content": "denied"})assert result["isError"] is True- assert result["content"] == [{"type": "text", "text": message}]- assert result["structuredContent"] == {"result": message}+ assert result["content"] == [+ {"type": "text", "text": "PERMISSION_DENIED: write permission required"}+ ]+ assert result["structuredContent"]["error"] == {+ "code": "PERMISSION_DENIED",+ "message": "write permission required",+ "details": {"resource": uri},+ }async def test_remote_resource_business_failure_sets_error_result(monkeypatch):@@ -160,7 +118,7 @@ async def test_grep_partial_failure_without_matches_stays_partial(monkeypatch):async def test_read_all_failures_set_error_result(monkeypatch):- read_visible = AsyncMock(side_effect=InvalidArgumentError("not readable"))+ read_visible = AsyncMock(side_effect=PermissionDeniedError("read permission required"))monkeypatch.setattr(mcp_endpoint,"get_service",@@ -178,11 +136,11 @@ async def test_read_all_failures_set_error_result(monkeypatch):assert type(direct_result) is strassert direct_result == (- "=== viking://resources/a.md ===\nnot readable\n\n"- "=== viking://resources/b.md ===\nnot readable"+ "=== viking://resources/a.md ===\nPERMISSION_DENIED: read permission required\n\n"+ "=== viking://resources/b.md ===\nPERMISSION_DENIED: read permission required")assert result["isError"] is True- assert "not readable" in result["content"][0]["text"]+ assert "PERMISSION_DENIED: read permission required" in result["content"][0]["text"]assert "structuredContent" not in result