Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(examples): add OpenWebUI tool-server plugin (#1387) (#2640)

yeyitech747474a53e81
diff --git a/examples/openwebui-plugin/README.md b/examples/openwebui-plugin/README.md
new file mode 100644
index 000000000..f143f76de
--- /dev/null
+++ b/examples/openwebui-plugin/README.md
@@ -0,0 +1,214 @@
+# OpenViking Tool Server for Open WebUI
+
+A standalone FastAPI server that exposes a curated subset of OpenViking
+endpoints as **OpenAPI tools** so Open WebUI can call them as native tools.
+
+[中文说明在下方 / Chinese instructions below.](#中文说明)
+
+## What This Plugin Does
+
+Open WebUI supports two integration mechanisms — Python "Functions" pasted into
+its admin UI, and **external OpenAPI tool servers** auto-discovered from
+`/openapi.json`. This plugin implements the second mechanism.
+
+It is a **thin translation layer**: every tool route forwards a request to the
+corresponding OpenViking HTTP endpoint, attaches tenant headers, and returns
+the response. There is no business logic here — see the OpenViking server for
+that.
+
+## Tools Exposed
+
+Seven curated tools, all auto-discovered by Open WebUI:
+
+| Tool | OpenViking endpoint | Purpose |
+| --- | --- | --- |
+| `ov_search` | `POST /api/v1/search/find` | Semantic search across memories, resources, skills |
+| `ov_recall_memories` | `POST /api/v1/search/find` (scoped to `viking://user/memories/`) | Recall personal memories for the current query |
+| `ov_add_memory` | `POST /api/v1/content/write` to `viking://user/memories/<name>` | Persist a new memory |
+| `ov_list_memories` | `GET /api/v1/fs/ls?uri=viking://user/memories/` | Browse the memories directory |
+| `ov_read_resource` | `GET /api/v1/content/read` | Read full text content of any `viking://` URI |
+| `ov_add_resource` | `POST /api/v1/resources` | Ingest a remote URL or path-reachable file |
+| `ov_session_status` | `GET /api/v1/sessions/{id}` | Inspect counts and archive state of a session |
+
+The list is intentionally small. Adding more is straightforward — see the
+[Roadmap](#roadmap).
+
+## Quickstart
+
+```bash
+cd examples/openwebui-plugin
+pip install -e .
+OV_API_KEY=your-key python -m openviking_openwebui
+```
+
+The server listens on `0.0.0.0:8765` by default. You should see:
+
+```
+INFO: Uvicorn running on http://0.0.0.0:8765
+```
+
+Verify the OpenAPI spec is served:
+
+```bash
+curl http://localhost:8765/openapi.json | jq '.paths | keys'
+```
+
+## Wiring Into Open WebUI
+
+1. Open WebUI → **Settings** → **Tools** → **Add Tool Server**.
+2. Paste the URL where this server is reachable, e.g. `http://localhost:8765`.
+3. Open WebUI fetches `/openapi.json`, lists all seven tools, and presents
+ them to the LLM as callable tools on every chat turn.
+
+No copy-pasting Python files, no admin-panel uploads. The same tool server is
+reusable across any OpenAPI-aware client.
+
+## Configuration
+
+All configuration is via environment variables:
+
+| Variable | Default | Description |
+| --- | --- | --- |
+| `OV_ENDPOINT` | `http://localhost:1933` | OpenViking server base URL |
+| `OV_API_KEY` | _(empty)_ | Bearer token sent as `Authorization: Bearer …` |
+| `OV_ACCOUNT` | `default` | Tenant — sent as `X-OpenViking-Account` |
+| `OV_USER` | `default` | User — sent as `X-OpenViking-User` |
+| `OV_AGENT` | `default` | Actor peer ID — sent as `X-OpenViking-Actor-Peer` |
+| `OV_BIND` | `0.0.0.0:8765` | Host:port the tool server binds to |
+| `OV_TIMEOUT` | `30` | HTTP timeout in seconds when calling OpenViking |
+
+There is no config file. This is intentional — make the deployment unit one
+binary and one set of env vars.
+
+## Tool Reference
+
+### `ov_search`
+Top-level semantic search. Takes `{query, limit?, target_uri?, score_threshold?}`
+and returns `{hits: [{uri, score, snippet?}], raw}`. Use this when you want to
+search across memories, resources, and skills together.
+
+### `ov_recall_memories`
+Same as `ov_search` but `target_uri` is forced to `viking://user/memories/`,
+so only personal memories are searched. Use this in chat to ask "what do you
+remember about me re: X?".
+
+### `ov_add_memory`
+Persists a memory. Takes `{name, content, mode?, wait?}` and writes
+`viking://user/memories/<name>` via OpenViking's content write API. `mode` is
+one of `replace | append | create`.
+
+### `ov_list_memories`
+Lists entries directly under `viking://user/memories/`. Takes
+`{recursive?, limit?}`.
+
+### `ov_read_resource`
+Reads any `viking://` URI's text content. Takes `{uri, offset?, limit?}`.
+
+### `ov_add_resource`
+Triggers OpenViking ingestion of a remote URL or path the OV server can reach.
+Takes `{path, to?, parent?, reason?, instruction?, wait?}`. Pure HTTP forward —
+the OV server validates the source.
+
+### `ov_session_status`
+Returns session metadata for a given session ID — message counts, archive
+state, pending tokens. Takes `{session_id}`.
+
+## Tests
+
+```bash
+cd examples/openwebui-plugin
+pip install -e ".[test]"
+pytest tests -x -q
+```
+
+The test suite uses `respx` to mock the OpenViking HTTP layer, and asserts
+each tool calls the correct upstream method/path/body and forwards tenant
+headers verbatim.
+
+## Limitations
+
+- **No streaming.** Open WebUI tools are request/response. Live transcript
+ streaming is out of scope for this plugin.
+- **No file uploads.** `ov_add_resource` accepts a remote URL or a path the OV
+ server can reach itself. To upload binary blobs, hit the OV server's
+ `temp_upload` endpoint directly.
+- **No write-side memory deletion / move tools.** Read-mostly by design; users
+ who want destructive operations should use the OV CLI.
+- **Single tenant per process.** Tenant identity comes from env vars, so run
+ one tool server per `(account, user)` pair if you need to multiplex.
+- **No bundled Open WebUI instance.** This is a tool server only — bring your
+ own Open WebUI.
+
+## Roadmap
+
+Adding a new tool is roughly:
+
+1. Add a Pydantic request model in `openviking_openwebui/tools.py`.
+2. Add a route handler decorated with `@router.post("/tools/<name>", operation_id="<name>")`.
+3. Forward to the OpenViking endpoint via `OVClient`.
+4. Add a test in `tests/test_tools.py` mocking the upstream call.
+
+Likely candidates the community might want next: `ov_session_create`,
+`ov_session_commit`, `ov_grep`, `ov_glob`, `ov_overview`, `ov_abstract`.
+
+## Security
+
+- Never commit `OV_API_KEY` to source control. Pass it via the environment.
+- The tool server has no auth of its own — bind it to localhost or a private
+ network, or front it with a proxy that enforces auth.
+- Tenant identity is server-side trust: anyone with `OV_API_KEY` and the
+ right `X-OpenViking-Account/User` headers can read that tenant's data. This
+ matches OpenViking's standard trust model.
+
+---
+
+## 中文说明
+
+这是一个独立的 FastAPI 服务,将 OpenViking 的一组核心 HTTP 端点封装为
+**OpenAPI 工具**,供 Open WebUI 自动发现并调用。
+
+### 它做什么
+
+Open WebUI 支持两种工具集成方式:把 Python "Functions" 粘贴进管理后台,
+或对接外部 OpenAPI 工具服务器(自动从 `/openapi.json` 发现工具)。
+本插件实现第二种方式——纯 HTTP 转发,不重复实现任何业务逻辑。
+
+### 暴露的 7 个工具
+
+`ov_search`、`ov_recall_memories`、`ov_add_memory`、`ov_list_memories`、
+`ov_read_resource`、`ov_add_resource`、`ov_session_status`。详见上方表格。
+
+### 快速开始
+
+```bash
+cd examples/openwebui-plugin
+pip install -e .
+OV_API_KEY=your-key python -m openviking_openwebui
+```
+
+默认监听 `0.0.0.0:8765`。
+
+### 接入 Open WebUI
+
+进入 Open WebUI 的 **设置 → 工具 → 添加工具服务器**,粘贴
+`http://localhost:8765`。Open WebUI 会自动读取 `/openapi.json`
+并把全部 7 个工具暴露给模型。
+
+### 环境变量
+
+`OV_ENDPOINT`、`OV_API_KEY`、`OV_ACCOUNT`、`OV_USER`、`OV_AGENT`、`OV_BIND`、
+`OV_TIMEOUT`。默认值与说明见上方英文表格。
+
+### 测试
+
+```bash
+pip install -e ".[test]"
+pytest tests -x -q
+```
+
+### 添加更多工具
+
+1. 在 `openviking_openwebui/tools.py` 中添加 Pydantic 请求模型;
+2. 添加路由 handler,设置 `operation_id`;
+3. 通过 `OVClient` 转发到对应 OpenViking 端点;
+4. 在 `tests/test_tools.py` 中加 mock 测试。
diff --git a/examples/openwebui-plugin/openviking_openwebui/__init__.py b/examples/openwebui-plugin/openviking_openwebui/__init__.py
new file mode 100644
index 000000000..87196f85c
--- /dev/null
+++ b/examples/openwebui-plugin/openviking_openwebui/__init__.py
@@ -0,0 +1,8 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""OpenViking OpenWebUI tool server package."""
+
+from .config import Settings, load_settings
+from .server import create_app
+
+__all__ = ["Settings", "create_app", "load_settings"]
diff --git a/examples/openwebui-plugin/openviking_openwebui/__main__.py b/examples/openwebui-plugin/openviking_openwebui/__main__.py
new file mode 100644
index 000000000..6f7d43d86
--- /dev/null
+++ b/examples/openwebui-plugin/openviking_openwebui/__main__.py
@@ -0,0 +1,23 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""``python -m openviking_openwebui`` entry point."""
+
+from __future__ import annotations
+
+import uvicorn
+
+from .config import load_settings
+
+
+def main() -> None:
+ settings = load_settings()
+ uvicorn.run(
+ "openviking_openwebui.server:app",
+ host=settings.bind_host,
+ port=settings.bind_port,
+ log_level="info",
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/openwebui-plugin/openviking_openwebui/client.py b/examples/openwebui-plugin/openviking_openwebui/client.py
new file mode 100644
index 000000000..e641de24c
--- /dev/null
+++ b/examples/openwebui-plugin/openviking_openwebui/client.py
@@ -0,0 +1,77 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Thin async HTTP client around the OpenViking server."""
+
+from __future__ import annotations
+
+from typing import Any, Dict, Optional
+
+import httpx
+
+from .config import Settings
+
+
+class OVError(Exception):
+ """Raised when the OpenViking server returns a non-2xx response."""
+
+ def __init__(self, status: int, payload: Any):
+ self.status = status
+ self.payload = payload
+ super().__init__(f"OpenViking error {status}: {payload!r}")
+
+
+class OVClient:
+ """Forward HTTP calls to OpenViking, attaching tenant headers."""
+
+ def __init__(self, settings: Settings, client: Optional[httpx.AsyncClient] = None):
+ self._settings = settings
+ self._owns_client = client is None
+ self._client = client or httpx.AsyncClient(
+ base_url=settings.endpoint,
+ timeout=settings.timeout_seconds,
+ )
+
+ async def aclose(self) -> None:
+ if self._owns_client:
+ await self._client.aclose()
+
+ def _headers(self) -> Dict[str, str]:
+ headers: Dict[str, str] = {}
+ if self._settings.api_key:
+ headers["Authorization"] = f"Bearer {self._settings.api_key}"
+ if self._settings.account:
+ headers["X-OpenViking-Account"] = self._settings.account
+ if self._settings.user:
+ headers["X-OpenViking-User"] = self._settings.user
+ if self._settings.agent:
+ headers["X-OpenViking-Actor-Peer"] = self._settings.agent
+ return headers
+
+ async def request(
+ self,
+ method: str,
+ path: str,
+ *,
+ params: Optional[Dict[str, Any]] = None,
+ json: Optional[Dict[str, Any]] = None,
+ ) -> Any:
+ response = await self._client.request(
+ method,
+ path,
+ params=params,
+ json=json,
+ headers=self._headers(),
+ )
+ try:
+ payload = response.json()
+ except ValueError:
+ payload = response.text
+ if response.status_code >= 400:
+ raise OVError(response.status_code, payload)
+ return payload
+
+ async def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
+ return await self.request("GET", path, params=params)
+
+ async def post(self, path: str, json: Optional[Dict[str, Any]] = None) -> Any:
+ return await self.request("POST", path, json=json)
diff --git a/examples/openwebui-plugin/openviking_openwebui/config.py b/examples/openwebui-plugin/openviking_openwebui/config.py
new file mode 100644
index 000000000..1caf22439
--- /dev/null
+++ b/examples/openwebui-plugin/openviking_openwebui/config.py
@@ -0,0 +1,63 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Environment-driven configuration for the OpenWebUI tool server."""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+
+
+def _env(name: str, default: str = "") -> str:
+ value = os.environ.get(name)
+ if value is None:
+ return default
+ return value.strip() or default
+
+
+@dataclass(frozen=True)
+class Settings:
+ """Settings resolved from environment variables.
+
+ Read once at process start. Override by exporting variables before
+ launching the server.
+ """
+
+ endpoint: str
+ api_key: str
+ account: str
+ user: str
+ agent: str
+ bind: str
+ timeout_seconds: float
+
+ @property
+ def bind_host(self) -> str:
+ host, _, _ = self.bind.partition(":")
+ return host or "0.0.0.0"
+
+ @property
+ def bind_port(self) -> int:
+ _, _, port = self.bind.partition(":")
+ try:
+ return int(port) if port else 8765
+ except ValueError:
+ return 8765
+
+ @property
+ def memories_uri(self) -> str:
+ """Conventional URI prefix where personal memories live."""
+ return "viking://user/memories/"
+
+
+def load_settings() -> Settings:
+ """Build a Settings instance from process env."""
+ return Settings(
+ endpoint=_env("OV_ENDPOINT", "http://localhost:1933").rstrip("/"),
+ api_key=_env("OV_API_KEY", ""),
+ account=_env("OV_ACCOUNT", "default"),
+ user=_env("OV_USER", "default"),
+ agent=_env("OV_AGENT", "default"),
+ bind=_env("OV_BIND", "0.0.0.0:8765"),
+ timeout_seconds=float(_env("OV_TIMEOUT", "30")),
+ )
diff --git a/examples/openwebui-plugin/openviking_openwebui/server.py b/examples/openwebui-plugin/openviking_openwebui/server.py
new file mode 100644
index 000000000..dd14c4586
--- /dev/null
+++ b/examples/openwebui-plugin/openviking_openwebui/server.py
@@ -0,0 +1,49 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""FastAPI app exposing OpenViking endpoints as OpenWebUI tools."""
+
+from __future__ import annotations
+
+from contextlib import asynccontextmanager
+from typing import Optional
+
+from fastapi import FastAPI
+
+from .client import OVClient
+from .config import Settings, load_settings
+from .tools import router as tools_router
+
+
+def create_app(settings: Optional[Settings] = None) -> FastAPI:
+ """Build the FastAPI app. Tests inject a custom Settings/OVClient."""
+ resolved = settings or load_settings()
+
+ @asynccontextmanager
+ async def lifespan(app: FastAPI):
+ client = OVClient(resolved)
+ app.state.ov_client = client
+ app.state.ov_settings = resolved
+ try:
+ yield
+ finally:
+ await client.aclose()
+
+ app = FastAPI(
+ title="OpenViking OpenWebUI Tools",
+ version="0.1.0",
+ description=(
+ "OpenAPI tool server that fronts a curated set of OpenViking "
+ "endpoints so OpenWebUI can call them as tools."
+ ),
+ lifespan=lifespan,
+ )
+
+ @app.get("/health", tags=["meta"])
+ async def health() -> dict:
+ return {"status": "ok", "endpoint": resolved.endpoint}
+
+ app.include_router(tools_router)
+ return app
+
+
+app = create_app()
diff --git a/examples/openwebui-plugin/openviking_openwebui/tools.py b/examples/openwebui-plugin/openviking_openwebui/tools.py
new file mode 100644
index 000000000..4d4d8117d
--- /dev/null
+++ b/examples/openwebui-plugin/openviking_openwebui/tools.py
@@ -0,0 +1,295 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""FastAPI route handlers, one per OpenWebUI tool."""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Literal, Optional
+
+from fastapi import APIRouter, Depends, HTTPException, Request
+from pydantic import BaseModel, Field
+
+from .client import OVClient, OVError
+from .config import Settings
+
+
+def get_client(request: Request) -> OVClient:
+ """Resolve the shared OVClient placed on the FastAPI app state."""
+ return request.app.state.ov_client
+
+
+def get_settings(request: Request) -> Settings:
+ return request.app.state.ov_settings
+
+
+router = APIRouter(tags=["openviking"])
+
+
+def _forward(exc: OVError) -> HTTPException:
+ """Surface the OV server's error status + body verbatim."""
+ return HTTPException(status_code=exc.status, detail=exc.payload)
+
+
+# --- Schemas -----------------------------------------------------------------
+
+
+class SearchRequest(BaseModel):
+ query: str = Field(..., description="Natural-language query")
+ limit: int = Field(10, ge=1, le=100)
+ target_uri: Optional[str] = Field(
+ None,
+ description="Optional viking:// prefix to scope the search",
+ )
+ score_threshold: Optional[float] = Field(None, ge=0.0, le=1.0)
+
+
+class SearchHit(BaseModel):
+ uri: str
+ score: float
+ snippet: Optional[str] = None
+
+
+class SearchResponse(BaseModel):
+ hits: List[SearchHit]
+ raw: Dict[str, Any] = Field(default_factory=dict)
+
+
+class RecallRequest(BaseModel):
+ query: str
+ limit: int = Field(6, ge=1, le=50)
+
+
+class AddMemoryRequest(BaseModel):
+ name: str = Field(..., description="Filename under viking://user/memories/, e.g. 'profile.md'")
+ content: str = Field(..., description="Memory body, plain text or Markdown")
+ mode: Literal["replace", "append", "create"] = "replace"
+ wait: bool = Field(False, description="Block until semantic indexing completes")
+
+
+class AddMemoryResponse(BaseModel):
+ uri: str
+ raw: Dict[str, Any] = Field(default_factory=dict)
+
+
+class ListMemoriesRequest(BaseModel):
+ recursive: bool = False
+ limit: int = Field(200, ge=1, le=1000)
+
+
+class ReadResourceRequest(BaseModel):
+ uri: str = Field(..., description="Full viking:// URI")
+ offset: int = 0
+ limit: int = -1
+
+
+class AddResourceRequest(BaseModel):
+ path: str = Field(..., description="Remote URL or local path the OV server can reach")
+ to: Optional[str] = None
+ parent: Optional[str] = None
+ reason: str = ""
+ instruction: str = ""
+ wait: bool = False
+
+
+class SessionStatusRequest(BaseModel):
+ session_id: str
+
+
+# --- Helpers -----------------------------------------------------------------
+
+
+def _hits_from_find(payload: Dict[str, Any]) -> List[SearchHit]:
+ """Flatten an OpenViking /search/find response into typed hits."""
+ result = payload.get("result") if isinstance(payload, dict) else None
+ if not isinstance(result, dict):
+ return []
+ bucket_keys = ("memories", "resources", "skills", "results")
+ seen: List[SearchHit] = []
+ for key in bucket_keys:
+ bucket = result.get(key)
+ if not isinstance(bucket, list):
+ continue
+ for item in bucket:
+ if not isinstance(item, dict):
+ continue
+ uri = item.get("uri") or item.get("target_uri")
+ if not isinstance(uri, str):
+ continue
+ score = float(item.get("score") or 0.0)
+ snippet = item.get("snippet") or item.get("abstract") or item.get("preview")
+ seen.append(
+ SearchHit(
+ uri=uri,
+ score=score,
+ snippet=snippet if isinstance(snippet, str) else None,
+ )
+ )
+ return seen
+
+
+def _memory_uri(settings: Settings, name: str) -> str:
+ name = name.strip().lstrip("/")
+ if not name:
+ raise HTTPException(status_code=400, detail="name must not be empty")
+ return settings.memories_uri + name
+
+
+# --- Routes ------------------------------------------------------------------
+
+
+ "/tools/ov_search",
+ response_model=SearchResponse,
+ operation_id="ov_search",
+ summary="Semantic search across OpenViking memories, resources, and skills.",
+)
+async def ov_search(
+ body: SearchRequest,
+ client: OVClient = Depends(get_client),
+) -> SearchResponse:
+ """Run a semantic find over OpenViking and return the top hits."""
+ payload: Dict[str, Any] = {"query": body.query, "limit": body.limit}
+ if body.target_uri:
+ payload["target_uri"] = body.target_uri
+ if body.score_threshold is not None:
+ payload["score_threshold"] = body.score_threshold
+ try:
+ raw = await client.post("/api/v1/search/find", json=payload)
+ except OVError as exc:
+ raise _forward(exc) from exc
+ return SearchResponse(hits=_hits_from_find(raw), raw=raw if isinstance(raw, dict) else {})
+
+
+ "/tools/ov_recall_memories",
+ response_model=SearchResponse,
+ operation_id="ov_recall_memories",
+ summary="Recall personal memories relevant to a query.",
+)
+async def ov_recall_memories(
+ body: RecallRequest,
+ client: OVClient = Depends(get_client),
+ settings: Settings = Depends(get_settings),
+) -> SearchResponse:
+ """Search scoped to viking://user/memories/ for personal memory recall."""
+ payload = {
+ "query": body.query,
+ "limit": body.limit,
+ "target_uri": settings.memories_uri,
+ }
+ try:
+ raw = await client.post("/api/v1/search/find", json=payload)
+ except OVError as exc:
+ raise _forward(exc) from exc
+ return SearchResponse(hits=_hits_from_find(raw), raw=raw if isinstance(raw, dict) else {})
+
+
+ "/tools/ov_add_memory",
+ response_model=AddMemoryResponse,
+ operation_id="ov_add_memory",
+ summary="Persist a new memory under viking://user/memories/.",
+)
+async def ov_add_memory(
+ body: AddMemoryRequest,
+ client: OVClient = Depends(get_client),
+ settings: Settings = Depends(get_settings),
+) -> AddMemoryResponse:
+ """Write a memory file via /api/v1/content/write."""
+ uri = _memory_uri(settings, body.name)
+ payload = {
+ "uri": uri,
+ "content": body.content,
+ "mode": body.mode,
+ "wait": body.wait,
+ }
+ try:
+ raw = await client.post("/api/v1/content/write", json=payload)
+ except OVError as exc:
+ raise _forward(exc) from exc
+ return AddMemoryResponse(uri=uri, raw=raw if isinstance(raw, dict) else {})
+
+
+ "/tools/ov_list_memories",
+ operation_id="ov_list_memories",
+ summary="List entries under viking://user/memories/.",
+)
+async def ov_list_memories(
+ body: ListMemoriesRequest,
+ client: OVClient = Depends(get_client),
+ settings: Settings = Depends(get_settings),
+) -> Dict[str, Any]:
+ """Browse the memories directory via /api/v1/fs/ls."""
+ params = {
+ "uri": settings.memories_uri,
+ "recursive": str(body.recursive).lower(),
+ "node_limit": body.limit,
+ }
+ try:
+ return await client.get("/api/v1/fs/ls", params=params)
+ except OVError as exc:
+ raise _forward(exc) from exc
+
+
+ "/tools/ov_read_resource",
+ operation_id="ov_read_resource",
+ summary="Read text content of any viking:// URI.",
+)
+async def ov_read_resource(
+ body: ReadResourceRequest,
+ client: OVClient = Depends(get_client),
+) -> Dict[str, Any]:
+ """Read full text content via /api/v1/content/read."""
+ params: Dict[str, Any] = {
+ "uri": body.uri,
+ "offset": body.offset,
+ "limit": body.limit,
+ }
+ try:
+ return await client.get("/api/v1/content/read", params=params)
+ except OVError as exc:
+ raise _forward(exc) from exc
+
+
+ "/tools/ov_add_resource",
+ operation_id="ov_add_resource",
+ summary="Ingest a remote URL or path-reachable file as an OpenViking resource.",
+)
+async def ov_add_resource(
+ body: AddResourceRequest,
+ client: OVClient = Depends(get_client),
+) -> Dict[str, Any]:
+ """POST /api/v1/resources to start ingestion."""
+ payload = {
+ "path": body.path,
+ "reason": body.reason,
+ "instruction": body.instruction,
+ "wait": body.wait,
+ }
+ if body.to:
+ payload["to"] = body.to
+ if body.parent:
+ payload["parent"] = body.parent
+ try:
+ return await client.post("/api/v1/resources", json=payload)
+ except OVError as exc:
+ raise _forward(exc) from exc
+
+
+ "/tools/ov_session_status",
+ operation_id="ov_session_status",
+ summary="Get OpenViking session metadata (counts, archive state, pending tokens).",
+)
+async def ov_session_status(
+ body: SessionStatusRequest,
+ client: OVClient = Depends(get_client),
+) -> Dict[str, Any]:
+ """GET /api/v1/sessions/{session_id}."""
+ try:
+ return await client.get(f"/api/v1/sessions/{body.session_id}")
+ except OVError as exc:
+ raise _forward(exc) from exc
diff --git a/examples/openwebui-plugin/pyproject.toml b/examples/openwebui-plugin/pyproject.toml
new file mode 100644
index 000000000..c3ff36663
--- /dev/null
+++ b/examples/openwebui-plugin/pyproject.toml
@@ -0,0 +1,36 @@
+[build-system]
+requires = ["setuptools>=68", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "openviking-openwebui"
+version = "0.1.0"
+description = "OpenAPI tool server that exposes a curated set of OpenViking endpoints to Open WebUI."
+readme = "README.md"
+requires-python = ">=3.9"
+license = { text = "AGPL-3.0" }
+authors = [{ name = "OpenViking Contributors" }]
+keywords = ["openviking", "open-webui", "openwebui", "openapi", "tools", "memory"]
+dependencies = [
+ "fastapi>=0.110",
+ "uvicorn[standard]>=0.27",
+ "httpx>=0.27",
+ "pydantic>=2.5",
+]
+
+[project.optional-dependencies]
+test = [
+ "pytest>=8",
+ "pytest-asyncio>=0.23",
+ "respx>=0.21",
+]
+
+[project.scripts]
+openviking-openwebui = "openviking_openwebui.__main__:main"
+
+[tool.setuptools.packages.find]
+include = ["openviking_openwebui*"]
+
+[tool.pytest.ini_options]
+asyncio_mode = "auto"
+testpaths = ["tests"]
diff --git a/examples/openwebui-plugin/tests/__init__.py b/examples/openwebui-plugin/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/examples/openwebui-plugin/tests/test_tools.py b/examples/openwebui-plugin/tests/test_tools.py
new file mode 100644
index 000000000..e8e872402
--- /dev/null
+++ b/examples/openwebui-plugin/tests/test_tools.py
@@ -0,0 +1,198 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Tests for the OpenWebUI tool server.
+
+Each test mocks the OpenViking HTTP layer with respx and asserts that the
+matching tool route forwards the right method, path, body, and tenant
+headers, and returns a payload matching its Pydantic model.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+import respx
+
+from openviking_openwebui.config import Settings
+from openviking_openwebui.server import create_app
+
+
+SETTINGS = Settings(
+ endpoint="http://ov.test",
+ api_key="key-xyz",
+ account="acct",
+ user="alice",
+ agent="webui",
+ bind="0.0.0.0:8765",
+ timeout_seconds=5.0,
+)
+
+
+async def client():
+ app = create_app(SETTINGS)
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
+ async with app.router.lifespan_context(app):
+ yield c
+
+
+def _assert_headers(request: httpx.Request) -> None:
+ assert request.headers["authorization"] == "Bearer key-xyz"
+ assert request.headers["x-openviking-account"] == "acct"
+ assert request.headers["x-openviking-user"] == "alice"
+ assert request.headers["x-openviking-actor-peer"] == "webui"
+
+
+async def test_ov_search_calls_find(client: httpx.AsyncClient) -> None:
+ route = respx.post("http://ov.test/api/v1/search/find").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "status": "ok",
+ "result": {
+ "memories": [
+ {"uri": "viking://user/memories/a.md", "score": 0.9, "snippet": "hi"}
+ ],
+ "resources": [],
+ },
+ },
+ )
+ )
+ resp = await client.post("/tools/ov_search", json={"query": "hello", "limit": 5})
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["hits"][0]["uri"] == "viking://user/memories/a.md"
+ assert data["hits"][0]["score"] == pytest.approx(0.9)
+ assert route.called
+ sent = route.calls.last.request
+ _assert_headers(sent)
+ body = httpx.Request("POST", "x", json={}).read # placeholder for typing
+ assert b'"query":"hello"' in route.calls.last.request.content.replace(b" ", b"")
+
+
+async def test_ov_recall_scopes_to_memories(client: httpx.AsyncClient) -> None:
+ route = respx.post("http://ov.test/api/v1/search/find").mock(
+ return_value=httpx.Response(200, json={"result": {"memories": []}})
+ )
+ resp = await client.post("/tools/ov_recall_memories", json={"query": "prefs", "limit": 3})
+ assert resp.status_code == 200
+ sent = route.calls.last.request
+ _assert_headers(sent)
+ raw = sent.content.decode()
+ assert "viking://user/memories/" in raw
+ assert '"limit":3' in raw.replace(" ", "")
+
+
+async def test_ov_add_memory_writes_under_memories(client: httpx.AsyncClient) -> None:
+ route = respx.post("http://ov.test/api/v1/content/write").mock(
+ return_value=httpx.Response(200, json={"status": "ok", "result": {"bytes": 10}})
+ )
+ resp = await client.post(
+ "/tools/ov_add_memory",
+ json={"name": "profile.md", "content": "I like Rust", "mode": "replace"},
+ )
+ assert resp.status_code == 200, resp.text
+ data = resp.json()
+ assert data["uri"] == "viking://user/memories/profile.md"
+ sent = route.calls.last.request
+ _assert_headers(sent)
+ raw = sent.content.decode()
+ assert "viking://user/memories/profile.md" in raw
+ assert "I like Rust" in raw
+
+
+async def test_ov_list_memories_calls_fs_ls(client: httpx.AsyncClient) -> None:
+ route = respx.get("http://ov.test/api/v1/fs/ls").mock(
+ return_value=httpx.Response(200, json={"status": "ok", "result": {"entries": []}})
+ )
+ resp = await client.post("/tools/ov_list_memories", json={"recursive": True, "limit": 50})
+ assert resp.status_code == 200
+ sent = route.calls.last.request
+ _assert_headers(sent)
+ assert "uri=viking%3A%2F%2Fuser%2Fmemories%2F" in str(sent.url)
+ assert "recursive=true" in str(sent.url)
+ assert "node_limit=50" in str(sent.url)
+
+
+async def test_ov_read_resource_calls_content_read(client: httpx.AsyncClient) -> None:
+ route = respx.get("http://ov.test/api/v1/content/read").mock(
+ return_value=httpx.Response(200, json={"status": "ok", "result": "body"})
+ )
+ resp = await client.post(
+ "/tools/ov_read_resource",
+ json={"uri": "viking://resources/a.md", "offset": 0, "limit": -1},
+ )
+ assert resp.status_code == 200
+ sent = route.calls.last.request
+ _assert_headers(sent)
+ assert "uri=viking%3A%2F%2Fresources%2Fa.md" in str(sent.url)
+
+
+async def test_ov_add_resource_posts_resources(client: httpx.AsyncClient) -> None:
+ route = respx.post("http://ov.test/api/v1/resources").mock(
+ return_value=httpx.Response(
+ 200, json={"status": "ok", "result": {"root_uri": "viking://x"}}
+ )
+ )
+ resp = await client.post(
+ "/tools/ov_add_resource",
+ json={"path": "https://example.com/doc.md", "wait": True},
+ )
+ assert resp.status_code == 200
+ sent = route.calls.last.request
+ _assert_headers(sent)
+ raw = sent.content.decode()
+ assert "https://example.com/doc.md" in raw
+ assert '"wait":true' in raw.replace(" ", "")
+
+
+async def test_ov_session_status_gets_session(client: httpx.AsyncClient) -> None:
+ route = respx.get("http://ov.test/api/v1/sessions/sess-42").mock(
+ return_value=httpx.Response(200, json={"status": "ok", "result": {"session_id": "sess-42"}})
+ )
+ resp = await client.post("/tools/ov_session_status", json={"session_id": "sess-42"})
+ assert resp.status_code == 200
+ sent = route.calls.last.request
+ _assert_headers(sent)
+ assert sent.url.path == "/api/v1/sessions/sess-42"
+
+
+async def test_error_pass_through(client: httpx.AsyncClient) -> None:
+ respx.post("http://ov.test/api/v1/search/find").mock(
+ return_value=httpx.Response(404, json={"error": {"code": "NOT_FOUND", "message": "nope"}})
+ )
+ resp = await client.post("/tools/ov_search", json={"query": "x"})
+ assert resp.status_code == 404
+ body = resp.json()
+ assert body["detail"]["error"]["code"] == "NOT_FOUND"
+
+
+async def test_openapi_lists_seven_tools(client: httpx.AsyncClient) -> None:
+ resp = await client.get("/openapi.json")
+ assert resp.status_code == 200
+ spec = resp.json()
+ op_ids = {
+ op.get("operationId")
+ for path in spec["paths"].values()
+ for op in path.values()
+ if isinstance(op, dict)
+ }
+ expected = {
+ "ov_search",
+ "ov_recall_memories",
+ "ov_add_memory",
+ "ov_list_memories",
+ "ov_read_resource",
+ "ov_add_resource",
+ "ov_session_status",
+ }
+ assert expected.issubset(op_ids)