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): expose privacy tree, resolve and upsert tools (#6341)
MaojiaSheng2b77e30aa329
diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex 5c44b1ce7..0c40eb37c 100644--- a/docs/en/guides/06-mcp-integration.md+++ b/docs/en/guides/06-mcp-integration.md@@ -143,6 +143,9 @@ The built-in MCP tools are listed below. Use the connected server's `tools/list`| `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 |+| `privacy_tree` | Check which credentials are saved; return active field metadata and references without values | `category` (optional) |+| `privacy_resolve` | Turn a complete `{{ov_privacy:...}}` placeholder into one current field's actual value for immediate use | `reference` |+| `privacy_upsert` | Save user-supplied credential fields with an atomic merge; return metadata and references without values | `category`, `target_key`, `values` || `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` |@@ -166,6 +169,44 @@ 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.+### Using saved credentials from a skill++If a SKILL.md, document or tool result contains an authentication placeholder such as:++```text+Authorization: Bearer {{ov_privacy:alice:viking://~/privacy/credential/github#/values/pat}}+```++and the current task needs the credential, call `privacy_resolve` with the entire+placeholder unchanged, excluding the surrounding `Authorization: Bearer` text:++```json+{+ "name": "privacy_resolve",+ "arguments": {+ "reference": "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/pat}}"+ }+}+```++These are the parameters for an MCP `tools/call` request. Use the returned `value`+in the API's authentication field; the placeholder itself is not a working key.+Resolution uses the current active version and rejects another owner's reference,+even for administrators. Field-level Privacy URIs are also accepted. If you do not+know the reference, call `privacy_tree`, optionally filtering by `category`.++To save a PAT supplied by the user, call `privacy_upsert` with+`category="credential"`, `target_key="github"` and `values={"pat":"<user-provided-token>"}`.+It creates the target or merges the supplied fields, preserving other fields such+as `username`. Changed values create and activate a version; this does not rotate+credentials at the external provider. Its response describes only the updated+fields, without echoing their values.++Tree and resolve are marked read-only; upsert is marked as a potentially destructive+write. Read-only does not mean non-sensitive: resolve returns plaintext to the MCP+client and Agent context. Keep references in saved documents and memory, and do+not echo resolved secrets in chat. Tree and upsert return no stored values.+### Resource permissions and sharingAll account users may call `list_users` and `list_groups`; neither tool accepts a different account.diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex 9da6f39b5..6840d61f6 100644--- a/docs/zh/guides/06-mcp-integration.md+++ b/docs/zh/guides/06-mcp-integration.md@@ -139,6 +139,9 @@ 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 服务健康状态 | 无 |+| `privacy_tree` | 盘点已保存的凭据;返回当前字段元数据及引用,不含值 | `category`(可选) |+| `privacy_resolve` | 将完整的 `{{ov_privacy:...}}` 占位符解析为一个当前字段的实际值,供立即使用 | `reference` |+| `privacy_upsert` | 原子合并用户提供的凭据字段;返回元数据和引用,不回显值 | `category`, `target_key`, `values` || `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` |@@ -160,6 +163,38 @@ claude mcp add --transport http openviking \> `processing_mode=vectors_only` 会跳过 VLM 语义理解阶段,不生成或刷新 `.abstract.md` / `.overview.md`;它只向量化当前非隐藏资源文件,并保留已存在的旧语义产物。+### 使用 skill 中引用的凭据++当 SKILL.md、文档或工具结果中出现以下认证占位符,且当前任务需要这个凭据时:++```text+Authorization: Bearer {{ov_privacy:alice:viking://~/privacy/credential/github#/values/pat}}+```++调用 `privacy_resolve`,原样传入完整占位符,不要带上外部的 `Authorization: Bearer`:++```json+{+ "name": "privacy_resolve",+ "arguments": {+ "reference": "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/pat}}"+ }+}+```++以上是 MCP `tools/call` 请求的参数。将返回的 `value` 填入 API 的认证字段;占位符本身不是+可以直接使用的密钥。解析始终读取当前生效版本,并拒绝其他 owner 的引用,管理员也不例外。+也支持字段级 Privacy URI。不知道引用时,先调用 `privacy_tree`,可用 `category` 缩小范围。++用户提供 PAT 并要求保存时,调用 `privacy_upsert`,传入 `category="credential"`、+`target_key="github"` 和 `values={"pat":"<user-provided-token>"}`。目标不存在时创建,存在时+合并指定字段,保留 `username` 等其他字段。值变化后创建并激活版本,但不会到外部服务轮换凭据。+成功响应只描述本次更新的字段,不回显它们的值。++tree 和 resolve 标记为只读,upsert 标记为可能覆盖数据的写入。只读不等于不敏感:resolve+会将明文返回给 MCP 客户端和 Agent 上下文。保存文档和记忆时保留引用,不在聊天中复述解析后的+密钥。tree 和 upsert 的响应不返回保存的值。+### 资源权限与授权对象`list_users`、`list_groups` 对当前 account 的普通用户开放,不接受跨 account 查询参数。diff --git a/openviking/privacy/operations.py b/openviking/privacy/operations.pynew file mode 100644index 000000000..023fb01ec--- /dev/null+++ b/openviking/privacy/operations.py@@ -0,0 +1,101 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Privacy operations shared by HTTP and MCP boundaries."""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++from openviking.privacy.reference import (+ build_privacy_field_reference,+ parse_privacy_field_selector,+)+from openviking.privacy.validation import validate_privacy_field_name, validate_privacy_identifier+from openviking.server.identity import RequestContext+from openviking_cli.exceptions import InvalidArgumentError, NotFoundError, PermissionDeniedError++if TYPE_CHECKING:+ from openviking.privacy.service import UserPrivacyConfigService+++def require_privacy_owner(owner_user_id: str, ctx: RequestContext) -> None:+ """Reject references belonging to another user, including for administrators."""+ if owner_user_id != ctx.user.user_id:+ raise PermissionDeniedError(+ f"Privacy reference belongs to user {owner_user_id}", resource=owner_user_id+ )+++def privacy_field_metadata(+ ctx: RequestContext, category: str, target_key: str, values: dict[str, Any]+) -> list[dict[str, Any]]:+ """Describe fields without including any of their stored values."""+ return [+ {+ "field": field,+ "configured": value is not None and str(value) != "",+ "reference": build_privacy_field_reference(+ ctx.user.user_id, category, target_key, field+ ),+ }+ for field, value in sorted(values.items())+ ]+++async def build_privacy_tree(+ privacy: UserPrivacyConfigService | None,+ ctx: RequestContext,+ category: str | None = None,+) -> dict[str, Any]:+ """List the caller's active targets and safe field metadata."""+ if category is not None:+ validate_privacy_identifier(category, "category")+ result: dict[str, Any] = {"owner_user_id": ctx.user.user_id, "categories": []}+ if privacy is None:+ return result+ categories = [category] if category is not None else await privacy.list_categories(ctx)+ for name in categories:+ targets = []+ for target_key in await privacy.list_targets(ctx, name):+ current = await privacy.get_current(ctx, name, target_key)+ if current is None:+ # A directory retained for its lock is not a saved configuration.+ continue+ targets.append(+ {+ "target_key": target_key,+ "version": current.version,+ "fields": privacy_field_metadata(ctx, name, target_key, current.values),+ }+ )+ result["categories"].append({"category": name, "targets": targets})+ return result+++async def resolve_privacy_field(+ privacy: UserPrivacyConfigService | None, ctx: RequestContext, selector: str+) -> dict[str, Any]:+ """Resolve one current field, enforcing the reference's owner before reading."""+ reference = parse_privacy_field_selector(selector, current_user_id=ctx.user.user_id)+ if reference is None:+ raise InvalidArgumentError(+ "selector must be an owner-bound Privacy reference or a field-level Privacy URI"+ )+ require_privacy_owner(reference.owner_user_id, ctx)+ validate_privacy_field_name(reference.field, location="field")+ if privacy is None or not await privacy.exists(ctx, reference.category, reference.target_key):+ raise NotFoundError(f"{reference.category}/{reference.target_key}", "privacy config")+ current = await privacy.get_current(ctx, reference.category, reference.target_key)+ if current is None or reference.field not in current.values:+ raise NotFoundError(selector, "privacy config field")+ value = current.values[reference.field]+ return {+ "owner_user_id": reference.owner_user_id,+ "category": reference.category,+ "target_key": reference.target_key,+ "field": reference.field,+ "version": current.version,+ "configured": value is not None and str(value) != "",+ "reference": reference.render(),+ "value": value,+ }diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 1a06ced05..767e7dcd8 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -51,6 +51,11 @@ from openviking.core.uri_validation import (validate_request_viking_uri,)from openviking.parse.mode import ParseMode, normalize_parse_mode+from openviking.privacy.operations import (+ build_privacy_tree,+ privacy_field_metadata,+ resolve_privacy_field,+)from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundErrorfrom openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingModefrom openviking.retrieve.context_assembler import (@@ -92,6 +97,7 @@ from openviking.utils.search_filters import (from openviking.utils.skill_processor import SkillProcessorfrom openviking.utils.time_decay import validate_event_time_decay_requestfrom openviking_cli.exceptions import (+ FailedPreconditionError,InvalidArgumentError,NotFoundError,OpenVikingError,@@ -431,6 +437,91 @@ async def set_acl(uri: str, acl: AclSpec) -> dict[str, Any]:)+# -- privacy ---------------------------------------------------------------+++@_mcp_error_results()[email protected](annotations=_READ_ONLY_TOOL_ANNOTATIONS)+async def privacy_tree(+ category: Annotated[+ Optional[str], Field(description="Only list this category, e.g. credential or skill")+ ] = None,+) -> dict[str, Any]:+ """Find saved API keys, tokens and other private fields for the current user.+ Use when you need to check whether a GitHub PAT or a skill's api_key is saved.+ Returns categories, targets, active versions, configured flags and complete+ {{ov_privacy:...}} references, never secret values or history. Pass a returned+ reference to privacy_resolve when you need the actual value for a task.+ """+ ctx = _get_ctx()+ return await build_privacy_tree(get_service().privacy_configs, ctx, category)+++@_mcp_error_results()[email protected](annotations=_READ_ONLY_TOOL_ANNOTATIONS)+async def privacy_resolve(+ reference: Annotated[+ str,+ Field(+ min_length=1,+ max_length=2048,+ description="Copy the entire {{ov_privacy:...}} placeholder unchanged, or supply one field-level Privacy URI. Omit surrounding text such as Authorization: Bearer.",+ ),+ ],+) -> dict[str, Any]:+ """Turn an {{ov_privacy:...}} placeholder into its actual API key or token.+ When a SKILL.md, document or tool result contains, for example,+ {{ov_privacy:alice:viking://~/privacy/credential/github#/values/pat}},+ and the task needs that credential, pass the whole placeholder as reference.+ Use the returned value in the API's Authorization header or credential field;+ do not send the placeholder itself as a key. Returns one current field owned+ by the caller. Keep references in saved documents and do not echo the secret+ in chat. If you do not know the reference, use privacy_tree first.+ """+ ctx = _get_ctx()+ return await resolve_privacy_field(get_service().privacy_configs, ctx, reference)+++@_mcp_error_results()[email protected](annotations=_DESTRUCTIVE_TOOL_ANNOTATIONS)+async def privacy_upsert(+ category: Annotated[str, Field(description="Credential category, e.g. credential or skill")],+ target_key: Annotated[+ str, Field(description="Credential target, e.g. github or the skill name")+ ],+ values: Annotated[+ dict[str, Any],+ Field(+ description='Fields to save, e.g. {"pat": "user-provided-token"}. Unspecified fields are preserved.'+ ),+ ],+) -> dict[str, Any]:+ """Save a credential the user supplies, e.g. a GitHub PAT or a skill's api_key.+ For a GitHub PAT use category="credential", target_key="github", values={"pat":+ "<user-provided-token>"}. Creates the target or merges the supplied fields;+ updating pat preserves other fields such as username. Changed values create+ and activate a version; this does not rotate keys at GitHub or other providers.+ Returns updated-field metadata and {{ov_privacy:...}} references, never values.+ Use those references instead of embedding the key in saved documents or memory.+ """+ ctx = _get_ctx()+ privacy = get_service().privacy_configs+ if privacy is None:+ raise FailedPreconditionError("Privacy configuration service is unavailable")+ current = await privacy.patch_values(+ ctx, category, target_key, values, updated_by=ctx.user.user_id+ )+ return {+ "owner_user_id": ctx.user.user_id,+ "category": category,+ "target_key": target_key,+ "version": current.version,+ "fields": privacy_field_metadata(+ ctx, category, target_key, {field: current.values[field] for field in values}+ ),+ }++# -- find / search ---------------------------------------------------------diff --git a/openviking/server/routers/privacy_configs.py b/openviking/server/routers/privacy_configs.pyindex 3aea7a341..c72e03f4c 100644--- a/openviking/server/routers/privacy_configs.py+++ b/openviking/server/routers/privacy_configs.py@@ -7,6 +7,11 @@ from typing import Any, Dict, Optionalfrom fastapi import APIRouter, Depends, Path, Queryfrom pydantic import BaseModel, ConfigDict, Field+from openviking.privacy.operations import (+ build_privacy_tree,+ require_privacy_owner,+ resolve_privacy_field,+)from openviking.privacy.reference import (build_privacy_field_reference,parse_privacy_field_selector,@@ -14,15 +19,12 @@ from openviking.privacy.reference import ()from openviking.privacy.sanitizer import PrivacySanitizerfrom openviking.privacy.scan import PRIVACY_SCAN_MAX_NODES, scan_privacy_content-from openviking.privacy.validation import (- validate_privacy_field_name,- validate_privacy_identifier,-)+from openviking.privacy.validation import validate_privacy_field_namefrom openviking.server.auth import get_request_contextfrom openviking.server.dependencies import get_servicefrom openviking.server.identity import RequestContextfrom openviking.server.models import Response-from openviking_cli.exceptions import InvalidArgumentError, NotFoundError, PermissionDeniedError+from openviking_cli.exceptions import InvalidArgumentError, NotFoundErrorrouter = APIRouter(prefix="/api/v1/privacy-configs", tags=["privacy-configs"])@@ -73,14 +75,6 @@ class PrivacySelectorRequest(BaseModel):selector: str = Field(..., min_length=1, max_length=2048)-def _require_selector_owner(owner_user_id: str, ctx: RequestContext) -> None:- if owner_user_id != ctx.user.user_id:- raise PermissionDeniedError(- f"Privacy reference belongs to user {owner_user_id}",- resource=owner_user_id,- )--@router.get("")async def list_privacy_categories(_ctx: RequestContext = Depends(get_request_context),@@ -116,35 +110,9 @@ async def resolve_privacy_reference(request: PrivacySelectorRequest,_ctx: RequestContext = Depends(get_request_context),):- reference = parse_privacy_field_selector(- request.selector,- current_user_id=_ctx.user.user_id,- )- if reference is None:- raise InvalidArgumentError(- "selector must be an owner-bound Privacy reference or a field-level Privacy URI"- )- _require_selector_owner(reference.owner_user_id, _ctx)- validate_privacy_field_name(reference.field, location="field")- service = get_service()- privacy = service.privacy_configs- await _require_privacy_target(privacy, _ctx, reference.category, reference.target_key)- current = await privacy.get_current(_ctx, reference.category, reference.target_key)- if current is None or reference.field not in current.values:- raise NotFoundError(request.selector, "privacy config field")- value = current.values[reference.field]return Response(status="ok",- result={- "owner_user_id": reference.owner_user_id,- "category": reference.category,- "target_key": reference.target_key,- "field": reference.field,- "version": current.version,- "configured": value is not None and str(value) != "",- "reference": reference.render(),- "value": value,- },+ result=await resolve_privacy_field(get_service().privacy_configs, _ctx, request.selector),)@@ -160,7 +128,7 @@ async def delete_privacy_selector(current_user_id=_ctx.user.user_id,)if field_reference is not None:- _require_selector_owner(field_reference.owner_user_id, _ctx)+ require_privacy_owner(field_reference.owner_user_id, _ctx)outcome = await privacy.delete_field(_ctx,field_reference.category,@@ -192,7 +160,7 @@ async def delete_privacy_selector(raise InvalidArgumentError("selector must be a Privacy target URI, field URI, or owner-bound reference")- _require_selector_owner(target_reference.owner_user_id, _ctx)+ require_privacy_owner(target_reference.owner_user_id, _ctx)deleted = await privacy.delete(_ctx,target_reference.category,@@ -216,55 +184,9 @@ async def list_privacy_tree(_ctx: RequestContext = Depends(get_request_context),):"""List the caller's active Privacy targets and field metadata without values."""- if category is not None:- validate_privacy_identifier(category, "category")- service = get_service()- privacy = service.privacy_configs- if privacy is None:- return Response(- status="ok",- result={"owner_user_id": _ctx.user.user_id, "categories": []},- )-- if category is not None:- categories = [category]- else:- categories = await privacy.list_categories(_ctx)-- tree = []- for name in categories:- targets = []- for target_key in await privacy.list_targets(_ctx, name):- current = await privacy.get_current(_ctx, name, target_key)- if current is None:- # A Skill update may leave an empty directory behind solely for- # its lock; only persisted configuration belongs in the tree.- continue- fields = [- {- "field": field,- "configured": value is not None and str(value) != "",- "reference": build_privacy_field_reference(- _ctx.user.user_id,- name,- target_key,- field,- ),- }- for field, value in sorted(current.values.items())- ]- targets.append(- {- "target_key": target_key,- "version": current.version,- "fields": fields,- }- )- tree.append({"category": name, "targets": targets})-return Response(status="ok",- result={"owner_user_id": _ctx.user.user_id, "categories": tree},+ result=await build_privacy_tree(get_service().privacy_configs, _ctx, category),)diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 0694527cd..709ef6b65 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -8,6 +8,7 @@ and service dependency, avoiding MCP protocol complexity."""import base64+import jsonimport refrom types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -15,10 +16,11 @@ from unittest.mock import AsyncMockimport httpximport pytestfrom fastapi import FastAPI-from mcp.types import AudioContent, ImageContent, TextContent+from mcp.types import AudioContent, CallToolResult, ImageContent, TextContentfrom starlette.routing import Routeimport openviking.server.mcp_endpoint as mcp_endpoint+from openviking.privacy.reference import build_privacy_field_referencefrom openviking.server.auth.plugins import DevAuthPluginfrom openviking.server.dependencies import set_servicefrom openviking.server.identity import AuthMode, RequestContext, Role@@ -90,6 +92,194 @@ def test_get_ctx_raises_when_unset():_mcp_ctx.reset(token)+async def test_privacy_tools_describe_placeholder_resolution_and_permissions():+ tools = {tool.name: tool for tool in await mcp_endpoint.mcp.list_tools()}+ for name in ("privacy_tree", "privacy_resolve"):+ assert tools[name].annotations.readOnlyHint is True+ assert tools["privacy_upsert"].annotations.readOnlyHint is False+ assert tools["privacy_upsert"].annotations.destructiveHint is True+ resolve_tool = tools["privacy_resolve"]+ assert (+ "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/pat}}"+ in resolve_tool.description+ )+ assert "SKILL.md" in resolve_tool.description+ assert "Authorization" in resolve_tool.description+ assert set(resolve_tool.inputSchema["properties"]) == {"reference"}+ assert resolve_tool.inputSchema["required"] == ["reference"]+ assert set(tools["privacy_upsert"].inputSchema["required"]) == {+ "category",+ "target_key",+ "values",+ }+ assert tools["privacy_upsert"].inputSchema["properties"]["values"]["type"] == "object"+++async def test_privacy_tools_merge_discover_and_resolve_without_echoing_saved_values(client):+ secrets = ["pat-original-marker", "pat-updated-marker", "username-private-marker"]+ saved = await mcp_endpoint.mcp.call_tool(+ "privacy_upsert",+ {+ "category": "credential",+ "target_key": "github",+ "values": {"pat": secrets[0], "username": secrets[2]},+ },+ )+ assert saved[1]["version"] == 1+ update = {"category": "credential", "target_key": "github", "values": {"pat": secrets[1]}}+ patched = await mcp_endpoint.mcp.call_tool("privacy_upsert", update)+ assert patched[1]["version"] == 2+ assert [field["field"] for field in patched[1]["fields"]] == ["pat"]+ repeated = await mcp_endpoint.mcp.call_tool("privacy_upsert", update)+ assert repeated[1]["version"] == 2+ tree = await mcp_endpoint.mcp.call_tool("privacy_tree", {"category": "credential"})+ response = await client.get(+ "/api/v1/privacy-configs/tree",+ params={"category": "credential"},+ headers={"X-OpenViking-User": DEFAULT_CTX.user.user_id},+ )+ assert response.status_code == 200, response.text+ assert tree[1] == response.json()["result"]+ for result in (saved, patched, repeated, tree):+ assert all(secret not in repr(result) for secret in secrets)+ assert '"values"' not in json.dumps(result[1])+ target = tree[1]["categories"][0]["targets"][0]+ assert target["version"] == 2+ resolved = await mcp_endpoint.mcp.call_tool(+ "privacy_resolve",+ {+ "reference": target["fields"][0]["reference"],+ },+ )+ assert resolved[1]["value"] == secrets[1]+ assert resolved[1]["version"] == 2+ assert "username" not in resolved[1]+ retained = await mcp_endpoint.mcp.call_tool(+ "privacy_resolve",+ {+ "reference": "viking://~/privacy/credential/github#/values/username",+ },+ )+ assert retained[1]["value"] == secrets[2]++[email protected]("role", [Role.USER, Role.ADMIN, Role.ROOT])+async def test_privacy_resolve_checks_owner_before_storage(service, monkeypatch, role):+ exists = AsyncMock()+ monkeypatch.setattr(service.privacy_configs, "exists", exists)+ token = _mcp_ctx.set(RequestContext(DEFAULT_CTX.user, role))+ try:+ result = await mcp_endpoint.mcp.call_tool(+ "privacy_resolve",+ {+ "reference": build_privacy_field_reference(+ "another-owner", "credential", "github", "pat"+ ),+ },+ )+ finally:+ _mcp_ctx.reset(token)+ assert isinstance(result, CallToolResult)+ assert result.isError is True+ assert result.structuredContent["error"]["code"] == "PERMISSION_DENIED"+ exists.assert_not_awaited()+++async def test_privacy_tools_keep_same_owner_in_other_accounts_isolated():+ await mcp_endpoint.mcp.call_tool(+ "privacy_upsert",+ {+ "category": "credential",+ "target_key": "github",+ "values": {"pat": "account-private-marker"},+ },+ )+ token = _mcp_ctx.set(+ RequestContext(UserIdentifier("another-account", DEFAULT_CTX.user.user_id), Role.USER)+ )+ try:+ tree = await mcp_endpoint.mcp.call_tool("privacy_tree", {})+ missing = await mcp_endpoint.mcp.call_tool(+ "privacy_resolve",+ {+ "reference": build_privacy_field_reference(+ DEFAULT_CTX.user.user_id, "credential", "github", "pat"+ ),+ },+ )+ finally:+ _mcp_ctx.reset(token)+ assert tree[1]["categories"] == []+ assert missing.isError is True+ assert missing.structuredContent["error"]["code"] == "NOT_FOUND"+ assert "account-private-marker" not in repr((tree, missing))+++async def test_privacy_tools_return_structured_errors_without_values():+ await mcp_endpoint.mcp.call_tool(+ "privacy_upsert",+ {+ "category": "credential",+ "target_key": "github",+ "values": {"pat": "private-input-marker"},+ },+ )+ cases = [+ ("privacy_tree", {"category": "../credential"}, "INVALID_ARGUMENT"),+ (+ "privacy_resolve",+ {"reference": "Authorization: Bearer {{ov_privacy:...}}"},+ "INVALID_ARGUMENT",+ ),+ (+ "privacy_resolve",+ {"reference": "viking://~/privacy/credential/github#/values/missing"},+ "NOT_FOUND",+ ),+ (+ "privacy_upsert",+ {+ "category": "credential",+ "target_key": "bad/target",+ "values": {"pat": "private-input-marker"},+ },+ "INVALID_ARGUMENT",+ ),+ ]+ for name, arguments, code in cases:+ result = await mcp_endpoint.mcp.call_tool(name, arguments)+ assert isinstance(result, CallToolResult)+ assert result.isError is True+ assert result.structuredContent["error"]["code"] == code+ assert "private-input-marker" not in repr(result)+++async def test_privacy_tools_handle_disabled_service(service, monkeypatch):+ monkeypatch.setattr(service, "_privacy_config_service", None)+ tree = await mcp_endpoint.mcp.call_tool("privacy_tree", {})+ assert tree[1] == {"owner_user_id": DEFAULT_CTX.user.user_id, "categories": []}+ for name, arguments, code in [+ (+ "privacy_resolve",+ {"reference": "viking://~/privacy/credential/github#/values/pat"},+ "NOT_FOUND",+ ),+ (+ "privacy_upsert",+ {+ "category": "credential",+ "target_key": "github",+ "values": {"pat": "disabled-private-marker"},+ },+ "FAILED_PRECONDITION",+ ),+ ]:+ result = await mcp_endpoint.mcp.call_tool(name, arguments)+ assert result.isError is True+ assert result.structuredContent["error"]["code"] == code+ assert "disabled-private-marker" not in repr(result)++@pytest.mark.parametrize(("uri", "expected"),[