Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(mcp): add download tool with single-use links, proxied by the gateway (#6119)
t0saki119eba57db8a
diff --git a/docs/en/agent-integrations/10-opencode.md b/docs/en/agent-integrations/10-opencode.mdindex 52788cf62..7e138461a 100644--- a/docs/en/agent-integrations/10-opencode.md+++ b/docs/en/agent-integrations/10-opencode.md@@ -125,10 +125,10 @@ API keys are sent as `Authorization: Bearer ...` by both hooks and the MCP proxy## Verify-Restart OpenCode after installation. In an OpenCode session, the plugin should expose the `openviking` MCP server with the full server MCP tool set (16 tools). OpenCode namespaces MCP tools as `openviking_*`:+Restart OpenCode after installation. In an OpenCode session, the plugin should expose the `openviking` MCP server with the full server MCP tool set (17 tools). OpenCode namespaces MCP tools as `openviking_*`:- `openviking_find`, `openviking_search` (`openviking_search` with `mode="context"` replaces the former recall tool)-- `openviking_read`, `openviking_list`, `openviking_tree`, `openviking_grep`, `openviking_glob`+- `openviking_read`, `openviking_download`, `openviking_list`, `openviking_tree`, `openviking_grep`, `openviking_glob`- `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`, `openviking_add_skill`- `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`diff --git a/docs/en/agent-integrations/11-pi.md b/docs/en/agent-integrations/11-pi.mdindex 26803a633..002eedb92 100644--- a/docs/en/agent-integrations/11-pi.md+++ b/docs/en/agent-integrations/11-pi.md@@ -36,7 +36,7 @@ The extension imports its shared modules from a `shared/` directory that is not- **Every prompt** runs semantic recall against the OpenViking server and injects matching memories as hidden context.- **Every turn** captures user and assistant messages (including structured tool calls) into an OpenViking session; takeover mode commits once synced-token pressure crosses the threshold and then keeps only the recent live tail in model context.- **Context takeover** is enabled by default. The `context` hook injects `[OpenViking Session Context]` from the latest archive overview before recall is added to the latest user turn.-- **Model-callable tools** are whatever the server's MCP `tools/list` returns, each registered under an `openviking_` prefix, including `openviking_find`, `openviking_search`, `openviking_read`, `openviking_list`, `openviking_tree`, `openviking_grep`, `openviking_glob`, `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`, `openviking_add_skill`, `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`. The extension keeps no tool catalogue of its own, so a server that adds or drops a tool changes pi's tool surface at the next session, with no extension release. The shared `mcpEnabled: false` turns the tool surface off and leaves recall, capture, and takeover running.+- **Model-callable tools** are whatever the server's MCP `tools/list` returns, each registered under an `openviking_` prefix, including `openviking_find`, `openviking_search`, `openviking_read`, `openviking_download`, `openviking_list`, `openviking_tree`, `openviking_grep`, `openviking_glob`, `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`, `openviking_add_skill`, `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`. The extension keeps no tool catalogue of its own, so a server that adds or drops a tool changes pi's tool surface at the next session, with no extension release. The shared `mcpEnabled: false` turns the tool surface off and leaves recall, capture, and takeover running.- **Skills**: the extension ships `openviking-memory`, `openviking-skills`, and `ov-experience-memory` from its `skills/` directory and adds them through pi's `resources_discover` event, so the model knows when to use which OpenViking tool. They are left out when `mcpEnabled` is `false`.- The tool handshake never fails startup. If only the MCP handshake fails, REST recall, capture, and takeover can still work. If the server is unavailable or authentication fails, those features also fail or fall back; the bridge retries on a later turn, so a server started after pi is picked up without a restart.- A footer status segment (`OV ✓ …`) shows connection and capture state, plus `tools ✗` when the handshake failed; the `/viking` command prints status, including the registered tool count or the last handshake error, and `/viking commit` forces a commit.diff --git a/docs/en/agent-integrations/13-trae.md b/docs/en/agent-integrations/13-trae.mdindex 1bc7391f3..94f6d535d 100644--- a/docs/en/agent-integrations/13-trae.md+++ b/docs/en/agent-integrations/13-trae.md@@ -39,7 +39,7 @@ TRAE and TRAE CN use the installed `hooks.json` and need no hook approval; resta- `UserPromptSubmit` recalls and injects context for the current request, including your own skills and those shared with your account under `viking://agent/skills`.- `PreToolUse` on TRAE and TRAE CN denies `Read`, `Glob`, and `Grep` calls whose path is a `viking://` URI and points to OpenViking MCP tools; a `Bash` or `RunCommand` command that carries a `viking://` URI still runs, with a notice suggesting those tools. TraeCode CLI 2.0 uses the Codex plugin, whose `PreToolUse` matches only `Bash`: it adds the same notice and never denies a call.- TRAE/TRAE CN `Stop` captures and commits the completed turn. TraeCode CLI 2.0 follows the Codex plugin’s capture and lifecycle commit policy.-- The OpenViking MCP server transparently exposes the full server MCP tool set (20 tools): `find`, `search`, `read`, `list`, `tree`, `remember`, `write`, `edit`, `add_resource`, `add_skill`, `list_watches`, `cancel_watch`, `grep`, `glob`, `forget`, `health`, `list_users`, `list_groups`, `get_acl`, and `set_acl`. `search` with `mode="context"` returns assembled context.+- The OpenViking MCP server transparently exposes the full server MCP tool set (21 tools): `find`, `search`, `read`, `download`, `list`, `tree`, `remember`, `write`, `edit`, `add_resource`, `add_skill`, `list_watches`, `cancel_watch`, `grep`, `glob`, `forget`, `health`, `list_users`, `list_groups`, `get_acl`, and `set_acl`. `search` with `mode="context"` returns assembled context.The skill catalog lists your own skills before those shared with your account, with each description cut to about 40 tokens. Its budget, `skillCatalogTokenBudget` (default `1200` tokens), is separate from the profile budget; when not every description fits, the catalog lists names only. Set `skillCatalog` to `false` or the budget to `0` to turn it off, either in the `plugin` section of `~/.openviking/ovcli.conf` ([Plugin Settings](../configuration/02-client.md#plugin-settings)) or through `OPENVIKING_SKILL_CATALOG` and `OPENVIKING_SKILL_CATALOG_TOKEN_BUDGET`.## Verifydiff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.mdindex 0fb5d0c9f..ab03fe6a8 100644--- a/docs/en/agent-integrations/16-capability-reference.md+++ b/docs/en/agent-integrations/16-capability-reference.md@@ -24,7 +24,7 @@ Long-term memories are extracted from a session only after a **commit**. Capture### Agent-callable tools-"Server MCP tools" means whatever the server's `tools/list` returns: 20 tools on the current server, listed in [Server MCP tools](#server-mcp-tools).+"Server MCP tools" means whatever the server's `tools/list` returns: 21 tools on the current server, listed in [Server MCP tools](#server-mcp-tools).| Integration | How it connects | Tools the agent can call ||---|---|---|@@ -82,7 +82,7 @@ Every MCP-based integration exposes the same server-defined tools and keeps no c| Group | Tools ||---|---|-| Search and browse | `find`, `search`, `read`, `list`, `tree`, `grep`, `glob` |+| Search and browse | `find`, `search`, `read`, `download`, `list`, `tree`, `grep`, `glob` || Write | `remember`, `write`, `edit`, `add_resource`, `add_skill` || Delete | `forget` || Watched resources | `list_watches`, `cancel_watch` (not yet available on the commercial edition) |diff --git a/docs/en/configuration/01-server.md b/docs/en/configuration/01-server.mdindex 9ff2f9862..246b12400 100644--- a/docs/en/configuration/01-server.md+++ b/docs/en/configuration/01-server.md@@ -313,7 +313,7 @@ When `base_url` is configured, OV sends the current user's OV API key in `X-API-| `with_bot` | boolean | `false` | Enable the VikingBot API proxy || `bot_api_url` | URL | `http://localhost:18790` | VikingBot OpenAPI endpoint || `public_base_url` | URL / `null` | `null` | Externally visible base URL |-| `upload_signed_ttl_seconds` | integer | `600` | Signed upload URL lifetime |+| `upload_signed_ttl_seconds` | integer | `600` | Signed upload and download URL lifetime || `temp_upload.default_mode` | `"local"` / `"shared"` | `"local"` | Temporary upload storage |### Encryption and API Key Hashingdiff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex fc78e2fa3..39c905b3f 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -1939,7 +1939,7 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:| `profile_enabled` | bool | Whether to allow request-scoped cProfile via `profile=1` on HTTP requests. When disabled, the server ignores that query parameter. When enabled, the CLI can display the returned `profile`, while the Python HTTP client currently triggers profiling but does not automatically attach the top-level `profile` field to most SDK return values. | `false` || `cors_origins` | list | Allowed CORS origins | `["*"]` || `public_base_url` | str | Public-facing base URL emitted in MCP-issued upload instructions. Resolution order: env var `OPENVIKING_PUBLIC_BASE_URL` → this field → `X-Forwarded-Host`/`X-Forwarded-Proto` request headers → `Host` request header → listen-address fallback. Set this (or the env var) when the server runs behind a reverse proxy that does not forward `X-Forwarded-*` headers. | `null` |-| `upload_signed_ttl_seconds` | int | TTL in seconds for the one-shot tokens minted by the MCP `add_resource` and `add_skill` tools for local-file uploads via `POST /api/v1/resources/temp_upload?token=...`. | `600` (10 minutes) |+| `upload_signed_ttl_seconds` | int | TTL in seconds for the one-shot tokens minted by the MCP `add_resource` and `add_skill` tools for local-file uploads via `POST /api/v1/resources/temp_upload?token=...`, and by the MCP `download` tool for `GET /api/v1/content/download?token=...`. | `600` (10 minutes) || `temp_upload.default_mode` | str | Server-side default for `POST /api/v1/resources/temp_upload` when the client does not send `upload_mode`: `"local"` (per-instance disk, current single-node behavior) or `"shared"` (distributed shared store usable across replicas). New shared uploads are stored in internal `viking://upload/<created_at_ms>-<uuid>/content` and `meta` objects, and can be consumed repeatedly for `ttl_seconds`. | `"local"` || `temp_upload.shared_max_size_bytes` | int | Maximum size accepted in `shared` mode, in bytes. Requests above this size are rejected before object-store write. | `536870912` (512 MiB) || `temp_upload.ttl_seconds` | int | Retention time shared by local and shared temporary uploads, in seconds. Each upload cleans files older than this for its mode; shared cleanup uses one upload-root listing, parses creation time from each first-level directory name, and recursively removes expired directories without filesystem modification times. Set to `0` to disable automatic cleanup. | `43200` (12 hours) |diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex 53d677fd8..5c44b1ce7 100644--- a/docs/en/guides/06-mcp-integration.md+++ b/docs/en/guides/06-mcp-integration.md@@ -128,7 +128,8 @@ The built-in MCP tools are listed below. Use the connected server's `tools/list`|------|-------------|----------------|| `find` | Fast semantic retrieval without session context. `context_type="skill"` on its own switches to package-level skill retrieval: one hit per skill package, its URI pointing at that package's `SKILL.md` and its summary taken from the skill itself, even when an auxiliary file inside the package is what matched. Without `target_uri` it searches both your own skills and the account-shared `viking://agent/skills`. Mixing `skill` with another context type keeps the generic retrieval path | `query`, `target_uri` (optional), `limit`, `min_score`, `level` (optional), `context_type` (optional), `read_content` (optional — inline each hit's content), `events_time_decay_protection` (optional) || `search` | Deep semantic retrieval; `mode="context"` assembles injection-ready context and replaces the former `recall` tool. `list` mode also returns one hit per skill package, its URI pointing at `SKILL.md` and its summary taken from the package itself, but `limit` applies before that merge, so a package matching in several files takes several slots and fewer than `limit` results come back | `query`, `mode` (`list` or `context`), `target_uri` (list mode only), `session_id` (optional), `limit`, `min_score`, `level` (list mode), `context_type` (optional), `events_time_decay_protection` (optional in both modes), plus context-mode `quotas`, `purpose`, `max_tokens`, `detail` or `detail_by_category`, `dedup_turns`, `exclude_uris`, `peer_scope`, scalar `other_peer_penalty` or `other_peer_penalties` by category, and `rewrite` (`off` or `auto`) |-| `read` | Read one or more `viking://` URIs. PNG, JPEG, GIF, and WebP return native MCP image content; WAV, MP3, FLAC, OGG, and M4A return native audio content. Video is not supported because MCP has no standard video content block | `uris` (single string or array), `offset`, `limit` (text lines) |+| `read` | Read one or more `viking://` URIs. PNG, JPEG, GIF, and WebP return native MCP image content; WAV, MP3, FLAC, OGG, and M4A return native audio content. Video is not supported because MCP has no standard video content block; use `download` for the original bytes | `uris` (single string or array), `offset`, `limit` (text lines) |+| `download` | Return a short-lived, single-use URL for fetching the original bytes of one file (any type, including PDF, images, archives, audio and video) with `curl`; it does not return the content. Directories are not supported | `uri` || `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` | Submit messages for long-term memory extraction; returns the background extraction `task_id` right away | `messages` (list of `{role, content}`) |@@ -213,7 +214,7 @@ A client that can read the source bytes and send a multipart HTTP request can up#### When you must set `OPENVIKING_PUBLIC_BASE_URL`-The upload URL the tool returns is resolved server-side in this order:+The upload URL that `add_resource` and `add_skill` return, and the download URL that `download` returns, are resolved server-side in this order:1. Environment variable `OPENVIKING_PUBLIC_BASE_URL`2. `server.public_base_url` in `ov.conf`@@ -238,6 +239,14 @@ services:OPENVIKING_PUBLIC_BASE_URL: "https://ov.your-domain.com"```+### Downloading original files++`read` returns text, or native image and audio content for small media files. To get the original bytes of any file, such as a PDF, an archive, a video, or a large image, call `download` with the file's `uri`. The tool checks that the file exists and that the caller can read it, then returns a `curl -fL -o <local path> <url>` command. The URL points at `GET /api/v1/content/download` and embeds a one-shot token (10-minute TTL by default, set by the same `upload_signed_ttl_seconds` as uploads), so no API key is needed.++The token is bound to the caller's identity and to that one file; a token request ignores any `uri` query parameter. Access is checked again when the file is fetched, so revoking access after the link is issued also blocks the download. Role handling matches uploads: in `api_key` mode the fetch is rejected if the user no longer exists, the identity is being deleted, or the role has been downgraded. A failed or repeated fetch needs a new link from `download`. Requests that carry an API key keep the normal path, so `ov get` is unchanged.++The download URL uses the same base-URL resolution as the upload URL above. Behind a reverse proxy, set `OPENVIKING_PUBLIC_BASE_URL` and make sure the proxy forwards `/api/v1/*` to the server, not only `/mcp`.+## Troubleshooting### Connection refuseddiff --git a/docs/en/guides/22-gateway-operations.md b/docs/en/guides/22-gateway-operations.mdindex b1f6f5cb5..465646967 100644--- a/docs/en/guides/22-gateway-operations.md+++ b/docs/en/guides/22-gateway-operations.md@@ -132,7 +132,7 @@ A standalone gateway serves the same `/gateway` paths on its own port, plus thes- `/` redirects to `/studio/`, where Studio has only the gateway and connection pages.- `/health` returns `service: "openviking-gateway"`, `auth_mode` and `openviking_url`, and also the caller's identity when the request carries a valid OpenViking credential.-**Public address.** For a shared deployment, set `public_url` to the address clients use to reach the server (or the standalone gateway), without `/gateway`; the gateway appends `/gateway` itself. When it is empty, an embedded gateway uses the server's public address (`OPENVIKING_PUBLIC_BASE_URL` or `server.public_base_url`). Studio's setup guides build client settings from it: Anthropic clients use `<public_url>/gateway`, and OpenAI-style clients `<public_url>/gateway/v1`. Without it, the guides use the address the browser used to open Studio, but upload links for file imports only work with `public_url` set; see [Import files and skills](#import-files-and-skills).+**Public address.** For a shared deployment, set `public_url` to the address clients use to reach the server (or the standalone gateway), without `/gateway`; the gateway appends `/gateway` itself. When it is empty, an embedded gateway uses the server's public address (`OPENVIKING_PUBLIC_BASE_URL` or `server.public_base_url`). Studio's setup guides build client settings from it: Anthropic clients use `<public_url>/gateway`, and OpenAI-style clients `<public_url>/gateway/v1`. Without it, the guides use the address the browser used to open Studio, but upload and download links only work with `public_url` set; see [Import files and skills](#import-files-and-skills).### Docker Compose@@ -442,9 +442,11 @@ When the model calls OpenViking tools and client tools in the same reply, the gaNew context profiles have **OpenViking tools** on, including those made with **Create with recommended settings**. The **Tools** list comes from your OpenViking service, and only read-only tools are selected by default:-- **Selected by default**: `find`, `search`, `grep`, `glob`, `list`, `tree`, `read`, `list_watches`, `get_acl`, `list_users`, `list_groups` and `health`.+- **Selected by default**: `find`, `search`, `grep`, `glob`, `list`, `tree`, `read`, `download`, `list_watches`, `get_acl`, `list_users`, `list_groups` and `health`.- **Not selected by default** (they change data): `remember`, `write`, `edit`, `add_resource`, `add_skill`, `forget`, `set_acl` and `cancel_watch`. Check `remember` to let the model save memories, and `add_resource` to let it import web pages or attachments.+`download` returns a one-time `curl` command, so it needs a client shell tool (see [Import files and skills](#import-files-and-skills) for which names count). Like upload links, the download link goes through the gateway at `public_url` plus `/gateway/downloads` by default. Set `mcp_file_links` to `direct` to pass OpenViking's own upload and download links through unchanged; they then point at the server, whose `OPENVIKING_PUBLIC_BASE_URL` (or `server.public_base_url`) must be an address the client can reach.+Tools that OpenViking adds later are available by default; ongoing conversations keep the tool list they started with. Existing context profiles keep their selection.**Allow OpenViking tools** is on by default for every upstream. With both switches on, new conversations get the selected tools with an `openviking_` prefix, such as `openviking_find` and `openviking_read`. Studio describes what each tool does, and shows a read-only label only when OpenViking provides that information. Tool definitions go with every request in the conversation, and the full set adds about 3,500 input tokens, so unchecking tools nobody needs also saves tokens.@@ -501,7 +503,7 @@ A false match also lasts for the whole conversation; start a new one.The model can import material when your OpenViking service provides the import tools and the profile has them checked. Importing by URL needs nothing more. Importing a local file needs one of these:-- **A client shell tool** (named like bash, shell, exec_command, terminal or run_command): the import tool returns a one-time upload link, and the model uploads the file with the client's shell tool, which goes through the client's permission prompt. Skill directories are zipped first. The link points to `public_url` plus `/gateway/uploads`, so `public_url` must be an address the client can reach, and any proxy in front must forward that path like the others. Without `public_url`, imports fail with "Set gateway.public_url for client uploads".+- **A client shell tool** (named like bash, shell, exec_command, terminal or run_command): the import tool returns a one-time upload link, and the model uploads the file with the client's shell tool, which goes through the client's permission prompt. Skill directories are zipped first. The link points to `public_url` plus `/gateway/uploads`, so `public_url` must be an address the client can reach, and any proxy in front must forward that path like the others. Without `public_url`, imports fail with "Set gateway.public_url for client uploads and downloads". With `mcp_file_links` set to `direct`, the link points at OpenViking Server instead.- **An attachment on the user message**: without a shell tool, the model can import a file attached to a user message, sent either as base64 data or as attachment text. This covers embedded `base64` and `text` data in Responses `input_file` and Anthropic `document.source`. Open WebUI usually sends only the extracted text, which is imported as a text file. Attachment URLs and provider file IDs are not fetched; to import a remote resource, use the import tool's URL parameter.Uploads are limited by `max_body_bytes` (32 MiB by default).@@ -676,7 +678,8 @@ Both forms use the same fields; they differ only in where the file lives and how| `port` | Standalone | `1935` | Listen port || `workers` | Standalone | `1` | Worker processes, 1–64 || `encryption` | Standalone | not set (plain text) | Same fields as the `encryption` section of `ov.conf`; see [Encryption](#encryption). Embedded gateways use the server's section |-| `public_url` | Both | empty | The external address clients use, without `/gateway` (the gateway appends it); when empty, an embedded gateway uses the server's public address; with neither, setup guides use the request's origin and file uploads do not work |+| `public_url` | Both | empty | The external address clients use, without `/gateway` (the gateway appends it); when empty, an embedded gateway uses the server's public address; with neither, setup guides use the request's origin, and MCP file uploads and downloads do not work unless `mcp_file_links` is `direct` |+| `mcp_file_links` | Both | `proxy` | How links from the MCP upload and download tools reach the client: `proxy` rewrites them to `public_url` plus `/gateway/uploads` or `/gateway/downloads` and needs `public_url`; `direct` passes OpenViking's links through unchanged and needs the server's `OPENVIKING_PUBLIC_BASE_URL` (or `server.public_base_url`) to be reachable by the client || `storage_path` | Both | `~/.openviking/gateway` | Local storage directory || `management_key` | Both | empty | Optional gateway management key, at least 32 characters || `min_server_version` | Both | `0.4.16` | Lowest OpenViking Server version a standalone gateway accepts |@@ -880,12 +883,12 @@ When the provider rejects a long conversation as too long, it is usually one of- **The conversation's profile has compaction off.** Profile changes only reach new conversations.- **Compaction failed.** The request detail shows the reason, and the gateway tries again after 60 seconds. If summaries keep getting cut off at the length limit, raise **Summary length**. `still_over_threshold` means the system prompt, tools and summary alone fill most of the window: lower **Summary length**, or check the model's context window setting.-### File imports fail+### File imports or downloads fail-- "Set gateway.public_url for client uploads": set `public_url` to an address the client can reach.-- The upload link is unreachable or returns 404: make sure `public_url` is not an old `:1935` address, does not already end in `/gateway`, and that your proxy forwards `/gateway/uploads` like the other paths.+- "Set gateway.public_url for client uploads and downloads": set `public_url` to an address the client can reach, or set `mcp_file_links` to `direct`.+- The upload or download link is unreachable or returns 404: make sure `public_url` is not an old `:1935` address, does not already end in `/gateway`, and that your proxy forwards `/gateway/uploads` and `/gateway/downloads` like the other paths. With `mcp_file_links` set to `direct`, check the server's `OPENVIKING_PUBLIC_BASE_URL` instead.- 413: the file is larger than `max_body_bytes` or the proxy's limit.-- 502 "OpenViking upload is unavailable": the gateway cannot reach OpenViking Server.+- 502 "OpenViking upload is unavailable" or "OpenViking download is unavailable": the gateway cannot reach OpenViking Server.- The model has no import tool: the OpenViking service does not provide it, the profile has it unchecked, or this request cannot use gateway tools. Check the tool list and the request detail.### Issues on degraded requestsdiff --git a/docs/zh/agent-integrations/10-opencode.md b/docs/zh/agent-integrations/10-opencode.mdindex 310ae4cbf..fef6ef758 100644--- a/docs/zh/agent-integrations/10-opencode.md+++ b/docs/zh/agent-integrations/10-opencode.md@@ -125,10 +125,10 @@ API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`## 验证-安装后重启 OpenCode。进入 OpenCode session 后,插件应暴露 `openviking` MCP server,透传服务端完整 MCP 工具集(16 个工具)。OpenCode 会给 MCP 工具加 `openviking_` 前缀:+安装后重启 OpenCode。进入 OpenCode session 后,插件应暴露 `openviking` MCP server,透传服务端完整 MCP 工具集(17 个工具)。OpenCode 会给 MCP 工具加 `openviking_` 前缀:- `openviking_find`、`openviking_search`(`openviking_search` 的 `mode="context"` 替代原 recall 工具)-- `openviking_read`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`+- `openviking_read`、`openviking_download`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`- `openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`、`openviking_add_skill`- `openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`diff --git a/docs/zh/agent-integrations/11-pi.md b/docs/zh/agent-integrations/11-pi.mdindex 6b4b95283..e5ca07f28 100644--- a/docs/zh/agent-integrations/11-pi.md+++ b/docs/zh/agent-integrations/11-pi.md@@ -36,7 +36,7 @@ npm ci --prefix ~/.pi/agent/extensions/openviking --omit=dev --ignore-scripts- **每个 prompt** 向 OpenViking server 做语义召回,把命中的记忆作为隐藏上下文注入。- **每个 turn** 把用户与助手消息(含结构化工具调用)捕获进 OpenViking session;takeover 模式会在 synced token 压力超过阈值后 commit,并在模型上下文中只保留近期 live tail。- **Context takeover** 默认开启。`context` hook 会先注入来自最新 archive overview 的 `[OpenViking Session Context]`,再把 recall 结果插入最新用户消息。-- **模型可调用工具**就是服务端 MCP `tools/list` 返回的工具,注册时统一加 `openviking_` 前缀,包括:`openviking_find`、`openviking_search`、`openviking_read`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`、`openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`、`openviking_add_skill`、`openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`。扩展自己不再维护工具清单,服务端增删工具后,下一次 pi 会话即生效,无需发布新版扩展。共享键 `mcpEnabled: false` 可关掉整个工具面,召回、捕获和 takeover 不受影响。+- **模型可调用工具**就是服务端 MCP `tools/list` 返回的工具,注册时统一加 `openviking_` 前缀,包括:`openviking_find`、`openviking_search`、`openviking_read`、`openviking_download`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`、`openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`、`openviking_add_skill`、`openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`。扩展自己不再维护工具清单,服务端增删工具后,下一次 pi 会话即生效,无需发布新版扩展。共享键 `mcpEnabled: false` 可关掉整个工具面,召回、捕获和 takeover 不受影响。- **Skill**:扩展从自己的 `skills/` 目录提供 `openviking-memory`、`openviking-skills` 和 `ov-experience-memory`,通过 pi 的 `resources_discover` 事件加入,让模型知道什么时候该用哪个 OpenViking 工具。`mcpEnabled` 为 `false` 时不会加入。- 工具握手失败不会影响启动。仅 MCP 握手失败时,REST 召回、捕获和 takeover 仍可使用;整个服务不可达或认证失败时,这些功能也会失败或降级。桥接会在后续 turn 重试,所以 pi 启动之后才拉起的服务端不必重启 pi 也能接上。- 底部状态栏显示 `OV ✓ …` 连接与捕获状态,握手失败时还会追加 `tools ✗`;`/viking` 命令查看状态,包括已注册的工具数量或最近一次握手错误,`/viking commit` 强制 commit。diff --git a/docs/zh/agent-integrations/13-trae.md b/docs/zh/agent-integrations/13-trae.mdindex 2150e3d78..a9e69d007 100644--- a/docs/zh/agent-integrations/13-trae.md+++ b/docs/zh/agent-integrations/13-trae.md@@ -39,7 +39,7 @@ TRAE 和 TRAE CN 使用安装后的 `hooks.json`,不需要审阅 hook,安装- `UserPromptSubmit`:根据当前问题召回并注入相关内容,召回范围包括你自己的 skill 和账号内共享在 `viking://agent/skills` 下的 skill。- `PreToolUse`:在 TRAE 和 TRAE CN 上,`Read`、`Glob`、`Grep` 的路径是 `viking://` URI 时拒绝调用,并提示改用 OpenViking MCP 工具;`Bash` 或 `RunCommand` 命令带 `viking://` URI 时照常执行,同时附加改用建议。TraeCode CLI 2.0 使用 Codex 插件,它的 `PreToolUse` 只匹配 `Bash`,只附加同样的提示,不拒绝调用。- TRAE/TRAE CN 的 `Stop` 捕获并提交本轮消息;TraeCode CLI 2.0 遵循 Codex 插件的捕获与生命周期提交策略。-- OpenViking MCP Server:透传服务端完整 MCP 工具集(20 个工具):`find`、`search`、`read`、`list`、`tree`、`remember`、`write`、`edit`、`add_resource`、`add_skill`、`list_watches`、`cancel_watch`、`grep`、`glob`、`forget`、`health`、`list_users`、`list_groups`、`get_acl`、`set_acl`。其中 `search` 的 `mode="context"` 可返回组装后的上下文。+- OpenViking MCP Server:透传服务端完整 MCP 工具集(21 个工具):`find`、`search`、`read`、`download`、`list`、`tree`、`remember`、`write`、`edit`、`add_resource`、`add_skill`、`list_watches`、`cancel_watch`、`grep`、`glob`、`forget`、`health`、`list_users`、`list_groups`、`get_acl`、`set_acl`。其中 `search` 的 `mode="context"` 可返回组装后的上下文。skill 清单先列你自己的 skill,再列账号内共享的 skill,每条描述截到约 40 token。清单的预算 `skillCatalogTokenBudget`(默认 `1200` token)独立于画像预算;描述放不下时只列名称。把 `skillCatalog` 设为 `false` 或把预算设为 `0` 即可关闭,既可以写在 `~/.openviking/ovcli.conf` 的 `plugin` 段(见[插件配置](../configuration/02-client.md#插件配置)),也可以用环境变量 `OPENVIKING_SKILL_CATALOG` 和 `OPENVIKING_SKILL_CATALOG_TOKEN_BUDGET`。## 验证diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.mdindex f3610674f..3550d4dba 100644--- a/docs/zh/agent-integrations/16-capability-reference.md+++ b/docs/zh/agent-integrations/16-capability-reference.md@@ -24,7 +24,7 @@### 可调用工具-“服务端 MCP 工具”指服务端 `tools/list` 返回的工具:当前服务端有 20 个,列在[服务端 MCP 工具](#服务端-mcp-工具)。+“服务端 MCP 工具”指服务端 `tools/list` 返回的工具:当前服务端有 21 个,列在[服务端 MCP 工具](#服务端-mcp-工具)。| 集成 | 接入方式 | Agent 可调用的工具 ||---|---|---|@@ -81,7 +81,7 @@| 分组 | 工具 ||---|---|-| 检索与浏览 | `find`、`search`、`read`、`list`、`tree`、`grep`、`glob` |+| 检索与浏览 | `find`、`search`、`read`、`download`、`list`、`tree`、`grep`、`glob` || 写入 | `remember`、`write`、`edit`、`add_resource`、`add_skill` || 删除 | `forget` || 监听资源 | `list_watches`、`cancel_watch`(商业版暂不支持) |diff --git a/docs/zh/configuration/01-server.md b/docs/zh/configuration/01-server.mdindex 32ac23f79..a77202c92 100644--- a/docs/zh/configuration/01-server.md+++ b/docs/zh/configuration/01-server.md@@ -312,7 +312,7 @@ Search 和 Find 请求的默认 `limit` 为 `10`,可以在每次 API 或 SDK| `with_bot` | boolean | `false` | 是否启用 VikingBot API 代理 || `bot_api_url` | URL | `http://localhost:18790` | VikingBot OpenAPI 地址 || `public_base_url` | URL / `null` | `null` | 外部访问使用的服务基准地址 |-| `upload_signed_ttl_seconds` | integer | `600` | 签名上传 URL 有效期 |+| `upload_signed_ttl_seconds` | integer | `600` | 签名上传、下载 URL 有效期 || `temp_upload.default_mode` | `"local"` / `"shared"` | `"local"` | 临时上传存储模式 |### 文件加密与 API Key 哈希diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex 7a219cc78..387dfde3f 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -1926,7 +1926,7 @@ ov add-resource ./docs --exclude "*.tmp"| `profile_enabled` | bool | 是否允许 HTTP 请求通过 `profile=1` 开启请求级 cProfile。关闭时服务端会忽略该请求参数;开启后,CLI 可以显示返回的 `profile`,而 Python HTTP client 默认只触发服务端 profile,不会把顶层 `profile` 字段自动附着到大多数 SDK 返回值上。 | `false` || `cors_origins` | list | CORS 允许的来源 | `["*"]` || `public_base_url` | str | MCP `add_resource` 和 `add_skill` 工具向客户端返回的上传指令里使用的对外可见 base URL。解析顺序:环境变量 `OPENVIKING_PUBLIC_BASE_URL` → 本字段 → 请求头 `X-Forwarded-Host` / `X-Forwarded-Proto` → 请求头 `Host` → 监听地址兜底。当 server 部署在反向代理后且代理不转发 `X-Forwarded-*` 时,请显式设置本字段(或环境变量)。 | `null` |-| `upload_signed_ttl_seconds` | int | MCP `add_resource` 和 `add_skill` 为本地文件上传 mint 的一次性 token 的过期时间(秒),走 `POST /api/v1/resources/temp_upload?token=...`。 | `600`(10 分钟) |+| `upload_signed_ttl_seconds` | int | MCP `add_resource` 和 `add_skill` 为本地文件上传 mint 的一次性 token 的过期时间(秒),走 `POST /api/v1/resources/temp_upload?token=...`;MCP `download` 为 `GET /api/v1/content/download?token=...` mint 的一次性 token 也用这个时长。 | `600`(10 分钟) || `temp_upload.default_mode` | str | `POST /api/v1/resources/temp_upload` 的服务端默认模式(客户端未显式传 `upload_mode` 时使用):`"local"`(仅当前实例本地磁盘,单机默认行为)或 `"shared"`(分布式共享存储,多副本部署可跨实例消费)。新的 shared 上传会固定写入内部 `viking://upload/<created_at_ms>-<uuid>/content` 和 `meta` 对象,在 `ttl_seconds` 指定的时间内可重复消费。 | `"local"` || `temp_upload.shared_max_size_bytes` | int | `shared` 模式下接受的最大文件大小(字节)。超过此阈值的请求会在写入对象存储之前被拒绝。 | `536870912`(512 MiB) || `temp_upload.ttl_seconds` | int | local 和 shared 临时上传文件共用的保留时间(秒)。每次对应模式的上传会清理超过此时间的文件;shared 只需一次上传根目录列举,从每个一级目录名解析创建时间,并递归删除过期目录,不依赖文件系统修改时间;设为 `0` 时禁用自动清理。 | `43200`(12 小时) |diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex 6999bd036..9da6f39b5 100644--- a/docs/zh/guides/06-mcp-integration.md+++ b/docs/zh/guides/06-mcp-integration.md@@ -124,7 +124,8 @@ claude mcp add --transport http openviking \|------|------|----------|| `find` | 无 session 上下文的快速语义检索。只传 `context_type="skill"` 时改走包级 skill 检索:每个 skill 包只返回一条命中,URI 指向该包的 `SKILL.md`,摘要取自 skill 本身,即使命中的是包内辅助文件也是如此;不传 `target_uri` 时同时检索自己的 skill 和账户共享的 `viking://agent/skills`。`skill` 与其它 context_type 混用时仍走通用检索路径 | `query`, `target_uri`(可选), `limit`, `min_score`, `level`(可选), `context_type`(可选), `read_content`(可选——直接内联每条命中的内容), `events_time_decay_protection`(可选) || `search` | 深度语义检索;`mode="context"` 组装可直接注入的上下文,并替代原 `recall` 工具。`list` 模式下每个 skill 包也只出一条命中,URI 指向 `SKILL.md`、摘要取自包本身,但 `limit` 在合并之前生效,所以一个包在多个文件上命中时会占掉多个名额,返回条数少于 `limit` | `query`, `mode`(`list` 或 `context`), `target_uri`(仅 list 模式), `session_id`(可选), `limit`, `min_score`, `level`(list 模式), `context_type`(可选), `events_time_decay_protection`(两种模式均可选),以及 context 模式的 `quotas`, `purpose`, `max_tokens`, `detail` 或 `detail_by_category`, `dedup_turns`, `exclude_uris`, `peer_scope`, 标量 `other_peer_penalty` 或按类别设置的 `other_peer_penalties`, `rewrite`(`off` 或 `auto`) |-| `read` | 读取一个或多个 `viking://` URI 的内容。PNG、JPEG、GIF、WebP 返回 MCP 原生图片内容;WAV、MP3、FLAC、OGG、M4A 返回原生音频内容。MCP 没有标准视频内容块,因此暂不支持视频 | `uris`(单个字符串或数组), `offset`, `limit`(文本行数) |+| `read` | 读取一个或多个 `viking://` URI 的内容。PNG、JPEG、GIF、WebP 返回 MCP 原生图片内容;WAV、MP3、FLAC、OGG、M4A 返回原生音频内容。MCP 没有标准视频内容块,因此暂不支持视频;需要原始字节时用 `download` | `uris`(单个字符串或数组), `offset`, `limit`(文本行数) |+| `download` | 返回一个短时有效、只能使用一次的 URL,用 `curl` 获取单个文件的原始字节(任意类型,包括 PDF、图片、压缩包、音频和视频);不返回文件内容。不支持目录 | `uri` || `list` | 列出 `viking://` 目录下的条目 | `uri`, `recursive`(可选) || `tree` | 以缩进形式展示 `viking://` URI 下的递归目录树——当需要全面了解文件树结构时使用(单层列表用 `list`,按文件名查找用 `glob`) | `uri`(可选), `level_limit`(默认 3), `node_limit`(默认 1000), `include_abstract`(可选——同时展示每个目录的摘要;skill 目录的摘要就是它的名字和描述) || `remember` | 提交消息做长期记忆提取;立即返回后台任务的 `task_id`,提取结果可能什么都不保留 | `messages`(`{role, content}` 列表) |@@ -205,7 +206,7 @@ claude mcp add --transport http openviking \#### 必须配置 `OPENVIKING_PUBLIC_BASE_URL` 的场景-工具响应里给出的上传 URL,server 端按以下顺序解析:+`add_resource`、`add_skill` 返回的上传 URL 和 `download` 返回的下载 URL,server 端都按以下顺序解析:1. 环境变量 `OPENVIKING_PUBLIC_BASE_URL`2. `ov.conf` 中的 `server.public_base_url`@@ -230,6 +231,14 @@ services:OPENVIKING_PUBLIC_BASE_URL: "https://ov.your-domain.com"```+### 下载原始文件++`read` 返回文本,小体积的图片和音频返回 MCP 原生内容。要拿到任意文件的原始字节(例如 PDF、压缩包、视频或大图),用文件的 `uri` 调用 `download`。工具先确认文件存在且调用方有读权限,再返回一条 `curl -fL -o <本地路径> <url>` 命令。URL 指向 `GET /api/v1/content/download`,内嵌一次性 token(默认 10 分钟过期,与上传共用 `upload_signed_ttl_seconds`),无需 API Key。++token 绑定调用方身份和这一个文件,带 token 的请求会忽略 `uri` 查询参数。取文件时会再次校验权限,所以签发链接后撤销访问权限,下载同样会失败。角色处理与上传一致:在 `api_key` 模式下,用户已不存在、身份正在删除或角色已降级时,下载会被拒绝。下载失败或链接已用过时,重新调用 `download` 获取新链接。带 API Key 的请求仍走原有路径,`ov get` 不受影响。++下载 URL 与上文的上传 URL 使用同一套 base URL 解析规则。部署在反向代理后时,请配置 `OPENVIKING_PUBLIC_BASE_URL`,并确保代理把 `/api/v1/*` 转发到 server,而不只是 `/mcp`。+## 故障排除### 连接被拒绝diff --git a/docs/zh/guides/22-gateway-operations.md b/docs/zh/guides/22-gateway-operations.mdindex 923c088a5..c1a27e969 100644--- a/docs/zh/guides/22-gateway-operations.md+++ b/docs/zh/guides/22-gateway-operations.md@@ -132,7 +132,7 @@ v0.5 网关用自己的密钥加密数据,这些数据会在首次启动时转- `/` 跳转到 `/studio/`,Studio 只包含网关和连接页面。- `/health` 返回 `service: "openviking-gateway"`、`auth_mode` 和 `openviking_url`;请求带有效的 OpenViking 凭证时,还返回调用方身份。-**对外地址。** 共享部署要把 `public_url` 设为客户端访问 Server(或独立网关)的地址,不带 `/gateway`,网关会自己加上。嵌入网关不设置时,沿用 Server 的对外地址(`OPENVIKING_PUBLIC_BASE_URL` 或 `server.public_base_url`)。Studio 的接入指南用它生成配置:Anthropic 客户端使用 `<public_url>/gateway`,OpenAI 风格的客户端使用 `<public_url>/gateway/v1`。不设置时,指南使用浏览器访问 Studio 的地址;但文件导入的上传链接必须依赖 `public_url`,见[导入文件和技能](#导入文件和技能)。+**对外地址。** 共享部署要把 `public_url` 设为客户端访问 Server(或独立网关)的地址,不带 `/gateway`,网关会自己加上。嵌入网关不设置时,沿用 Server 的对外地址(`OPENVIKING_PUBLIC_BASE_URL` 或 `server.public_base_url`)。Studio 的接入指南用它生成配置:Anthropic 客户端使用 `<public_url>/gateway`,OpenAI 风格的客户端使用 `<public_url>/gateway/v1`。不设置时,指南使用浏览器访问 Studio 的地址;但上传和下载链接必须依赖 `public_url`,见[导入文件和技能](#导入文件和技能)。### Docker Compose@@ -442,9 +442,11 @@ ov.example.com {新建的上下文配置默认开启 **OpenViking 工具**,“使用推荐设置创建”也一样。**工具**清单来自你的 OpenViking 服务,默认只勾选只读工具:-- **默认勾选**:`find`、`search`、`grep`、`glob`、`list`、`tree`、`read`、`list_watches`、`get_acl`、`list_users`、`list_groups` 和 `health`。+- **默认勾选**:`find`、`search`、`grep`、`glob`、`list`、`tree`、`read`、`download`、`list_watches`、`get_acl`、`list_users`、`list_groups` 和 `health`。- **默认不勾选**(会修改数据):`remember`、`write`、`edit`、`add_resource`、`add_skill`、`forget`、`set_acl` 和 `cancel_watch`。想让模型保存记忆就勾选 `remember`,想让它导入网页或附件就勾选 `add_resource`。+`download` 返回一条一次性的 `curl` 命令,所以客户端需要有 shell 工具(哪些名称算 shell 工具见[导入文件和技能](#导入文件和技能))。和上传链接一样,下载链接默认经过网关,指向 `public_url` 加 `/gateway/downloads`。把 `mcp_file_links` 设为 `direct` 后,网关原样透传 OpenViking 返回的上传和下载链接,链接直接指向 Server,此时 Server 的 `OPENVIKING_PUBLIC_BASE_URL`(或 `server.public_base_url`)必须是客户端能访问的地址。+OpenViking 以后新增的工具会默认可用,已有对话仍沿用开始时的工具清单。已有的上下文配置保留原来的勾选。每个上游的**允许 OpenViking 工具**默认开启。两个开关都开启时,新对话获得选中的工具,名称加上 `openviking_` 前缀,例如 `openviking_find`、`openviking_read`。Studio 会说明每个工具的用途;只有 OpenViking 提供了相应信息时,才显示只读标记。工具定义随对话中的每个请求发送,全部工具约占 3,500 个输入 token,所以取消用不到的工具也能省 token。@@ -501,7 +503,7 @@ OpenViking 以后新增的工具会默认可用,已有对话仍沿用开始时OpenViking 服务提供导入工具、上下文配置也勾选了它们时,模型就能导入资料。按 URL 导入不需要额外条件;导入本地文件需要以下两种方式之一:-- **客户端有 shell 工具**(名称类似 bash、shell、exec_command、terminal 或 run_command):导入工具返回一个一次性上传链接,模型再用客户端的 shell 工具上传文件,这一步经过客户端的权限确认。技能目录会先打包成 zip。链接指向 `public_url` 加 `/gateway/uploads`,所以 `public_url` 必须是客户端能访问的地址,前面的代理也要像其他路径一样转发它。没有设置 `public_url` 时,导入失败并提示 "Set gateway.public_url for client uploads"。+- **客户端有 shell 工具**(名称类似 bash、shell、exec_command、terminal 或 run_command):导入工具返回一个一次性上传链接,模型再用客户端的 shell 工具上传文件,这一步经过客户端的权限确认。技能目录会先打包成 zip。链接指向 `public_url` 加 `/gateway/uploads`,所以 `public_url` 必须是客户端能访问的地址,前面的代理也要像其他路径一样转发它。没有设置 `public_url` 时,导入失败并提示 "Set gateway.public_url for client uploads and downloads"。`mcp_file_links` 设为 `direct` 时,链接改为直接指向 OpenViking Server。- **用户消息带附件**:没有 shell 工具时,模型可以导入用户消息里附带的文件,文件可以是 base64 数据,也可以是附件文本,支持 Responses `input_file` 和 Anthropic `document.source` 中内嵌的 `base64`、`text` 数据。Open WebUI 通常只发送提取出的文本,这些文本作为文本文件导入。附件中的 URL 和服务商的文件 ID 不会被抓取;要导入远程资源,请用导入工具的 URL 参数。上传大小受 `max_body_bytes` 限制(默认 32 MiB)。@@ -676,7 +678,8 @@ Token 预算只计算模型使用 OpenViking 工具时新增的调用、结果| `port` | 独立 | `1935` | 监听端口 || `workers` | 独立 | `1` | worker 进程数,1–64 || `encryption` | 独立 | 不设置(明文) | 字段同 `ov.conf` 的 `encryption` 段,见[加密](#加密);嵌入网关沿用 Server 的设置 |-| `public_url` | 两者 | 空 | 客户端访问的对外地址,不带 `/gateway`(网关自己加);嵌入时为空则沿用 Server 的对外地址;都没有时接入指南用请求来源地址,文件上传不可用 |+| `public_url` | 两者 | 空 | 客户端访问的对外地址,不带 `/gateway`(网关自己加);嵌入时为空则沿用 Server 的对外地址;都没有时接入指南用请求来源地址,MCP 文件上传和下载也不可用(`mcp_file_links` 为 `direct` 时除外) |+| `mcp_file_links` | 两者 | `proxy` | MCP 上传和下载工具返回的链接如何交给客户端:`proxy` 改写为 `public_url` 加 `/gateway/uploads` 或 `/gateway/downloads`,需要设置 `public_url`;`direct` 原样透传 OpenViking 的链接,需要 Server 的 `OPENVIKING_PUBLIC_BASE_URL`(或 `server.public_base_url`)是客户端能访问的地址 || `storage_path` | 两者 | `~/.openviking/gateway` | 本地存储目录 || `management_key` | 两者 | 空 | 可选的网关管理密钥,至少 32 个字符 || `min_server_version` | 两者 | `0.4.16` | 独立网关要求的 OpenViking Server 最低版本 |@@ -880,12 +883,12 @@ URL 必须是 HTTP(S),不能含凭证、查询参数或 fragment。未知字- **对话所用的上下文配置关闭了压缩。** 修改配置只对新对话生效。- **压缩失败。** 请求详情会显示原因,网关 60 秒后再试。摘要总因长度上限被截断时,调大**摘要长度上限**。原因是 `still_over_threshold` 时,说明系统提示词、工具和摘要本身就占满了大部分窗口:调小**摘要长度上限**,或者检查模型的上下文窗口设置。-### 文件导入失败+### 文件导入或下载失败-- "Set gateway.public_url for client uploads":把 `public_url` 设为客户端能访问的地址。-- 上传链接无法访问或返回 404:确认 `public_url` 不是旧的 `:1935` 地址,也没有以 `/gateway` 结尾,并且代理像其他路径一样转发 `/gateway/uploads`。+- "Set gateway.public_url for client uploads and downloads":把 `public_url` 设为客户端能访问的地址,或者把 `mcp_file_links` 设为 `direct`。+- 上传或下载链接无法访问或返回 404:确认 `public_url` 不是旧的 `:1935` 地址,也没有以 `/gateway` 结尾,并且代理像其他路径一样转发 `/gateway/uploads` 和 `/gateway/downloads`。`mcp_file_links` 设为 `direct` 时,改查 Server 的 `OPENVIKING_PUBLIC_BASE_URL`。- 413:文件超过了 `max_body_bytes` 或代理的上限。-- 502 "OpenViking upload is unavailable":网关连不上 OpenViking Server。+- 502 "OpenViking upload is unavailable" 或 "OpenViking download is unavailable":网关连不上 OpenViking Server。- 模型没有导入工具:OpenViking 服务没有提供该工具,上下文配置没有勾选,或者当前请求不能使用网关工具。检查工具清单和请求详情。### 降级请求的异常diff --git a/examples/opencode-plugin/INSTALL-ZH.md b/examples/opencode-plugin/INSTALL-ZH.mdindex fa779ad3a..81eac8667 100644--- a/examples/opencode-plugin/INSTALL-ZH.md+++ b/examples/opencode-plugin/INSTALL-ZH.md@@ -178,7 +178,7 @@ OpenCode 的 `mcp.openviking` 配置。进入新的 OpenCode session 后,可以让 agent 浏览 OpenViking memory,或搜索一个已索引的资源。插件应暴露 OpenViking MCP server,OpenCode 中的工具名会带 `openviking_` 前缀:- `openviking_search`、`openviking_find`-- `openviking_read`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`+- `openviking_read`、`openviking_download`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`- `openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`、`openviking_add_skill`- `openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`@@ -203,6 +203,7 @@ curl http://localhost:1933/health- `openviking_find`:快速语义检索- `openviking_remember`:存储重要事实或决策,供记忆提取- `openviking_read`:读取一个或多个 `viking://` 文件+- `openviking_download`:获取一次性 URL,用 `curl` 下载文件原始字节- `openviking_list`:列出 `viking://` 目录- `openviking_tree`:展示 `viking://` 目录树- `openviking_grep`:精确文本或正则搜索diff --git a/examples/opencode-plugin/INSTALL.md b/examples/opencode-plugin/INSTALL.mdindex b90bf80a2..fa0ea490c 100644--- a/examples/opencode-plugin/INSTALL.md+++ b/examples/opencode-plugin/INSTALL.md@@ -175,7 +175,7 @@ Restart OpenCode after changing plugin or OpenViking configuration.In a new OpenCode session, ask the agent to browse OpenViking memory or search for a known indexed resource. The plugin should expose the OpenViking MCP server, with tools namespaced by OpenCode as `openviking_*`:- `openviking_search`, `openviking_find`-- `openviking_read`, `openviking_list`, `openviking_tree`, `openviking_grep`, `openviking_glob`+- `openviking_read`, `openviking_download`, `openviking_list`, `openviking_tree`, `openviking_grep`, `openviking_glob`- `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`, `openviking_add_skill`- `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`@@ -200,6 +200,7 @@ The plugin registers OpenViking's stdio MCP proxy through OpenCode config. The s- `openviking_find`: fast semantic retrieval.- `openviking_remember`: store important facts or decisions for memory extraction.- `openviking_read`: read one or more `viking://` files.+- `openviking_download`: get a one-time URL for fetching a file's original bytes with `curl`.- `openviking_list`: list a `viking://` directory.- `openviking_tree`: show a `viking://` directory tree.- `openviking_grep`: exact text or regex search.diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.mdindex b4655c5ea..3a360e28a 100644--- a/examples/opencode-plugin/README.md+++ b/examples/opencode-plugin/README.md@@ -226,6 +226,7 @@ OpenCode sees the OpenViking MCP server as `openviking`, so tool names are names- `openviking_find`: fast semantic retrieval.- `openviking_remember`: store important facts or decisions for memory extraction.- `openviking_read`: read one or more `viking://` files.+- `openviking_download`: get a one-time URL for fetching a file's original bytes with `curl`.- `openviking_list`: list a `viking://` directory.- `openviking_tree`: show a `viking://` directory tree.- `openviking_grep`: exact text or regex search.diff --git a/examples/pi-coding-agent-extension/README.md b/examples/pi-coding-agent-extension/README.mdindex 62799e5da..71b6960e0 100644--- a/examples/pi-coding-agent-extension/README.md+++ b/examples/pi-coding-agent-extension/README.md@@ -306,13 +306,14 @@ Tool capture preserves structured tool parts with bounded inputs and outputs. ThThe extension keeps no tool catalogue of its own. At session start it asks the server's `/mcp` endpoint for `tools/list` and registers one pi tool per descriptor it gets back, named `openviking_` + the server's own name, with the server's description and argument schema. A server that gains, drops or re-documents a tool changes pi's tool surface at the next session, with no extension release.-Against a current server, that is these 15:+Against a current server, that is these 16:| Tool | Description ||-----------------------------|-------------------------------------------------------------------------|| `openviking_find` | Fast ranked retrieval across memories, resources and skills || `openviking_search` | Deep retrieval with session context and intent analysis; `mode="context"` returns an assembled block || `openviking_read` | Read one or more `viking://` file URIs, with line-based `offset`/`limit` |+| `openviking_download` | Get a one-time URL for fetching a file's original bytes with `curl` || `openviking_list` | List one sorted page under a `viking://` directory || `openviking_tree` | Show a recursive directory tree, optionally with abstracts || `openviking_remember` | Submit messages for long-term memory extraction; returns the background extraction `task_id` right away |diff --git a/openviking/server/auth/__init__.py b/openviking/server/auth/__init__.pyindex 2230371a9..46b72e95e 100644--- a/openviking/server/auth/__init__.py+++ b/openviking/server/auth/__init__.py@@ -13,7 +13,12 @@ from openviking.server.identity import (ResolvedIdentity,Role,)-from openviking.server.upload_token_store import UploadTokenError, upload_token_store+from openviking.server.upload_token_store import (+ ConsumedUploadToken,+ UploadTokenError,+ download_token_store,+ upload_token_store,+)from openviking.telemetry.span_models import update_root_span_identityfrom openviking_cli.exceptions import (FailedPreconditionError,@@ -205,6 +210,53 @@ async def get_session_request_context()+async def _context_from_signed_token(+ request: Request, consumed: ConsumedUploadToken+) -> RequestContext:+ """Rebuild the request context bound to a consumed upload/download token.++ 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.+ """+ if _auth_mode(request) == AuthMode.API_KEY:+ manager = get_api_key_manager_or_raise(request)+ current_role = await manager.get_registered_user_role(consumed.account_id, consumed.user_id)+ if current_role is None:+ raise UnauthenticatedError("Signed token's user no longer exists")+ if Role(consumed.role).rank > current_role.rank:+ raise UnauthenticatedError(+ "Signed token's role exceeds the user's current role; request a new token"+ )+ return await _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),+ role=Role.USER,+ group_ids=await resolve_group_ids(request, consumed.account_id, consumed.user_id),+ # Actor peer comes from the token (bound at mint time from the trusted MCP+ # context), never from this request's headers, so server-side+ # auto-ingest keeps the caller's peer scope for reason-memory routing.+ actor_peer_id=consumed.actor_peer_id or None,+ )+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=f"invalid identity in token: {exc}") from exc+ update_root_span_identity(+ request_state=request.state,+ account_id=consumed.account_id,+ user_id=consumed.user_id,+ )+ return ctx++async def get_upload_request_context(request: Request,token: Optional[str] = Query(None),@@ -231,47 +283,7 @@ 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)- current_role = await manager.get_registered_user_role(- consumed.account_id, consumed.user_id- )- if current_role is None:- raise UnauthenticatedError("Upload token's user no longer exists")- 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 await _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),- role=Role.USER,- group_ids=await resolve_group_ids(request, consumed.account_id, consumed.user_id),- # Actor peer comes from the token (bound at mint time from the trusted MCP- # context), never from this upload request's headers, so server-side- # auto-ingest keeps the caller's peer scope for reason-memory routing.- actor_peer_id=consumed.actor_peer_id or None,- )- except ValueError as exc:- raise HTTPException(- status_code=400, detail=f"invalid identity in token: {exc}"- ) from exc- update_root_span_identity(- request_state=request.state,- account_id=consumed.account_id,- user_id=consumed.user_id,- )- return ctx+ return await _context_from_signed_token(request, consumed)identity = await resolve_identity(request, x_api_key, authorization, x_openviking_account, x_openviking_user@@ -279,6 +291,38 @@ async def get_upload_request_context(return await get_request_context(request, identity, x_openviking_actor_peer)+async def get_download_request_context(+ request: Request,+ token: Optional[str] = Query(None),+ x_api_key: Optional[str] = Header(None),+ authorization: Optional[str] = Header(None),+ x_openviking_account: Optional[str] = Header(None, alias="X-OpenViking-Account"),+ x_openviking_user: Optional[str] = Header(None, alias="X-OpenViking-User"),+ x_openviking_actor_peer: Optional[str] = Header(None, alias="X-OpenViking-Actor-Peer"),+) -> RequestContext:+ """Two-layer auth for ``GET /content/download``: API key first, else a signed token.++ Mirrors :func:`get_upload_request_context`. A download token (minted by the MCP+ ``download`` tool) is single-use and bound to one resolved URI, which is stashed on+ ``request.state.signed_download_uri``; the handler serves only that URI.+ """+ api_key = _extract_api_key(x_api_key, authorization)+ if token and not api_key:+ try:+ consumed = download_token_store.consume(token)+ except UploadTokenError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc+ request.state.signed_download_uri = consumed.uri+ return await _context_from_signed_token(request, consumed)++ identity = await resolve_identity(+ request, x_api_key, authorization, x_openviking_account, x_openviking_user+ )+ return await get_request_context(+ request, identity, x_openviking_actor_peer, x_api_key, authorization+ )++def require_role(*allowed_roles: Role):"""Dependency factory that checks role permission.diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.pyindex 9da7e4db3..4ef60297c 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -18,7 +18,9 @@ from __future__ import annotationsimport base64import contextvars+import dataclassesimport os+import shlexfrom contextlib import asynccontextmanagerfrom datetime import datetime, timezonefrom functools import wraps@@ -49,6 +51,7 @@ from openviking.core.uri_validation import (validate_request_viking_uri,)from openviking.parse.mode import ParseMode, normalize_parse_mode+from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundErrorfrom openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingModefrom openviking.retrieve.context_assembler import (DEFAULT_MAX_TOKENS,@@ -66,7 +69,8 @@ from openviking.server.auth import (should_expose_user_key,)from openviking.server.dependencies import get_server_config, get_service-from openviking.server.identity import RequestContext, Role+from openviking.server.error_mapping import map_exception+from openviking.server.identity import AuthMode, RequestContext, Rolefrom openviking.server.local_input_guard import (TEMP_FILE_ID_RE,is_remote_resource_source,@@ -76,7 +80,7 @@ from openviking.server.resource_ingest import ingest_temp_uploadfrom openviking.server.routers.search import context_only_fields_errorfrom openviking.server.skill_ingest import install_skillsfrom openviking.server.temp_upload_store import TempUploadStore-from openviking.server.upload_token_store import upload_token_store+from openviking.server.upload_token_store import download_token_store, upload_token_storefrom openviking.service.skill_sources import GIT_SKILL_SOURCE_PREFIXESfrom openviking.storage.acl import AclSpecfrom openviking.utils.media_limits import MAX_INLINE_TOOL_RESULT_MEDIA_BYTES@@ -835,10 +839,9 @@ def _mcp_media_download_hint(uri: str) -> str:"""Return actionable fallbacks when media cannot be inlined."""path = uri.split("#", 1)[0].split("?", 1)[0]filename = PurePosixPath(path).name or "download"- encoded_uri = quote(uri, safe="")return (- f'Use `ov get "{uri}" "./{filename}"` or GET '- f"`/api/v1/content/download?uri={encoded_uri}` to fetch the original file."+ f'Call the download tool with uri="{uri}" for a temporary curl-able URL, '+ f'or use `ov get "{uri}" "./{filename}"` to fetch the original file.')@@ -992,6 +995,110 @@ async def read(return combined+# -- download --------------------------------------------------------------+++def _human_size(size: int) -> str:+ if size < 1024:+ return f"{size} B"+ value = size / 1024+ for unit in ("KB", "MB"):+ if value < 1024:+ return f"{value:.1f} {unit}"+ value /= 1024+ return f"{value:.1f} GB"+++@_mcp_error_results()[email protected](annotations=_READ_ONLY_TOOL_ANNOTATIONS)+async def download(uri: str) -> str:+ """Get a short-lived URL for downloading the original bytes of one file (any type, including PDF, images, archives, audio and video). It does not return the content; use `read` to read text. Fetch the URL with `curl -fL -o <local path> <url>`; no OpenViking API key is needed. The link works once and expires in about 10 minutes; call download again for a new link. Directories are not supported: use `list` or `tree` and download files one at a time."""+ service = get_service()+ ctx = _get_ctx()+ resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)+ server_config = get_server_config()+ stat_ctx = ctx+ if (+ server_config is not None+ and server_config.get_effective_auth_mode() != AuthMode.API_KEY.value+ and ctx.role != Role.USER+ ):+ # Outside API-key mode the token fetch runs as USER, so check with that authority.+ stat_ctx = dataclasses.replace(ctx, role=Role.USER)+ try:+ stat = await service.fs.stat(resolved_uri, ctx=stat_ctx, skip_count=True)+ except AGFSNotFoundError as exc:+ raise NotFoundError(resolved_uri, "file") from exc+ except AGFSClientError as exc:+ mapped = map_exception(exc, resource=resolved_uri, resource_type="file")+ if mapped is not None:+ raise mapped from exc+ raise+ if stat.get("isDir"):+ return _mcp_failure(+ f"Cannot download {uri}: URI points to a directory. Downloads are per-file: "+ "use the list or tree tool to find files and download them one at a time."+ )++ ttl_seconds = (+ server_config.upload_signed_ttl_seconds+ if server_config is not None+ else _DEFAULT_UPLOAD_TTL_SECONDS+ )+ token, expires_at = download_token_store.issue(+ 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 "",+ uri=resolved_uri,+ )+ base_url, url_source = _resolve_public_base_url()+ download_url = f"{base_url}/api/v1/content/download?token={quote(token, safe='')}"+ expires_iso = datetime.fromtimestamp(expires_at, tz=timezone.utc).isoformat(timespec="seconds")+ minutes = max(1, ttl_seconds // 60)+ filename = stat.get("name") or PurePosixPath(resolved_uri).name or "download"+ size = stat.get("size")+ details = (+ f"{filename}, {_human_size(size)}"+ if isinstance(size, int) and not isinstance(size, bool) and size >= 0+ else filename+ )++ prose = (+ f"Download link for {resolved_uri} ({details}):\n"+ "\n"+ f" curl -fL -o {shlex.quote('./' + filename)} {shlex.quote(download_url)}\n"+ "\n"+ "Choose any local path for -o. The URL's token authorizes this one download against "+ "OpenViking itself (no OpenViking API key needed). It works once: if the fetch fails, "+ "call download again for a new link.\n"+ "\n"+ "If the OpenViking server sits behind a private gateway or reverse proxy that "+ "requires extra request headers (e.g. `openviking_name`, tenant/vault headers, "+ "or a gateway API key), those headers are enforced on every request including "+ "this download — replay the same headers you use for MCP calls when fetching the "+ "file. A gateway rejection typically looks like HTTP 400/401/403 before the "+ "token is even checked.\n"+ "\n"+ f"This download URL expires in ~{minutes} minutes ({expires_iso})."+ )++ if url_source not in ("env", "config"):+ prose += (+ "\n\n"+ "Note for the user: this download URL was auto-detected from the incoming "+ "request because OPENVIKING_PUBLIC_BASE_URL is not set on the server. "+ "If the download fails (connection refused, wrong host, TLS error), ask the "+ "server operator to set OPENVIKING_PUBLIC_BASE_URL to the agent-facing "+ "URL of the OpenViking server (e.g. via docker-compose `environment:` "+ "or systemd unit) and retry."+ )++ return prose++# -- list ------------------------------------------------------------------@@ -1272,9 +1379,7 @@ async def edit(updated = current.replace(old_string, new_string)if updated == current:return f"No changes: {uri} already matches the requested edit."- result = await service.fs.write(- uri=uri, content=updated, ctx=ctx, mode="replace", wait=wait- )+ result = await service.fs.write(uri=uri, content=updated, ctx=ctx, mode="replace", wait=wait)written = result.get("written_bytes", 0)message = f"Edited {result.get('uri', uri)} ({written} bytes written)."return message + _indexing_hint(result)diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.pyindex eb212d023..8372f6c7d 100644--- a/openviking/server/routers/content.py+++ b/openviking/server/routers/content.py@@ -2,10 +2,10 @@# SPDX-License-Identifier: AGPL-3.0"""Content endpoints for OpenViking HTTP Server."""-from typing import Literal+from typing import Literal, Optionalfrom urllib.parse import quote-from fastapi import APIRouter, Body, Depends, Query+from fastapi import APIRouter, Body, Depends, HTTPException, Query, Requestfrom fastapi.responses import Response as FastAPIResponsefrom pydantic import BaseModel, ConfigDict, Field, model_validator@@ -19,6 +19,7 @@ from openviking.core.uri_validation import validate_request_viking_urifrom openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundErrorfrom openviking.resource.processing_mode import DEFAULT_PROCESSING_MODE, ProcessingModefrom openviking.server.auth import (+ get_download_request_context,get_request_context,require_role,)@@ -202,10 +203,20 @@ async def overview(@router.get("/download")async def download(- uri: str = Query(..., description="Viking URI"),- _ctx: RequestContext = Depends(get_request_context),+ request: Request,+ uri: Optional[str] = Query(None, description="Viking URI"),+ _ctx: RequestContext = Depends(get_download_request_context),):- """Download file as raw bytes (for images, binaries, etc.)."""+ """Download file as raw bytes (for images, binaries, etc.).++ A signed ``?token=`` from the MCP ``download`` tool serves only the URI bound to the+ token; any ``uri`` query parameter is ignored on that path.+ """+ signed_uri = getattr(request.state, "signed_download_uri", None)+ if signed_uri is not None:+ uri = signed_uri+ if not uri:+ raise HTTPException(status_code=400, detail="uri is required")service = get_service()uri = validate_request_viking_uri(resolve_path_variables(uri), _ctx)try:diff --git a/openviking/server/upload_token_store.py b/openviking/server/upload_token_store.pyindex 648b7356f..f012e50a2 100644--- a/openviking/server/upload_token_store.py+++ b/openviking/server/upload_token_store.py@@ -4,7 +4,7 @@Issued by the MCP ``add_resource`` tool when a caller passes a local-file path; consumed by``POST /api/v1/resources/temp_upload`` when the request carries a ``?token=`` instead of an-API key. Tokens are 6-character base62 strings indexed in a process-local dict — no signing+API key. Tokens are 10-character base62 strings indexed in a process-local dict — no signingkey, no on-disk state, no replay-set bookkeeping. ``dict.pop`` doubles as theconsume-and-burn primitive.@@ -19,6 +19,11 @@ is installed as skills rather than ingested as a resource. The ``temp_file_id``does not pre-bind a filename and the upload can flow through either the local or sharedTempUploadStore mode without a side-channel.+``download_token_store`` is a separate instance used by the MCP ``download`` tool: its tokens+carry the resolved ``uri`` of one file and are consumed by ``GET /api/v1/content/download``.+Keeping the two stores apart means an upload token can never be redeemed for a download, or+the reverse.+Single-worker only: tokens are lost on restart and not shared across uvicorn workers.Multi-worker deployments should rely on the shared-mode TempUploadStore for the actualfile payload; only the brief upload-token handshake is process-local.@@ -37,7 +42,7 @@ from openviking.server.identity import Rolefrom openviking.storage.acl import AclSpec_TOKEN_ALPHABET = string.ascii_letters + string.digits # base62-_TOKEN_LENGTH = 6+_TOKEN_LENGTH = 10class UploadTokenError(Exception):@@ -64,6 +69,7 @@ class _TokenInfo:list_only: bool = Falseacl: AclSpec | None = Nonefrom_oauth: bool = False+ uri: str = ""@dataclass(frozen=True)@@ -87,6 +93,7 @@ class ConsumedUploadToken:list_only: bool = Falseacl: AclSpec | None = Nonefrom_oauth: bool = False+ uri: str = ""class UploadTokenStore:@@ -114,6 +121,7 @@ class UploadTokenStore:list_only: bool = False,acl: AclSpec | None = None,from_oauth: bool = False,+ uri: str = "",) -> Tuple[str, float]:"""Mint a fresh token bound to the caller identity and ingestion parameters.@@ -143,6 +151,7 @@ class UploadTokenStore:list_only,acl,from_oauth,+ uri,)for _ in range(8):token = "".join(secrets.choice(_TOKEN_ALPHABET) for _ in range(_TOKEN_LENGTH))@@ -178,6 +187,7 @@ class UploadTokenStore:list_only=info.list_only,acl=info.acl,from_oauth=info.from_oauth,+ uri=info.uri,)def peek(self, token: str) -> Optional[_TokenInfo]:@@ -196,3 +206,4 @@ class UploadTokenStore:upload_token_store = UploadTokenStore()+download_token_store = UploadTokenStore()diff --git a/openviking_gateway/app.py b/openviking_gateway/app.pyindex 25ba79310..2602c0b2a 100644--- a/openviking_gateway/app.py+++ b/openviking_gateway/app.py@@ -255,6 +255,27 @@ def create_app(config: GatewayConfig, *, openviking_url: str, vlm_source=None, eexcept (aiohttp.ClientError, asyncio.TimeoutError):raise HTTPException(502, "OpenViking upload is unavailable")+ @app.get("/downloads")+ async def proxy_download(request: Request):+ token = request.query_params.get("token", "")+ if not token or len(token) > 16384:+ raise HTTPException(400, "A signed download token is required")+ try:+ async with app.state.http.get(+ openviking_url + "/api/v1/content/download",+ params={"token": token},+ headers={"accept-encoding": "identity"},+ timeout=aiohttp.ClientTimeout(total=120),+ allow_redirects=False,+ ) as response:+ return Response(+ await response.read(),+ status_code=response.status,+ headers=filtered_headers(response.headers),+ )+ except (aiohttp.ClientError, asyncio.TimeoutError):+ raise HTTPException(502, "OpenViking download is unavailable")+@app.api_route("/v1/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"])@app.api_route("/api/v3/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"])@app.api_route(diff --git a/openviking_gateway/config.py b/openviking_gateway/config.pyindex 8444b2dcc..ac23d425a 100644--- a/openviking_gateway/config.py+++ b/openviking_gateway/config.py@@ -5,7 +5,7 @@import loggingimport osfrom pathlib import Path-from typing import ClassVar+from typing import ClassVar, Literalfrom urllib.parse import urlsplit, urlunsplitfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator@@ -40,6 +40,7 @@ class GatewayConfig(BaseModel):removed_fields: ClassVar[frozenset[str]] = frozenset({"encryption_key_env"})public_url: str = ""+ mcp_file_links: Literal["proxy", "direct"] = "proxy"storage_path: str = "~/.openviking/gateway"management_key: str = Field(default="", repr=False)min_server_version: str = "0.4.16"diff --git a/openviking_gateway/proxy.py b/openviking_gateway/proxy.pyindex d2fec24da..bad57498b 100644--- a/openviking_gateway/proxy.py+++ b/openviking_gateway/proxy.py@@ -403,6 +403,7 @@ class ProxyRequest:self.credential,self.config.public_url,self.config.max_body_bytes,+ self.config.mcp_file_links,)loop = HiddenToolLoop(prepared, executor, self.store, capture)headers = {diff --git a/openviking_gateway/tool_catalog.py b/openviking_gateway/tool_catalog.pyindex 3f26ba4d9..85ac9cb78 100644--- a/openviking_gateway/tool_catalog.py+++ b/openviking_gateway/tool_catalog.py@@ -13,11 +13,15 @@ from .tool_protocols.common import PREFIXfrom .windows import native_definitions# Only what the gateway adds to MCP: the arguments a notice names, in order of-# preference, and the attachment upload hook with its usage note.+# preference, the attachment upload hook, and usage notes.TOOL_OVERRIDES = {"find": {"notice": ("query",)},"search": {"notice": ("query",)},"read": {"notice": ("uris",)},+ "download": {+ "notice": ("uri",),+ "description": " Run the returned curl command with the client's shell tool.",+ },"list": {"notice": ("uri",)},"write": {"notice": ("uri",)},"add_resource": {diff --git a/openviking_gateway/tool_executor.py b/openviking_gateway/tool_executor.pyindex a4861e6e6..1c7b15949 100644--- a/openviking_gateway/tool_executor.py+++ b/openviking_gateway/tool_executor.py@@ -1,6 +1,6 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Bounded, user-authenticated MCP calls, native tools and signed file upload handoff."""+"""Bounded, user-authenticated MCP calls, native tools and signed file link handoff."""import asyncioimport base64@@ -27,6 +27,14 @@ from .windows import NATIVE_TOOLSUPLOAD_URL = re.compile(r'https?://[^\s<>"\x27`]+/api/v1/resources/temp_upload\?token=[^\s<>"\x27`]+')+DOWNLOAD_URL = re.compile(r'https?://[^\s<>"\x27`]+/api/v1/content/download\?token=[^\s<>"\x27`]+')+AUTO_DETECTED_NOTE = re.compile(+ r"\n*Note for the user: this (?:upload|download) URL was auto-detected[^\n]*"+)+++def error_result(text):+ return {"content": [{"type": "text", "text": text}], "isError": True}def has_shell(body):@@ -99,10 +107,10 @@ def content_blocks(result):return blocks-def upload_token(result):+def signed_token(result, pattern):for block in content_blocks(result):if block.get("type") == "text":- match = UPLOAD_URL.search(block.get("text", ""))+ match = pattern.search(block.get("text", ""))if match:return parse_qs(urlsplit(match[0]).query).get("token", [""])[0]return ""@@ -153,10 +161,13 @@ def result_text(result, limit):class ToolExecutor:- def __init__(self, viking, store, prepared, credential, public_url, max_upload_bytes):+ def __init__(+ self, viking, store, prepared, credential, public_url, max_upload_bytes, file_links="proxy"+ ):self.viking, self.store, self.request = viking, store, preparedself.credential, self.key = credential, credential["openviking_key"]self.public_url, self.max_upload_bytes = public_url.rstrip("/"), max_upload_bytes+ self.file_links = file_linksself.policy = prepared.root["policy"]self.schemas = {t["function"]["name"]: t["function"]["parameters"] for t in prepared.root["tools"]@@ -258,8 +269,16 @@ class ToolExecutor:self.request.original):raise ValueError("A local path requires a client shell or attachment")+ elif name == "download" and not has_shell(self.request.original):+ return error_result("download requires a client shell tool to fetch the file")value = await self.viking.mcp("tools/call", self.key, {"name": name, "arguments": args})- token = upload_token(value) if upload else ""+ if upload:+ pattern, route = UPLOAD_URL, "/uploads"+ elif name == "download":+ pattern, route = DOWNLOAD_URL, "/downloads"+ else:+ pattern, route = None, ""+ token = signed_token(value, pattern) if pattern else ""if file:if not token or value.get("isError"):raise VikingError("upload_instruction_missing")@@ -268,11 +287,12 @@ class ToolExecutor:"content": [{"type": "text", "text": orjson.dumps(uploaded).decode()}],"isError": uploaded.get("status") == "error" or bool(uploaded.get("error")),}- if token:+ if token and self.file_links == "proxy":if not self.public_url:- raise ValueError("Set gateway.public_url for client uploads")- url = self.public_url + MOUNT_PATH + "/uploads?token=" + quote(token, safe="")+ return error_result("Set gateway.public_url for client uploads and downloads")+ url = self.public_url + MOUNT_PATH + route + "?token=" + quote(token, safe="")for block in value.get("content", []):if block.get("type") == "text":- block["text"] = UPLOAD_URL.sub(lambda _: url, block["text"])+ text = AUTO_DETECTED_NOTE.sub("", block["text"])+ block["text"] = pattern.sub(lambda _: url, text)return valuediff --git a/tests/gateway/test_app.py b/tests/gateway/test_app.pyindex f750bfab1..3e09d56e5 100644--- a/tests/gateway/test_app.py+++ b/tests/gateway/test_app.py@@ -6,7 +6,7 @@ from pathlib import Pathimport orjsonimport pytestfrom aiohttp import web-from conftest import MCP_TOOLS+from conftest import MCP_TOOLS, TEXT, mcp_toolfrom openviking_gateway.capture import ready_atfrom openviking_gateway.protocols import normalize@@ -814,6 +814,148 @@ async def test_shell_upload_instructions_use_public_proxy(running_gateway):assert response.json()["choices"][0]["message"]["tool_calls"][0]["function"]["name"] == "bash"+OV_DOWNLOAD = "http://private-ov/api/v1/content/download?token=AbC123xyz_"+OV_UPLOAD = "http://private-ov/api/v1/resources/temp_upload?token=signed-once"+OV_NOTE = (+ "\n\nNote for the user: this download URL was auto-detected from the incoming request "+ "because OPENVIKING_PUBLIC_BASE_URL is not set on the server."+)+++async def gateway_tool_result(running_gateway, session, name, arguments, mcp_text, shell=True):+ """Run one gateway tool call; return its result as the model sees it and the MCP calls."""+ app, client, _, key, _, _ = running_gateway+ app.state.test_backend["catalog"] = [*MCP_TOOLS, mcp_tool("download", {"uri": TEXT}, ("uri",))]+ model_requests, mcp_calls = [], []++ async def backend(request):+ if request.path == "/mcp":+ mcp_calls.append((await request.json())["params"])+ return web.json_response(+ {"id": 1, "result": {"content": [{"type": "text", "text": mcp_text}]}}+ )+ if request.path == "/v1/chat/completions":+ model_requests.append(await request.json())+ if len(model_requests) == 1:+ return web.json_response(+ completion(+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [tool_call("openviking_" + name, arguments=arguments)],+ },+ "tool_calls",+ )+ )+ return web.json_response(completion({"role": "assistant", "content": "Done."}))+ return None++ app.state.test_backend["handler"] = backend+ body = {"model": "model", "messages": [{"role": "user", "content": "fetch it"}]}+ if shell:+ body["tools"] = [{"type": "function", "function": {"name": "bash"}}]+ response = await client.post(+ "/v1/chat/completions",+ headers={"Authorization": "Bearer " + key["key"], "X-OpenViking-Session": session},+ json=body,+ )+ assert response.status_code == 200, response.text+ return model_requests[1]["messages"][-1]["content"], mcp_calls+++async def test_download_link_uses_public_proxy(running_gateway):+ app, client, admin, _, _, _ = running_gateway+ app.state.config.public_url = "https://gateway.example"+ await enable_tools(client, admin)+ result, _ = await gateway_tool_result(+ running_gateway,+ "download",+ "download",+ {"uri": "viking://resources/a.pdf"},+ f"Download link:\n\n curl -fL -o ./a.pdf '{OV_DOWNLOAD}'" + OV_NOTE,+ )+ assert "curl -fL -o ./a.pdf 'https://gateway.example/gateway/downloads?token=AbC123xyz_'" in (+ result+ )+ assert "private-ov" not in result and "OPENVIKING_PUBLIC_BASE_URL" not in result+ fetched = []++ async def backend(request):+ if request.path == "/api/v1/content/download":+ fetched.append(dict(request.query))+ assert "Authorization" not in request.headers and "X-API-Key" not in request.headers+ if request.query["token"] != "AbC123xyz_":+ return web.json_response({"error": "invalid token"}, status=401)+ return web.Response(+ body=b"%PDF-1.7 bytes",+ content_type="application/pdf",+ headers={"Content-Disposition": 'attachment; filename="a.pdf"'},+ )+ return None++ app.state.test_backend["handler"] = backend+ response = await client.get(+ "/downloads?token=AbC123xyz_&uri=viking://resources/other.pdf",+ headers={"Authorization": "Bearer not-forwarded"},+ )+ assert response.status_code == 200, response.text+ assert response.content == b"%PDF-1.7 bytes"+ assert response.headers["content-type"] == "application/pdf"+ assert response.headers["content-disposition"] == 'attachment; filename="a.pdf"'+ assert fetched == [{"token": "AbC123xyz_"}]+ response = await client.get("/downloads?token=expired")+ assert response.status_code == 401 and response.json() == {"error": "invalid token"}+ assert (await client.get("/downloads")).status_code == 400+++async def test_direct_file_links_pass_through(running_gateway):+ app, client, admin, _, _, _ = running_gateway+ app.state.config.public_url = ""+ app.state.config.mcp_file_links = "direct"+ await enable_tools(client, admin)+ result, _ = await gateway_tool_result(+ running_gateway,+ "direct-download",+ "download",+ {"uri": "viking://a.pdf"},+ OV_DOWNLOAD + OV_NOTE,+ )+ assert result == OV_DOWNLOAD + OV_NOTE+ result, _ = await gateway_tool_result(+ running_gateway,+ "direct-upload",+ "add_resource",+ {"path": "/home/client/file.md"},+ "POST to " + OV_UPLOAD,+ )+ assert result == "POST to " + OV_UPLOAD+++async def test_proxied_download_requires_public_url(running_gateway):+ app, client, admin, _, _, _ = running_gateway+ app.state.config.public_url = ""+ await enable_tools(client, admin)+ result, mcp_calls = await gateway_tool_result(+ running_gateway, "download", "download", {"uri": "viking://a.pdf"}, OV_DOWNLOAD+ )+ assert result == "Set gateway.public_url for client uploads and downloads"+ assert len(mcp_calls) == 1+++async def test_download_requires_client_shell(running_gateway):+ _, client, admin, _, _, _ = running_gateway+ await enable_tools(client, admin)+ result, mcp_calls = await gateway_tool_result(+ running_gateway,+ "download",+ "download",+ {"uri": "viking://a.pdf"},+ OV_DOWNLOAD,+ shell=False,+ )+ assert "requires a client shell" in result and mcp_calls == []++@pytest.mark.parametrize("vendor", ["ark", "byteplus"])async def test_ark_responses_stream_keeps_native_fields_and_done(running_gateway, vendor):app, client, admin, key, _, _ = running_gatewaydiff --git a/tests/gateway/test_gateway_config.py b/tests/gateway/test_gateway_config.pyindex 8a849564f..ffe43afb9 100644--- a/tests/gateway/test_gateway_config.py+++ b/tests/gateway/test_gateway_config.py@@ -280,3 +280,17 @@ def test_public_url_normalization():assert ipv6.openviking_url == "http://[::1]:1933"with pytest.raises(ValidationError):StandaloneGatewayConfig(openviking_url="http://localhost:99999")+++def test_mcp_file_links_default_environment_and_validation(monkeypatch):+ assert GatewayConfig().mcp_file_links == "proxy"+ assert EmbeddedGatewayConfig(mcp_file_links="direct").mcp_file_links == "direct"+ monkeypatch.setenv("OPENVIKING_GATEWAY_MCP_FILE_LINKS", "direct")+ config = StandaloneGatewayConfig(openviking_url="http://openviking:1933")+ assert config.mcp_file_links == "direct"+ monkeypatch.setenv("OPENVIKING_GATEWAY_MCP_FILE_LINKS", "public")+ with pytest.raises(ValidationError):+ GatewayConfig()+ monkeypatch.delenv("OPENVIKING_GATEWAY_MCP_FILE_LINKS")+ with pytest.raises(ValidationError):+ GatewayConfig(mcp_file_links="public")diff --git a/tests/server/test_content_download_token.py b/tests/server/test_content_download_token.pynew file mode 100644index 000000000..d1c5f7235--- /dev/null+++ b/tests/server/test_content_download_token.py@@ -0,0 +1,228 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Tests for the signed-token path on GET /api/v1/content/download.++The MCP ``download`` tool mints a single-use ``?token=`` bound to the caller's identity and+one resolved file URI. A GET carrying that token (and no API key) serves only the bound file;+an API-key GET keeps the normal ``?uri=`` behavior used by ``ov get``.+"""++from __future__ import annotations++from types import SimpleNamespace+from urllib.parse import parse_qs, urlparse++import httpx+import pytest+from fastapi import FastAPI+from fastapi.responses import JSONResponse++from openviking.server import mcp_endpoint+from openviking.server.auth.plugins import ApiKeyAuthPlugin+from openviking.server.config import ServerConfig+from openviking.server.identity import RequestContext, Role+from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS+from openviking.server.routers import content as content_router+from openviking.server.routers import resources as resources_router+from openviking.server.upload_token_store import download_token_store, upload_token_store+from openviking_cli.exceptions import OpenVikingError, PermissionDeniedError+from openviking_cli.session.user_id import UserIdentifier++TARGET = "viking://resources/specs/design.pdf"+OTHER = "viking://resources/specs/secret.pdf"++[email protected](autouse=True)+def _reset_token_stores():+ upload_token_store.clear()+ download_token_store.clear()+ yield+ upload_token_store.clear()+ download_token_store.clear()+++class _FakeFS:+ def __init__(self):+ self.files = {TARGET: b"%PDF-design", OTHER: b"%PDF-secret"}+ self.denied: set[tuple[str, str]] = set()+ self.reads: list[tuple[str, RequestContext]] = []++ def _check(self, uri, ctx):+ if (uri, ctx.user.user_id) in self.denied:+ raise PermissionDeniedError(f"Access denied for {uri}")++ async def stat(self, uri, ctx, skip_count=False):+ self._check(uri, ctx)+ if uri.endswith("/specs"):+ return {"name": "specs", "size": 0, "isDir": True}+ return {"name": uri.rsplit("/", 1)[-1], "size": len(self.files[uri]), "isDir": False}++ async def read_file_bytes(self, uri, ctx):+ self._check(uri, ctx)+ self.reads.append((uri, ctx))+ return self.files[uri]+++async def api_key_manager():+ from openviking.server.store_assembly import build_api_key_manager+ from tests.server.account_store_fakes import InMemoryAGFS++ manager = build_api_key_manager("test-root", SimpleNamespace(agfs=InMemoryAGFS()))+ await manager.load()+ try:+ await manager.create_account("acct", "owner")+ manager.user_key = await manager.register_user("acct", "user", Role.ADMIN)+ yield manager+ finally:+ await manager.close()+++def fake_fs(monkeypatch, api_key_manager):+ fs = _FakeFS()+ service = SimpleNamespace(fs=fs)+ config = ServerConfig(auth_mode="api_key", root_api_key="test-root")+ monkeypatch.setattr(mcp_endpoint, "get_service", lambda: service)+ monkeypatch.setattr(mcp_endpoint, "get_server_config", lambda: config)+ monkeypatch.setattr(content_router, "get_service", lambda: service)+ monkeypatch.delenv("OPENVIKING_PUBLIC_BASE_URL", raising=False)+ return fs+++async def client(api_key_manager, fake_fs):+ app = FastAPI()+ app.state.config = ServerConfig(auth_mode="api_key", root_api_key="test-root")+ app.state.auth_plugin = ApiKeyAuthPlugin()+ app.state.api_key_manager = api_key_manager+ app.include_router(content_router.router)+ app.include_router(resources_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}+ )++ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://test"+ ) as c:+ yield c+++def _identity(role: Role = Role.ADMIN) -> RequestContext:+ return RequestContext(UserIdentifier("acct", "user"), role, actor_peer_id="bot-a")+++async def _mint(uri: str = TARGET, identity: RequestContext | None = None) -> str:+ token = mcp_endpoint._mcp_ctx.set(identity or _identity())+ try:+ result = await mcp_endpoint.download(uri=uri)+ finally:+ mcp_endpoint._mcp_ctx.reset(token)+ url = next(part for part in result.split() if "?token=" in part).strip("'")+ return parse_qs(urlparse(url).query)["token"][0]+++async def test_token_serves_bound_file_once_and_ignores_uri_param(client, fake_fs):+ token = await _mint()++ response = await client.get(+ "/api/v1/content/download",+ params={"token": token, "uri": OTHER},+ headers={"X-OpenViking-Account": "other", "X-OpenViking-User": "spoofed"},+ )+ assert response.status_code == 200, response.text+ assert response.content == b"%PDF-design"+ assert response.headers["content-type"] == "application/octet-stream"+ assert "filename*=UTF-8''design.pdf" in response.headers["content-disposition"]+ uri, ctx = fake_fs.reads[-1]+ assert uri == TARGET+ assert ctx.user == UserIdentifier("acct", "user")+ assert ctx.role == Role.ADMIN+ assert ctx.actor_peer_id == "bot-a"++ reused = await client.get("/api/v1/content/download", params={"token": token})+ assert reused.status_code == 401+++async def test_expired_token_is_rejected(client, monkeypatch):+ import openviking.server.upload_token_store as store_mod++ now = [1000.0]+ monkeypatch.setattr(store_mod.time, "time", lambda: now[0])+ token = await _mint()+ now[0] += 601++ response = await client.get("/api/v1/content/download", params={"token": token})+ assert response.status_code == 401+++async def test_upload_and_download_tokens_are_not_interchangeable(client, upload_temp_dir):+ upload_token, _ = upload_token_store.issue("acct", "user", role=Role.USER, ttl_seconds=600)+ response = await client.get("/api/v1/content/download", params={"token": upload_token})+ assert response.status_code == 401+ assert upload_token_store.peek(upload_token) is not None++ download_token = await _mint()+ response = await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": download_token},+ files={"file": ("x.md", b"x", "text/markdown")},+ )+ assert response.status_code == 401+ assert download_token_store.peek(download_token) is not None+++async def test_api_key_request_keeps_normal_path(client, api_key_manager, fake_fs):+ token = await _mint()++ response = await client.get(+ "/api/v1/content/download",+ params={"token": token, "uri": OTHER},+ headers={"X-API-Key": api_key_manager.user_key},+ )+ assert response.status_code == 200, response.text+ assert response.content == b"%PDF-secret"+ assert download_token_store.peek(token) is not None++ response = await client.get(+ "/api/v1/content/download", headers={"X-API-Key": api_key_manager.user_key}+ )+ assert response.status_code == 400+++async def test_token_loses_authority_after_role_downgrade_or_user_removal(client, api_key_manager):+ token = await _mint()+ await api_key_manager.set_role("acct", "user", Role.USER)+ assert (+ await client.get("/api/v1/content/download", params={"token": token})+ ).status_code == 401++ token = await _mint(identity=_identity(Role.USER))+ await api_key_manager.begin_deletion(+ "acct",+ "user",+ task_id="delete-download-user",+ owner_account_id="acct",+ owner_user_id="owner",+ )+ assert (+ await client.get("/api/v1/content/download", params={"token": token})+ ).status_code == 412++ token = await _mint(identity=_identity(Role.USER))+ assert await api_key_manager.finish_deletion("acct", "user", "delete-download-user")+ assert (+ await client.get("/api/v1/content/download", params={"token": token})+ ).status_code == 401+++async def test_access_is_rechecked_at_fetch(client, fake_fs):+ token = await _mint()+ fake_fs.denied.add((TARGET, "user"))++ response = await client.get("/api/v1/content/download", params={"token": token})+ assert response.status_code == 403+ assert fake_fs.reads == []diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 0f44ddbf8..4fa6dee1d 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -31,6 +31,7 @@ from openviking.server.mcp_endpoint import (add_resource,add_skill,cancel_watch,+ download,edit,forget,glob,@@ -1193,7 +1194,7 @@ async def test_read_rejects_images_too_large_for_common_clients(monkeypatch):assert "too large to inline" in resultassert 'ov get "viking://resources/huge.png" "./huge.png"' in result- assert "/api/v1/content/download?uri=viking%3A%2F%2Fresources%2Fhuge.png" in result+ assert 'Call the download tool with uri="viking://resources/huge.png"' in resultread_file_bytes.assert_not_awaited()@@ -1639,6 +1640,144 @@ async def test_add_resource_local_path_infers_from_x_forwarded_headers(service,upload_token_store.clear()+# ---------------------------------------------------------------------------+# download tool+# ---------------------------------------------------------------------------+++def _clear_download_tokens():+ from openviking.server.upload_token_store import download_token_store++ download_token_store.clear()+ yield download_token_store+ download_token_store.clear()+++def _stat_service(monkeypatch, stat):+ monkeypatch.setattr(+ mcp_endpoint, "get_service", lambda: SimpleNamespace(fs=SimpleNamespace(stat=stat))+ )+++async def test_download_tool_is_registered_read_only():+ tools = {tool.name: tool for tool in await mcp_endpoint.mcp.list_tools()}++ tool = tools["download"]+ assert set(tool.inputSchema["properties"]) == {"uri"}+ assert tool.annotations.readOnlyHint is True+ assert tool.description.startswith("Get a short-lived URL for downloading")+++async def test_download_mints_token_bound_to_identity_and_uri(monkeypatch, _clear_download_tokens):+ store = _clear_download_tokens+ stat = AsyncMock(return_value={"name": "design.pdf", "size": 2_516_582, "isDir": False})+ _stat_service(monkeypatch, stat)+ ctx = RequestContext(+ UserIdentifier("acct", "alice"), Role.USER, actor_peer_id="bot-a", from_oauth=True+ )+ monkeypatch.setenv("OPENVIKING_PUBLIC_BASE_URL", "https://ov.example.com/")+ token_ctx = _mcp_ctx.set(ctx)+ try:+ result = await download("viking://~/specs/design.pdf")+ finally:+ _mcp_ctx.reset(token_ctx)++ stat.assert_awaited_once_with("viking://user/alice/specs/design.pdf", ctx=ctx, skip_count=True)+ assert "viking://user/alice/specs/design.pdf (design.pdf, 2.4 MB)" in result+ match = re.search(+ r"curl -fL -o \./design\.pdf 'https://ov\.example\.com/api/v1/content/download"+ r"\?token=([A-Za-z0-9]+)'",+ result,+ )+ assert match, result+ assert "no OpenViking API key needed" in result+ assert "replay the same headers" in result+ assert "expires in ~10 minutes" in result+ assert "OPENVIKING_PUBLIC_BASE_URL is not set" not in result+ info = store.peek(match.group(1))+ assert info.uri == "viking://user/alice/specs/design.pdf"+ assert (info.account_id, info.user_id, info.role) == ("acct", "alice", Role.USER)+ assert info.actor_peer_id == "bot-a"+ assert info.from_oauth is True+++async def test_download_shell_quotes_untrusted_filename(monkeypatch, _clear_download_tokens):+ _stat_service(+ monkeypatch, AsyncMock(return_value={"name": "$(id).pdf", "size": 3, "isDir": False})+ )++ result = await download("viking://resources/$(id).pdf")++ assert "-o './$(id).pdf' " in result+++async def test_download_rejects_directory_without_minting(monkeypatch, _clear_download_tokens):+ _stat_service(monkeypatch, AsyncMock(return_value={"name": "specs", "isDir": True}))++ result = await download("viking://resources/specs")++ assert "directory" in result+ assert "list or tree" in result+ assert _clear_download_tokens._store == {}+++async def test_download_missing_file_fails_without_minting(service, _clear_download_tokens):+ with pytest.raises(NotFoundError):+ await download("viking://resources/does-not-exist.pdf")+ assert _clear_download_tokens._store == {}+++async def test_download_denied_file_fails_without_minting(monkeypatch, _clear_download_tokens):+ _stat_service(monkeypatch, AsyncMock(side_effect=PermissionDeniedError("denied")))++ with pytest.raises(PermissionDeniedError):+ await download("viking://resources/secret.pdf")+ assert _clear_download_tokens._store == {}+++async def test_download_checks_with_user_role_outside_api_key_mode(+ monkeypatch, _clear_download_tokens+):+ stat = AsyncMock(return_value={"name": "a.bin", "size": 10, "isDir": False})+ _stat_service(monkeypatch, stat)+ monkeypatch.setattr(+ mcp_endpoint,+ "get_server_config",+ lambda: SimpleNamespace(+ get_effective_auth_mode=lambda: "dev",+ upload_signed_ttl_seconds=600,+ ),+ )+ monkeypatch.setenv("OPENVIKING_PUBLIC_BASE_URL", "https://ov.example.com")+ ctx = RequestContext(UserIdentifier("default", "default"), Role.ROOT)+ token_ctx = _mcp_ctx.set(ctx)+ try:+ await download("viking://resources/a.bin")+ finally:+ _mcp_ctx.reset(token_ctx)++ assert stat.await_args.kwargs["ctx"].role == Role.USER+++async def test_download_inferred_base_url_adds_operator_note(monkeypatch, _clear_download_tokens):+ from openviking.server.mcp_endpoint import _request_url_ctx++ _stat_service(+ monkeypatch, AsyncMock(return_value={"name": "a.bin", "size": 10, "isDir": False})+ )+ monkeypatch.delenv("OPENVIKING_PUBLIC_BASE_URL", raising=False)+ token = _request_url_ctx.set({"x_forwarded_host": "ov.public.example.com"})+ try:+ result = await download("viking://resources/a.bin")+ finally:+ _request_url_ctx.reset(token)++ assert "https://ov.public.example.com/api/v1/content/download?token=" in result+ assert "(a.bin, 10 B)" in result+ assert "OPENVIKING_PUBLIC_BASE_URL is not set" in result++async def test_add_resource_temp_file_id_lookalike_in_path_is_rejected(service):result = await add_resource(path="upload_abc123.pdf")assert "looks like a temp_file_id" in result.lower()diff --git a/tests/server/test_upload_token_store.py b/tests/server/test_upload_token_store.pyindex 40b31b453..f965932bf 100644--- a/tests/server/test_upload_token_store.py+++ b/tests/server/test_upload_token_store.py@@ -52,3 +52,31 @@ def test_purge_expired_drops_stale_tokens(store, monkeypatch):store.issue("a", "u", role=Role.USER, ttl_seconds=600)assert store.peek(t1) is Noneassert store.peek(t2) is not None+++def test_consume_returns_bound_uri(store):+ token, _ = store.issue(+ "acct", "user", role=Role.USER, ttl_seconds=60, uri="viking://resources/a.pdf"+ )+ assert len(token) == 10+ assert store.consume(token).uri == "viking://resources/a.pdf"+++def test_upload_and_download_stores_are_isolated():+ from openviking.server.upload_token_store import download_token_store, upload_token_store++ upload_token_store.clear()+ download_token_store.clear()+ try:+ upload_token, _ = upload_token_store.issue("a", "u", role=Role.USER, ttl_seconds=60)+ download_token, _ = download_token_store.issue(+ "a", "u", role=Role.USER, ttl_seconds=60, uri="viking://resources/a.pdf"+ )+ with pytest.raises(UploadTokenError):+ download_token_store.consume(upload_token)+ with pytest.raises(UploadTokenError):+ upload_token_store.consume(download_token)+ assert download_token_store.consume(download_token).uri == "viking://resources/a.pdf"+ finally:+ upload_token_store.clear()+ download_token_store.clear()