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): auto-ingest local-file uploads via signed temp_upload token (#2925)
t0saki78321080d540
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex 6ac6bd7bb..67057ae8f 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -1418,7 +1418,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 one-shot tokens minted by the MCP `add_resource` tool for local-file uploads via the signed `POST /api/v1/resources/temp_upload_signed` endpoint. | `600` (10 minutes) |+| `upload_signed_ttl_seconds` | int | TTL in seconds for the one-shot tokens minted by the MCP `add_resource` tool for local-file uploads via `POST /api/v1/resources/temp_upload?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). | `"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.shared_prefix` | str | URI prefix used when allocating shared `temp_file_id` objects. | `"viking://upload"` |diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.mdindex 89474b881..f1f0a3597 100644--- a/docs/en/guides/06-mcp-integration.md+++ b/docs/en/guides/06-mcp-integration.md@@ -132,16 +132,14 @@ Once connected, OpenViking exposes 14 tools:> Feishu/Lark imports without `args.feishu_access_token` keep the existing app/tenant-token behavior and can be watched. Feishu/Lark one-time user-token imports pass only `args.feishu_access_token`; Feishu/Lark user-token watches must also pass `args.feishu_refresh_token` and require the same Feishu app credentials configured on the OpenViking server.-### Adding local-file resources (progressive upload)+### Adding local-file resources (single-step upload)The `add_resource` tool accepts both **remote URLs** and **local file paths**, handled differently:- **Remote URL** (`http(s)://`, `git@`, `ssh://`, `git://`): single round-trip — the server fetches and ingests directly.-- **Local file path**: the tool returns a **two-step upload instruction** (plain prose with `Step 1` / `Step 2` formatting). The agent must:- 1. POST the file as `multipart/form-data` to the `temp_upload_signed` URL given in the response (URL embeds a one-shot token; 10-minute TTL by default). The server mints the `temp_file_id` at write time and returns it as JSON: `{"temp_file_id": "..."}`.- 2. Read `temp_file_id` from that response, then call `add_resource(temp_file_id="<id from step 1>")` again — the server resolves the file via `TempUploadStore` and ingests.+- **Local file path**: the tool returns an **upload instruction** (plain prose). The agent POSTs the file as `multipart/form-data` (field name `file`) to the `temp_upload` URL given in the response. The URL embeds a one-shot token (10-minute TTL by default) that authorizes the upload, so no API key is needed. The server then ingests the file **automatically in the same request** and returns the final result — the agent does **not** call `add_resource` again.-This lets any MCP client — including sandboxed environments without a local filesystem (Claude web, Manus, etc.) — push files into OpenViking without pre-installing the `ov` CLI. The signed endpoint shares the same persistence layer as the authenticated `temp_upload` route, so the `local` / `shared` upload modes (and multi-worker support via the `shared` mode) apply equally.+This lets any MCP client — including sandboxed environments without a local filesystem (Claude web, Manus, etc.) — push files into OpenViking without pre-installing the `ov` CLI. The token upload reuses the authenticated `temp_upload` route (API key first, otherwise the one-shot `?token=`) and its `TempUploadStore` persistence, so the same `local` / `shared` upload modes apply. Note: the one-shot token is held in-process, so in a multi-worker deployment the `add_resource` call and the follow-up upload POST must reach the same worker (or run single-worker) for the token to resolve.#### When you must set `OPENVIKING_PUBLIC_BASE_URL`diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex ac8d3c991..2ead03bcd 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -1391,7 +1391,7 @@ openviking 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` 工具向客户端返回的上传指令里使用的对外可见 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` 为本地文件上传 mint 的一次性 token 在签名端点 `POST /api/v1/resources/temp_upload_signed` 上的过期时间(秒)。 | `600`(10 分钟) |+| `upload_signed_ttl_seconds` | int | MCP `add_resource` 为本地文件上传 mint 的一次性 token 的过期时间(秒),走 `POST /api/v1/resources/temp_upload?token=...`。 | `600`(10 分钟) || `temp_upload.default_mode` | str | `POST /api/v1/resources/temp_upload` 的服务端默认模式(客户端未显式传 `upload_mode` 时使用):`"local"`(仅当前实例本地磁盘,单机默认行为)或 `"shared"`(分布式共享存储,多副本部署可跨实例消费)。 | `"local"` || `temp_upload.shared_max_size_bytes` | int | `shared` 模式下接受的最大文件大小(字节)。超过此阈值的请求会在写入对象存储之前被拒绝。 | `536870912`(512 MiB) || `temp_upload.shared_prefix` | str | 分配 shared `temp_file_id` 对象时使用的 URI 前缀。 | `"viking://upload"` |diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.mdindex 7437e1dac..58ab81f5c 100644--- a/docs/zh/guides/06-mcp-integration.md+++ b/docs/zh/guides/06-mcp-integration.md@@ -124,16 +124,14 @@ claude mcp add --transport http openviking \> 未传 `args.feishu_access_token` 的飞书/Lark 导入保持现有应用/tenant token 行为,也支持 watch。飞书/Lark 一次性用户 token 导入只传 `args.feishu_access_token`;飞书/Lark 用户 token watch 还必须传 `args.feishu_refresh_token`,并要求 OpenViking 服务端配置同一个飞书应用凭证。-### 添加本地文件资源(渐进式上传)+### 添加本地文件资源(单步上传)`add_resource` 工具同时接受**远程 URL** 和**本地文件路径**。两者的处理路径不同:- **远程 URL**(`http(s)://`、`git@`、`ssh://`、`git://`):一次调用即完成,server 直接拉取并入库。-- **本地文件路径**:返回**两步上传指令**(纯文本,Step 1 / Step 2 排版),agent 需要:- 1. 把文件以 `multipart/form-data` POST 到响应里给出的 `temp_upload_signed` URL(URL 内嵌一次性 token,默认 10 分钟过期)。Server 在写入时 mint `temp_file_id`,通过 JSON `{"temp_file_id": "..."}` 返回。- 2. 从响应体读出 `temp_file_id`,再次调用 `add_resource(temp_file_id="<step 1 返回的 id>")`,server 通过 `TempUploadStore` 解析文件并入库。+- **本地文件路径**:返回**上传指令**(纯文本)。agent 把文件以 `multipart/form-data`(字段名 `file`)POST 到响应里给出的 `temp_upload` URL。该 URL 内嵌一次性 token(默认 10 分钟过期)作为鉴权凭证,无需 API Key。Server 随后在**同一次请求内自动入库**并返回最终结果,agent **无需**再次调用 `add_resource`。-这样设计是为了让任何 MCP 客户端(包括无本地文件系统的 Claude web、Manus 等沙箱环境)都能往 OpenViking 灌文件,而不需要客户端预装 `ov` CLI。签名端点和认证版的 `temp_upload` 共享同一个持久化层(`TempUploadStore`),所以 `local` / `shared` 上传模式(以及 `shared` 模式带来的多 worker 支持)在两个端点上行为一致。+这样设计是为了让任何 MCP 客户端(包括无本地文件系统的 Claude web、Manus 等沙箱环境)都能往 OpenViking 灌文件,而不需要客户端预装 `ov` CLI。token 上传复用认证版的 `temp_upload` 路由(API Key 优先,否则走一次性 `?token=`)及其 `TempUploadStore` 持久化,所以 `local` / `shared` 上传模式行为一致。注意:一次性 token 保存在进程内,因此多 worker 部署下 `add_resource` 调用与后续的上传 POST 必须落到同一个 worker(或以单 worker 运行),token 才能被解析。#### 必须配置 `OPENVIKING_PUBLIC_BASE_URL` 的场景diff --git a/openviking/server/auth/__init__.py b/openviking/server/auth/__init__.pyindex 17ab2629c..5f245b901 100644--- a/openviking/server/auth/__init__.py+++ b/openviking/server/auth/__init__.py@@ -4,7 +4,7 @@from typing import Optional-from fastapi import Depends, Header, Request+from fastapi import Depends, Header, HTTPException, Query, Requestfrom openviking.core.peer_id import normalize_peer_idfrom openviking.server.identity import (@@ -13,6 +13,7 @@ from openviking.server.identity import (ResolvedIdentity,Role,)+from openviking.server.upload_token_store import UploadTokenError, upload_token_storefrom openviking.telemetry.span_models import update_root_span_identityfrom openviking_cli.exceptions import (InvalidArgumentError,@@ -165,6 +166,58 @@ async def get_request_context(return ctx+async def get_upload_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"),+ x_openviking_agent: Optional[str] = Header(None, alias="X-OpenViking-Agent"),+) -> RequestContext:+ """Two-layer auth for the ``temp_upload`` route: API key first, else a signed token.++ When an API key (``X-API-Key`` / ``Authorization: Bearer``) is present, resolve identity+ normally — an authenticated caller is never downgraded to the token path. Otherwise, if a+ ``?token=`` is present, consume it (single-use) and rebuild the bound identity/business+ params; the token itself is the authorization, so no auth-plugin identity checks run and+ any spoofed ``X-OpenViking-Account/User`` headers are ignored. The consumed token is+ stashed on ``request.state.signed_upload`` so the handler can finish ingestion.+ """+ api_key = _extract_api_key(x_api_key, authorization)+ if token and not api_key:+ try:+ consumed = upload_token_store.consume(token)+ except UploadTokenError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc+ request.state.signed_upload = consumed+ try:+ ctx = RequestContext(+ user=UserIdentifier(consumed.account_id, consumed.user_id),+ role=Role.USER,+ # 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++ 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_openviking_agent)++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 31c87056d..da36f1314 100644--- a/openviking/server/mcp_endpoint.py+++ b/openviking/server/mcp_endpoint.py@@ -45,6 +45,7 @@ from openviking.server.local_input_guard import (TEMP_FILE_ID_RE,is_remote_resource_source,)+from openviking.server.resource_ingest import ingest_temp_uploadfrom openviking.server.temp_upload_store import TempUploadStorefrom openviking.server.upload_token_store import upload_token_storefrom openviking_cli.exceptions import (@@ -490,9 +491,9 @@ async def add_resource(RSS / Atom URL ingests the WHOLE site as one resource tree; pass ``args={"site": true}``to force whole-site ingestion from a bare domain.- Local file: pass ``path`` as a filesystem path (e.g. ``/tmp/foo.pdf``). The response is a- multi-step upload instruction — HTTP POST the file to the returned URL, read ``temp_file_id``- from the upload body, then re-call this tool with ``temp_file_id`` (omit ``path``) to ingest.+ Local file: pass ``path`` as a filesystem path (e.g. ``/tmp/foo.pdf``). The response is an+ upload instruction — HTTP POST the file to the returned URL and the server ingests it+ automatically; you do NOT need to call this tool again.Args:path: Remote URL or local filesystem path. Required unless ``temp_file_id`` is set.@@ -517,36 +518,32 @@ async def add_resource("use a positive number of minutes (>=1440 recommended) to subscribe to auto-refresh.")- # Branch 1: ingest by temp_file_id (second leg of progressive upload, or REST-style)+ # Branch 1: ingest by temp_file_id. Kept for backward compat / REST-style use — the+ # signed upload now auto-ingests server-side, so agents no longer need this second leg.if temp_file_id:from openviking.server.config import ServerConfigserver_config = get_server_config() or ServerConfig()store = TempUploadStore.build(server_config)try:- resolved = await store.resolve_for_consume(temp_file_id, ctx)+ result = await ingest_temp_upload(+ store, temp_file_id, ctx, to=to, reason=description, args=args+ )except (PermissionDeniedError, InvalidArgumentError) as exc:return f"Error: {exc}"- try:- try:- result = await service.resources.add_resource(- path=resolved.local_path,- ctx=ctx,- to=to or None,- reason=description,- source_name=resolved.original_filename,- wait=False,- allow_local_path_resolution=True,- enforce_public_remote_targets=True,- args=args,- )- except Exception as exc:- await store.mark_failed(resolved, ctx)- return f"Error adding resource: {exc}"- await store.mark_consumed(resolved, ctx)- finally:- await resolved.cleanup()- root_uri = result.get("root_uri", "")+ except Exception as exc:+ return f"Error adding resource: {exc}"+ # add_resource returns a business-error dict (no raise) for parse/finalize failures;+ # surface it instead of reporting a false success.+ if isinstance(result, dict) and result.get("status") == "error":+ errors = result.get("errors")+ detail = (+ result.get("message")+ or (errors[0] if isinstance(errors, list) and errors else None)+ or "resource processing failed"+ )+ return f"Error adding resource: {detail}"+ root_uri = result.get("root_uri", "") if isinstance(result, dict) else ""return (f"Resource added: {root_uri}"if root_uri@@ -609,24 +606,24 @@ async def add_resource(ctx.user.account_id,ctx.user.user_id,ttl_seconds=ttl_seconds,+ to=to,+ reason=description,+ actor_peer_id=ctx.actor_peer_id or "",)base_url, url_source = _resolve_public_base_url()- upload_url = f"{base_url}/api/v1/resources/temp_upload_signed?token={quote(token, safe='')}"+ upload_url = f"{base_url}/api/v1/resources/temp_upload?token={quote(token, safe='')}"expires_iso = datetime.fromtimestamp(expires_at, tz=timezone.utc).isoformat(timespec="seconds")minutes = max(1, ttl_seconds // 60)prose = (- "Local file detected — upload required before this resource can be ingested.\n"+ "Local file detected — upload it to ingest this resource.\n""\n"- 'Step 1. HTTP POST the file bytes (multipart/form-data, field name "file") to:\n'+ 'HTTP POST the file bytes (multipart/form-data, field name "file") to:\n'"\n"f" {upload_url}\n""\n"- ' The response will be JSON: {"temp_file_id": "<id>"}\n'- "\n"- "Step 2. Read `temp_file_id` from that response, then call this tool again:\n"- "\n"- ' add_resource(temp_file_id="<id from step 1>")\n'+ "The URL's token authorizes the upload (no API key needed); the server ingests "+ "the file automatically once received — you do NOT need to call add_resource again.\n""\n"f"This upload URL expires in ~{minutes} minutes ({expires_iso}).")@@ -636,7 +633,7 @@ async def add_resource("\n\n""Note for the user: this upload URL was auto-detected from the incoming ""request because OPENVIKING_PUBLIC_BASE_URL is not set on the server. "- "If Step 1 fails (connection refused, wrong host, TLS error), ask the "+ "If the upload 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."diff --git a/openviking/server/resource_ingest.py b/openviking/server/resource_ingest.pynew file mode 100644index 000000000..23f9760e2--- /dev/null+++ b/openviking/server/resource_ingest.py@@ -0,0 +1,64 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Shared helper to ingest an already-uploaded temp file as a resource.++Used by both the MCP ``add_resource`` tool (``temp_file_id`` branch) and the signed+``temp_upload`` route (automatic post-upload ingestion). Resolves the temp file, calls+``ResourceService.add_resource`` (async, ``wait=False``), and drives the ``TempUploadStore``+lifecycle: mark_consumed on success / mark_failed on error, always cleaning up.+"""++from __future__ import annotations++from typing import Any, Optional++from openviking.server.dependencies import get_service+from openviking.server.identity import RequestContext+from openviking.server.temp_upload_store import TempUploadStore+++async def ingest_temp_upload(+ store: TempUploadStore,+ temp_file_id: str,+ ctx: RequestContext,+ *,+ to: str = "",+ reason: str = "",+ args: Optional[dict[str, Any]] = None,+) -> dict[str, Any]:+ """Resolve a temp upload and ingest it as a resource; return the raw add_resource result.++ The return value is the service's own dict — either a success payload (containing+ ``root_uri``) or a business-error dict (``{"status": "error", ...}``) that ``add_resource``+ returns WITHOUT raising. Callers MUST inspect ``status``: HTTP callers pass it through+ ``response_from_result`` (which maps errors to the right status code); the MCP tool formats+ it — so an ingestion failure is never reported as success. The upload is marked consumed+ only on success (mark_failed on business error or exception), and its temp file is always+ cleaned up. ``resolve_for_consume`` may raise (PermissionDenied / InvalidArgument) before+ anything is resolved — the caller surfaces that.+ """+ resolved = await store.resolve_for_consume(temp_file_id, ctx)+ try:+ try:+ result = await get_service().resources.add_resource(+ path=resolved.local_path,+ ctx=ctx,+ to=to or None,+ reason=reason,+ source_name=resolved.original_filename,+ wait=False,+ allow_local_path_resolution=True,+ enforce_public_remote_targets=True,+ args=args,+ )+ except Exception:+ await store.mark_failed(resolved, ctx)+ raise+ if isinstance(result, dict) and result.get("status") == "error":+ await store.mark_failed(resolved, ctx)+ else:+ await store.mark_consumed(resolved, ctx)+ finally:+ await resolved.cleanup()++ return resultdiff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.pyindex bcf541ae9..ead922ce8 100644--- a/openviking/server/routers/resources.py+++ b/openviking/server/routers/resources.py@@ -4,21 +4,20 @@from typing import Any, Dict, Optional-from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile+from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFilefrom pydantic import BaseModel, ConfigDict, Field, model_validator-from openviking.server.auth import get_request_context+from openviking.server.auth import get_request_context, get_upload_request_contextfrom openviking.server.dependencies import get_service-from openviking.server.identity import RequestContext, Role+from openviking.server.identity import RequestContextfrom openviking.server.local_input_guard import require_remote_resource_source+from openviking.server.resource_ingest import ingest_temp_uploadfrom openviking.server.responses import response_from_resultfrom openviking.server.skill_source_metadata import persist_skill_source_metadatafrom openviking.server.telemetry import run_operationfrom openviking.server.temp_upload_store import TempUploadStore-from openviking.server.upload_token_store import UploadTokenError, upload_token_storefrom openviking.telemetry import TelemetryRequestfrom openviking_cli.exceptions import InvalidArgumentError-from openviking_cli.session.user_id import UserIdentifierrouter = APIRouter(prefix="/api/v1", tags=["resources"])@@ -128,65 +127,45 @@ async def temp_upload(file: UploadFile = File(...),telemetry: bool = Form(False),upload_mode: str = Form("local"),- _ctx: RequestContext = Depends(get_request_context),+ _ctx: RequestContext = Depends(get_upload_request_context),):- """Upload a temporary file for add_resource or import_ovpack."""+ """Upload a temporary file for add_resource or import_ovpack.++ Two auth layers (see :func:`get_upload_request_context`): with an API key the file is+ stored and its ``temp_file_id`` returned (used by the CLI and ``import_ovpack``). With a+ signed ``?token=`` — minted by the MCP ``add_resource`` tool for local-file paths — the+ server additionally finishes ingestion in-request: it resolves the upload, calls+ ``add_resource`` with the token-bound ``to``/``reason``, and returns the final result, so+ the agent never needs a second call. The ``?token=`` query param is consumed by the auth+ dependency.+ """+ signed = getattr(request.state, "signed_upload", None)- async def _upload() -> dict[str, str]:+ async def _upload() -> dict[str, Any]:store = TempUploadStore.build(request.app.state.config)temp_file_id = await store.save_upload(file, upload_mode, _ctx)- return {"temp_file_id": temp_file_id}-- execution = await run_operation(- operation="resources.temp_upload",- telemetry=telemetry,- fn=_upload,- )- return response_from_result(execution.result, telemetry=execution.telemetry)--[email protected]("/resources/temp_upload_signed")-async def temp_upload_signed(- request: Request,- file: UploadFile = File(...),- token: str = Query(..., min_length=1),- upload_mode: str = Query("local"),-):- """Upload via short-lived signed token. Used by the MCP progressive-upload flow.-- No identity headers required — the token (issued by ``add_resource`` MCP for local-file- paths) carries the bound (account_id, user_id). The token is consumed on first- use; subsequent attempts return 401. The server mints the ``temp_file_id`` at write time- and returns it in the response body; the caller then calls ``add_resource`` with that id.-- Persistence flows through :class:`TempUploadStore`, so the same local/shared upload modes- and size limit (``temp_upload.shared_max_size_bytes``) as the auth'd ``/temp_upload`` route- apply here too.- """- try:- account_id, user_id = upload_token_store.consume(token)- except UploadTokenError as exc:- raise HTTPException(status_code=401, detail=str(exc)) from exc-- try:- ctx = RequestContext(- user=UserIdentifier(account_id, user_id),- role=Role.USER,+ if signed is None:+ return {"temp_file_id": temp_file_id}+ return await ingest_temp_upload(+ store, temp_file_id, _ctx, to=signed.to, reason=signed.reason)- except ValueError as exc:- raise HTTPException(status_code=400, detail=f"invalid identity in token: {exc}") from exc- store = TempUploadStore.build(request.app.state.config)try:- temp_file_id = await store.save_upload(file, upload_mode, ctx)+ execution = await run_operation(+ operation="resources.temp_upload",+ telemetry=telemetry,+ fn=_upload,+ )except InvalidArgumentError as exc:- # save_upload raises InvalidArgumentError for both bad mode and oversize.- # Map oversize specifically to 413; the rest stay 400.+ if signed is None:+ raise+ # save_upload raises InvalidArgumentError for both bad mode and oversize. The signed+ # route mapped oversize to 413 and the rest to 400 before the routes merged; preserve+ # that contract for the token path.msg = str(exc)status = 413 if "exceeds size limit" in msg else 400raise HTTPException(status_code=status, detail=msg) from exc-- return {"temp_file_id": temp_file_id}+ return response_from_result(execution.result, telemetry=execution.telemetry)@router.post("/resources")diff --git a/openviking/server/upload_token_store.py b/openviking/server/upload_token_store.pyindex a9f770525..7b9c765da 100644--- a/openviking/server/upload_token_store.py+++ b/openviking/server/upload_token_store.py@@ -3,14 +3,17 @@"""In-memory store for short-lived upload tokens used by the MCP progressive upload flow.Issued by the MCP ``add_resource`` tool when a caller passes a local-file path; consumed by-``POST /api/v1/resources/temp_upload_signed``. Tokens are 6-character base62 strings indexed-in a process-local dict — no signing key, no on-disk state, no replay-set bookkeeping.-``dict.pop`` doubles as the consume-and-burn primitive.--The token only carries the identity bound at issue time (account/user). The-``temp_file_id`` is minted by :class:`openviking.server.temp_upload_store.TempUploadStore`-at upload time and returned in the upload response body — the token does-not pre-bind a filename, so the upload can flow through either the local or shared+``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+key, no on-disk state, no replay-set bookkeeping. ``dict.pop`` doubles as the+consume-and-burn primitive.++The token carries the identity bound at issue time (account/user), the caller's actor peer+scope (``actor_peer_id``), and the business params (``to``/``reason``) so the server can+finish ingestion automatically once the file lands — the caller does not re-invoke+``add_resource``, and the ingest keeps the original peer scope. The ``temp_file_id`` is minted by+:class:`openviking.server.temp_upload_store.TempUploadStore` at upload time, so the token+does not pre-bind a filename and the upload can flow through either the local or sharedTempUploadStore mode without a side-channel.Single-worker only: tokens are lost on restart and not shared across uvicorn workers.@@ -38,9 +41,23 @@ class UploadTokenError(Exception):class _TokenInfo:account_id: struser_id: str+ to: str+ reason: str+ actor_peer_id: strexpires_at: float+@dataclass(frozen=True)+class ConsumedUploadToken:+ """Identity and business params bound to an upload token, returned by ``consume``."""++ account_id: str+ user_id: str+ to: str+ reason: str+ actor_peer_id: str++class UploadTokenStore:def __init__(self) -> None:self._store: dict[str, _TokenInfo] = {}@@ -50,11 +67,21 @@ class UploadTokenStore:account_id: str,user_id: str,ttl_seconds: int,+ *,+ to: str = "",+ reason: str = "",+ actor_peer_id: str = "",) -> Tuple[str, float]:- """Mint a fresh token bound to (account, user). Returns (token, expires_at)."""+ """Mint a fresh token bound to (account, user) plus ``to``/``reason``/``actor_peer_id``.++ ``actor_peer_id`` is captured from the minting request's context so server-side+ auto-ingest keeps the caller's peer scope (reason-memory routing) — it is NOT taken+ from the later upload request's headers, which could be spoofed. Returns+ (token, expires_at).+ """self._purge_expired()expires_at = time.time() + max(1, ttl_seconds)- info = _TokenInfo(account_id, user_id, expires_at)+ info = _TokenInfo(account_id, user_id, to, reason, actor_peer_id, expires_at)for _ in range(8):token = "".join(secrets.choice(_TOKEN_ALPHABET) for _ in range(_TOKEN_LENGTH))if token not in self._store:@@ -62,8 +89,8 @@ class UploadTokenStore:return token, expires_atraise RuntimeError("upload_token_store: failed to mint a unique token after 8 attempts")- def consume(self, token: str) -> Tuple[str, str]:- """Pop the token and validate it. Returns (account_id, user_id) on success."""+ def consume(self, token: str) -> ConsumedUploadToken:+ """Pop the token and validate it. Returns the bound identity + business params."""if not token:raise UploadTokenError("missing upload token")info = self._store.pop(token, None)@@ -71,7 +98,9 @@ class UploadTokenStore:raise UploadTokenError("unknown or already-consumed upload token")if info.expires_at < time.time():raise UploadTokenError("upload token expired")- return info.account_id, info.user_id+ return ConsumedUploadToken(+ info.account_id, info.user_id, info.to, info.reason, info.actor_peer_id+ )def peek(self, token: str) -> Optional[_TokenInfo]:"""Read a token without consuming. Test helper only."""diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.pyindex 34d483475..da0984491 100644--- a/tests/server/test_mcp_endpoint.py+++ b/tests/server/test_mcp_endpoint.py@@ -363,15 +363,13 @@ async def test_add_resource_local_path_returns_upload_instruction(service):upload_token_store.clear()result = await add_resource(path="/tmp/sample_local_file_xyz.pdf")- assert "upload required" in result.lower()- assert "Step 1." in result- assert "Step 2." in result- assert "/api/v1/resources/temp_upload_signed" in result- assert "token=" in result- # The server now mints temp_file_id at upload time; the prose tells the agent- # to read it from the upload response.- assert "temp_file_id" in result- assert "<id from step 1>" in result+ assert "local file detected" in result.lower()+ # Single-step flow: POST the file and the server auto-ingests. No second call, no+ # temp_file_id handshake exposed to the agent.+ assert "/api/v1/resources/temp_upload?token=" in result+ assert "temp_upload_signed" not in result+ assert "automatically" in result.lower()+ assert "temp_file_id" not in result# Default fixture sets neither env nor config.public_base_url → URL is auto-inferred# and the troubleshooting hint must appear.assert "OPENVIKING_PUBLIC_BASE_URL" in result@@ -384,7 +382,7 @@ async def test_add_resource_local_path_uses_env_var_when_set(service, monkeypatcupload_token_store.clear()monkeypatch.setenv("OPENVIKING_PUBLIC_BASE_URL", "https://my-ov.example.com")result = await add_resource(path="/tmp/x.pdf")- assert "https://my-ov.example.com/api/v1/resources/temp_upload_signed" in result+ assert "https://my-ov.example.com/api/v1/resources/temp_upload?token=" in result# Explicit source → no troubleshooting hintassert "OPENVIKING_PUBLIC_BASE_URL is not set" not in resultupload_token_store.clear()@@ -402,7 +400,7 @@ async def test_add_resource_local_path_uses_config_when_env_unset(service, monke)result = await add_resource(path="/tmp/x.pdf")- assert "https://configured.example.com/api/v1/resources/temp_upload_signed" in result+ assert "https://configured.example.com/api/v1/resources/temp_upload?token=" in resultassert "OPENVIKING_PUBLIC_BASE_URL is not set" not in resultupload_token_store.clear()@@ -426,7 +424,7 @@ async def test_add_resource_local_path_infers_from_x_forwarded_headers(service,finally:_request_url_ctx.reset(token)- assert "https://ov.public.example.com/api/v1/resources/temp_upload_signed" in result+ assert "https://ov.public.example.com/api/v1/resources/temp_upload?token=" in result# Inferred → hint must appearassert "OPENVIKING_PUBLIC_BASE_URL" in resultupload_token_store.clear()@@ -488,6 +486,24 @@ async def test_add_resource_temp_file_id_branch_resolves_and_ingests(upload_token_store.clear()+async def test_add_resource_temp_file_id_ingest_error_is_surfaced(+ service, upload_temp_dir, monkeypatch+):+ """add_resource returns a business-error dict without raising; MCP must surface it."""+ tfid = "upload_deadbeef.md"+ (upload_temp_dir / tfid).write_text("junk")++ async def failing_add_resource(*, path, ctx, **kwargs):+ return {"status": "error", "errors": ["parse failed"]}++ monkeypatch.setattr(service.resources, "add_resource", failing_add_resource)++ result = await add_resource(temp_file_id=tfid)+ assert "Error adding resource" in result+ assert "parse failed" in result+ assert "Resource added" not in result++async def test_add_resource_watch_without_to_is_forwarded(service, monkeypatch):"""watch_interval > 0 may omit `to`; the service binds to the created root_uri."""captured = {}diff --git a/tests/server/test_resources_temp_upload_signed.py b/tests/server/test_resources_temp_upload_signed.pydeleted file mode 100644index bd789b72e..000000000--- a/tests/server/test_resources_temp_upload_signed.py+++ /dev/null@@ -1,103 +0,0 @@-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.-# SPDX-License-Identifier: AGPL-3.0-"""Tests for POST /api/v1/resources/temp_upload_signed."""--from __future__ import annotations--from pathlib import Path--import httpx-import pytest--from openviking.server.upload_token_store import upload_token_store--[email protected](autouse=True)-def _reset_token_store():- upload_token_store.clear()- yield- upload_token_store.clear()---def _issue(account_id: str = "acct", user_id: str = "user"):- token, _ = upload_token_store.issue(account_id, user_id, ttl_seconds=600)- return token---async def test_signed_upload_writes_file_and_returns_minted_tfid(- client: httpx.AsyncClient, upload_temp_dir: Path-):- token = _issue()- resp = await client.post(- "/api/v1/resources/temp_upload_signed",- params={"token": token},- files={"file": ("hello.md", b"hello world", "text/markdown")},- )- assert resp.status_code == 200, resp.text- body = resp.json()- tfid = body["temp_file_id"]- # TempUploadStore in local mode mints names like upload_<hex>.<ext>- assert tfid.startswith("upload_")-- # File lands in the flat-local TempUploadStore layout, not a per-tenant subdir.- written = upload_temp_dir / tfid- assert written.is_file()- assert written.read_bytes() == b"hello world"-- meta_path = upload_temp_dir / f"{tfid}.ov_upload.meta"- assert meta_path.is_file()---async def test_signed_upload_burns_token_on_use(client: httpx.AsyncClient, upload_temp_dir: Path):- token = _issue()- resp1 = await client.post(- "/api/v1/resources/temp_upload_signed",- params={"token": token},- files={"file": ("a.txt", b"first", "text/plain")},- )- assert resp1.status_code == 200-- resp2 = await client.post(- "/api/v1/resources/temp_upload_signed",- params={"token": token},- files={"file": ("a.txt", b"second", "text/plain")},- )- assert resp2.status_code == 401---async def test_signed_upload_unknown_token(client: httpx.AsyncClient, upload_temp_dir: Path):- resp = await client.post(- "/api/v1/resources/temp_upload_signed",- params={"token": "ZZZZZZ"},- files={"file": ("upload_abc.md", b"x", "text/plain")},- )- assert resp.status_code == 401---async def test_signed_upload_oversize_rejected(- client: httpx.AsyncClient, upload_temp_dir: Path, app-):- """Size cap is enforced while streaming by TempUploadStore — same limit as /temp_upload."""- app.state.config.temp_upload.shared_max_size_bytes = 16-- token = _issue()- big = b"x" * 64- resp = await client.post(- "/api/v1/resources/temp_upload_signed",- params={"token": token},- files={"file": ("big.bin", big, "text/plain")},- )- assert resp.status_code == 413---async def test_legacy_temp_upload_still_writes_flat(- client: httpx.AsyncClient, upload_temp_dir: Path-):- """The CLI flow at POST /api/v1/resources/temp_upload must keep working unchanged."""- resp = await client.post(- "/api/v1/resources/temp_upload",- files={"file": ("legacy.md", b"legacy", "text/plain")},- )- assert resp.status_code == 200- tfid = resp.json()["result"]["temp_file_id"]- assert (upload_temp_dir / tfid).is_file()diff --git a/tests/server/test_resources_temp_upload_token.py b/tests/server/test_resources_temp_upload_token.pynew file mode 100644index 000000000..db967ffd8--- /dev/null+++ b/tests/server/test_resources_temp_upload_token.py@@ -0,0 +1,201 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Tests for the signed-token upload path on POST /api/v1/resources/temp_upload.++The MCP ``add_resource`` tool mints a short-lived ``?token=`` for local-file paths. A POST+carrying that token (and no API key) is authorized by the token alone, and the server+finishes ingestion in-request — the agent never posts a ``temp_file_id`` back. An API-key+POST keeps the legacy behavior of just storing the file and returning its ``temp_file_id``.+"""++from __future__ import annotations++from pathlib import Path++import httpx+import pytest++from openviking.server.upload_token_store import upload_token_store++[email protected](autouse=True)+def _reset_token_store():+ upload_token_store.clear()+ yield+ upload_token_store.clear()+++def _issue(+ account_id: str = "acct",+ user_id: str = "user",+ *,+ to: str = "",+ reason: str = "",+ actor_peer_id: str = "",+):+ token, _ = upload_token_store.issue(+ account_id, user_id, ttl_seconds=600, to=to, reason=reason, actor_peer_id=actor_peer_id+ )+ return token+++def _stub_ingest(service, monkeypatch, root_uri: str = "viking://resources/uploaded") -> dict:+ """Stub add_resource so token-path uploads don't run the full ingest pipeline."""+ captured: dict = {}++ async def fake_add_resource(*, path, ctx, **kwargs):+ captured["path"] = path+ captured["content"] = Path(path).read_bytes()+ captured["ctx"] = ctx+ captured["to"] = kwargs.get("to")+ captured["reason"] = kwargs.get("reason")+ captured["allow_local_path_resolution"] = kwargs.get("allow_local_path_resolution")+ return {"root_uri": root_uri}++ monkeypatch.setattr(service.resources, "add_resource", fake_add_resource)+ return captured+++async def test_token_upload_auto_ingests_and_returns_result(+ client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch+):+ captured = _stub_ingest(service, monkeypatch)+ token = _issue()+ resp = await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": token},+ files={"file": ("hello.md", b"hello world", "text/markdown")},+ )+ assert resp.status_code == 200, resp.text+ result = resp.json()["result"]+ # Auto-ingest returns the final resource, not a temp_file_id handshake.+ assert result["root_uri"] == "viking://resources/uploaded"+ assert "temp_file_id" not in result+ # The stored file was resolved and handed to add_resource as a local path.+ assert captured["allow_local_path_resolution"] is True+ assert captured["content"] == b"hello world"+++async def test_token_upload_forwards_to_and_reason(+ client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch+):+ captured = _stub_ingest(service, monkeypatch)+ token = _issue(to="viking://resources/team/proj", reason="quarterly report")+ resp = await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": token},+ files={"file": ("r.md", b"data", "text/markdown")},+ )+ assert resp.status_code == 200, resp.text+ assert captured["to"] == "viking://resources/team/proj"+ assert captured["reason"] == "quarterly report"+++async def test_token_upload_uses_token_identity_ignoring_spoofed_headers(+ client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch+):+ captured = _stub_ingest(service, monkeypatch)+ token = _issue(account_id="real_acct", user_id="real_user")+ resp = await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": token},+ files={"file": ("r.md", b"data", "text/markdown")},+ headers={"X-OpenViking-Account": "evil", "X-OpenViking-User": "attacker"},+ )+ assert resp.status_code == 200, resp.text+ ctx = captured["ctx"]+ assert ctx.user.account_id == "real_acct"+ assert ctx.user.user_id == "real_user"+++async def test_token_upload_preserves_actor_peer_from_token(+ client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch+):+ """Actor peer scope comes from the token (bound at mint), not the upload headers."""+ captured = _stub_ingest(service, monkeypatch)+ token = _issue(actor_peer_id="bot-a")+ resp = await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": token},+ files={"file": ("r.md", b"data", "text/markdown")},+ # A spoofed actor-peer header must be ignored; the token's peer wins.+ headers={"X-OpenViking-Actor-Peer": "evil-bot"},+ )+ assert resp.status_code == 200, resp.text+ assert captured["ctx"].actor_peer_id == "bot-a"+++async def test_token_upload_ingest_error_is_not_reported_as_success(+ client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch+):+ """A business-error result from add_resource must surface as an HTTP error, not 200 ok."""++ async def failing_add_resource(*, path, ctx, **kwargs):+ return {"status": "error", "code": "PROCESSING_ERROR", "errors": ["parse failed"]}++ monkeypatch.setattr(service.resources, "add_resource", failing_add_resource)+ token = _issue()+ resp = await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": token},+ files={"file": ("bad.md", b"junk", "text/markdown")},+ )+ assert resp.status_code >= 400, resp.text+ assert resp.json().get("status") == "error"+++async def test_token_upload_burns_token_on_use(+ client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch+):+ _stub_ingest(service, monkeypatch)+ token = _issue()+ resp1 = await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": token},+ files={"file": ("a.txt", b"first", "text/plain")},+ )+ assert resp1.status_code == 200, resp1.text++ resp2 = await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": token},+ files={"file": ("a.txt", b"second", "text/plain")},+ )+ assert resp2.status_code == 401+++async def test_token_upload_unknown_token(client: httpx.AsyncClient, upload_temp_dir: Path):+ resp = await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": "ZZZZZZ"},+ files={"file": ("upload_abc.md", b"x", "text/plain")},+ )+ assert resp.status_code == 401+++async def test_token_upload_oversize_rejected(+ client: httpx.AsyncClient, upload_temp_dir: Path, app+):+ """Size cap is enforced by TempUploadStore before ingestion; oversize maps to 413."""+ app.state.config.temp_upload.shared_max_size_bytes = 16+ token = _issue()+ big = b"x" * 64+ resp = await client.post(+ "/api/v1/resources/temp_upload",+ params={"token": token},+ files={"file": ("big.bin", big, "text/plain")},+ )+ assert resp.status_code == 413+++async def test_apikey_temp_upload_returns_temp_file_id(+ client: httpx.AsyncClient, upload_temp_dir: Path+):+ """No token → legacy path: store the file and return its temp_file_id unchanged."""+ resp = await client.post(+ "/api/v1/resources/temp_upload",+ files={"file": ("legacy.md", b"legacy", "text/plain")},+ )+ assert resp.status_code == 200, resp.text+ tfid = resp.json()["result"]["temp_file_id"]+ assert (upload_temp_dir / tfid).is_file()diff --git a/tests/server/test_upload_token_store.py b/tests/server/test_upload_token_store.pyindex abf149d3e..96395f37d 100644--- a/tests/server/test_upload_token_store.py+++ b/tests/server/test_upload_token_store.py@@ -20,20 +20,37 @@ def store() -> UploadTokenStore:def test_issue_returns_token_of_expected_length(store):- token, expires_at = store.issue("acct", "user", "agent", ttl_seconds=60)+ token, expires_at = store.issue("acct", "user", ttl_seconds=60)assert len(token) == _TOKEN_LENGTHassert all(c in _TOKEN_ALPHABET for c in token)assert expires_at > 0def test_consume_roundtrip(store):- token, _ = store.issue("acct", "user", "agent", ttl_seconds=60)- aid, uid, agid = store.consume(token)- assert (aid, uid, agid) == ("acct", "user", "agent")+ token, _ = store.issue("acct", "user", ttl_seconds=60)+ consumed = store.consume(token)+ assert (consumed.account_id, consumed.user_id) == ("acct", "user")+ # Business params default to empty when not supplied at issue time.+ assert (consumed.to, consumed.reason, consumed.actor_peer_id) == ("", "", "")+++def test_consume_returns_bound_business_params(store):+ token, _ = store.issue(+ "acct",+ "user",+ ttl_seconds=60,+ to="viking://resources/team/proj",+ reason="quarterly",+ actor_peer_id="bot-a",+ )+ consumed = store.consume(token)+ assert consumed.to == "viking://resources/team/proj"+ assert consumed.reason == "quarterly"+ assert consumed.actor_peer_id == "bot-a"def test_consume_burns_token(store):- token, _ = store.issue("acct", "user", "agent", ttl_seconds=60)+ token, _ = store.issue("acct", "user", ttl_seconds=60)store.consume(token)with pytest.raises(UploadTokenError, match="unknown or already-consumed"):store.consume(token)@@ -55,7 +72,7 @@ def test_consume_expired_token(store, monkeypatch):fake_now = [1000.0]monkeypatch.setattr(mod.time, "time", lambda: fake_now[0])- token, _ = store.issue("acct", "user", "agent", ttl_seconds=60)+ token, _ = store.issue("acct", "user", ttl_seconds=60)fake_now[0] += 61with pytest.raises(UploadTokenError, match="expired"):store.consume(token)@@ -67,13 +84,13 @@ def test_purge_expired_drops_stale_tokens(store, monkeypatch):fake_now = [1000.0]monkeypatch.setattr(mod.time, "time", lambda: fake_now[0])- t1, _ = store.issue("a", "u", "ag", ttl_seconds=10)- t2, _ = store.issue("a", "u", "ag", ttl_seconds=600)+ t1, _ = store.issue("a", "u", ttl_seconds=10)+ t2, _ = store.issue("a", "u", ttl_seconds=600)fake_now[0] += 30 # t1 expired, t2 still alive# Issuing a new token implicitly purges; t1 should be gone afterward- store.issue("a", "u", "ag", ttl_seconds=600)+ store.issue("a", "u", ttl_seconds=600)assert store.peek(t1) is Noneassert store.peek(t2) is not None@@ -93,12 +110,12 @@ def test_issue_handles_dense_alphabet_collisions(store, monkeypatch):monkeypatch.setattr(mod.secrets, "choice", fake_choice)- t1, _ = store.issue("a", "u", "ag", ttl_seconds=60)- t2, _ = store.issue("a", "u", "ag", ttl_seconds=60)+ t1, _ = store.issue("a", "u", ttl_seconds=60)+ t2, _ = store.issue("a", "u", ttl_seconds=60)assert t1 != t2def test_clear_resets_state(store):- store.issue("a", "u", "ag", ttl_seconds=60)+ store.issue("a", "u", ttl_seconds=60)store.clear()assert store._store == {}