Skip to content

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

feat(mcp): add an add_skill tool and make skills findable over MCP (#5160)

t0saki6b127eb92ccd
diff --git a/docs/en/agent-integrations/10-opencode.md b/docs/en/agent-integrations/10-opencode.md
index be1e0a14d..b92e9a3fc 100644
--- a/docs/en/agent-integrations/10-opencode.md
+++ b/docs/en/agent-integrations/10-opencode.md
@@ -140,11 +140,11 @@ 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 (15 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 (16 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_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`
+- `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`, `openviking_add_skill`
- `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`
Ask OpenCode to search or browse OpenViking memory. Runtime state and errors are written to:
diff --git a/docs/en/agent-integrations/13-trae.md b/docs/en/agent-integrations/13-trae.md
index f902194c8..fcf302e9a 100644
--- a/docs/en/agent-integrations/13-trae.md
+++ b/docs/en/agent-integrations/13-trae.md
@@ -68,7 +68,7 @@ TRAE and TRAE CN read `hooks.json` directly and need no such approval — restar
- `UserPromptSubmit` recalls and injects context for the current request.
- `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.
- `Stop` captures and immediately commits the completed turn, including short sessions.
-- The OpenViking MCP server transparently exposes the full server MCP tool set (15 tools): `find`, `search`, `read`, `list`, `tree`, `remember`, `write`, `edit`, `add_resource`, `list_watches`, `cancel_watch`, `grep`, `glob`, `forget`, and `health`. `search` with `mode="context"` returns assembled context.
+- The OpenViking MCP server transparently exposes the full server MCP tool set (16 tools): `find`, `search`, `read`, `list`, `tree`, `remember`, `write`, `edit`, `add_resource`, `add_skill`, `list_watches`, `cancel_watch`, `grep`, `glob`, `forget`, and `health`. `search` with `mode="context"` returns assembled context.
## Verify
diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md
index 4ced0aadf..7023baa61 100644
--- a/docs/en/agent-integrations/16-capability-reference.md
+++ b/docs/en/agent-integrations/16-capability-reference.md
@@ -21,31 +21,31 @@
## 1.1 Active tool surface (agentic calls)
-- **MCP-based harnesses (claude-code, codex/trae-cli, cursor, trae/trae-cn, zcode, opencode) share an identical active tool surface comprising 15 tools.** The server centrally defines these tools. The plugin reads `~/.openviking/ovcli.conf` via its proxy and establishes a connection to the server-defined MCP tools.
+- **MCP-based harnesses (claude-code, codex/trae-cli, cursor, trae/trae-cn, zcode, opencode) share an identical active tool surface comprising 16 tools.** The server centrally defines these tools. The plugin reads `~/.openviking/ovcli.conf` via its proxy and establishes a connection to the server-defined MCP tools.
- `trae-cli` means TraeCode CLI 2.0 (2.0 only). It is installed via a `codex` plugin alias and maintains format compatibility with `codex`. Therefore, it is consolidated into the `codex` row in the matrices below.
| harness | tool surface | tools (enabled by default) | search memory | search resource | search skill | write memory | write resource | write skill | delete type boundary |
|---|---|---|---|---|---|---|---|---|---|
-| claude-code | MCP passthrough | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |
-| codex / trae-cli | MCP passthrough | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |
-| cursor | MCP passthrough | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |
-| trae / trae-cn | MCP passthrough | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |
-| zcode | MCP passthrough | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |
-| opencode | MCP passthrough (host adds an `openviking_` prefix) | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |
-| dsh | MCP passthrough (`@deepseek-ai/dsh-mcp-client` → the shared stdio proxy; host adds an `mcp__openviking__` prefix) | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | no type distinction² |
+| claude-code | MCP passthrough | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
+| codex / trae-cli | MCP passthrough | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
+| cursor | MCP passthrough | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
+| trae / trae-cn | MCP passthrough | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
+| zcode | MCP passthrough | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
+| opencode | MCP passthrough (host adds an `openviking_` prefix) | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
+| dsh | MCP passthrough (`@deepseek-ai/dsh-mcp-client` → the shared stdio proxy; host adds an `mcp__openviking__` prefix) | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | no type distinction² |
| pi | native registration (7 × `viking_*`) | 7 (registration runs preflight checks⁴) | ✅ | ✅ | ✅ | ✅ `viking_remember` | ✅ `viking_add_resource` (URL only) | ❌ | no type distinction; delete by query needs score>0.8³ |
| openclaw | native registration (15 × `memory_*`/`ov_*` and friends) | 15 (14 on by default⁵) | ✅ `memory_recall` | ✅ `ov_search` (both scopes by default) | ✅ `ov_search` | ✅ `memory_store` | off by default⁵ | ✅ `add_skill` | memory-only allowlist + auto-delete only for a single candidate with score≥0.85 |
| hermes | native registration (6 × `viking_*`) | 6 (all on once the provider is active) | ✅ | ✅ | ✅ | ✅ `viking_remember` (writes the file directly, no extraction) | ✅ multi-protocol ingest (HTTP/Git/SSH/local file/directory zip) | ❌ | memory-only + `.md` leaf check |
| ov CLI | CLI commands | ~40 command groups | ✅ `ov find` | ✅ `ov find` | ✅ `ov find` | ✅ `ov add-memory` | ✅ `ov add-resource` | ✅ `ov add-skill` | `ov rm` executes directly (TUI deletion asks for confirmation and blocks root/scope deletes) |
-¹ MCP `write` can target `viking://resources`, `viking://user`, or `viking://agent`. Adding skills via MCP is not yet supported; use the openclaw `add_skill` tool, `ov add-skill` CLI, or the REST API instead.
+¹ MCP `write` rejects the user's own `skills/` subtree; under `viking://agent/skills` it writes a plain file that skips skill installation (no frontmatter abstract, no privacy extraction), so use `add_skill` there too. Skills are created, installed, and replaced through the MCP `add_skill` tool (inline SKILL.md text, a Git URL, or a signed upload of a local directory or zip), which shares one install implementation with REST `POST /api/v1/skills`.
² MCP `forget` does not differentiate between memory, resource, and skill types. However, the storage layer protects namespace roots: deletion requests for bare `viking://`, `viking://user`, and `viking://agent` are rejected. See [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).
³ For `viking_forget` on pi: the `recursive` flag is strictly set to false (directories are never deleted), and deleting by query requires a match score > 0.8.
⁴ The `pi` harness registers its tools only if the session misses `bypassSessionPatterns`, `client.health()` passes, and `ensureSession` succeeds (`index.ts:66-108`). If the health check fails, no tools are registered for that session.
⁵ The `add_resource` tool in openclaw requires a double opt-in before activation.
-**Skill addition/deletion boundaries**: Skills can be added via the openclaw `add_skill` tool (enabled by default), the `ov add-skill` CLI command, or the REST API. Deletion operates across four tiers, detailed in [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).
+**Skill addition/deletion boundaries**: Skills can be added via the MCP `add_skill` tool, the openclaw `add_skill` tool (enabled by default), the `ov add-skill` CLI command, or the REST API. Deletion operates across four tiers, detailed in [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).
## 1.2 Automatic hook surface (driven by the harness)
@@ -87,21 +87,22 @@ These tools are defined on the server side, and future updates will be centrally
| # | Tool | What it does | Key parameters (definition line) |
|---|---|---|---|
-| 1 | `find` | Fast semantic search requiring no session context | `query, target_uri="", limit=10, min_score=0.35, level, context_type` (`:259`) |
-| 2 | `search` | Deep search, featuring optional `session_id` integration and intent analysis | The session is only loaded if the server has `retrieval.enable_intent` enabled (defaults to true) (`:285`, `:302-304`) |
-| 3 | `read` | Read the full text of one or more `viking://` files | Uses a concurrency semaphore of 10; a single failure yields `(nothing found at <uri>)` rather than raising an exception (`:389`) |
-| 4 | `list` | List a directory (function name `ls`, explicitly registered as `list`) | `recursive=False` (`:423`) |
-| 5 | `tree` | Recursive directory tree | `level_limit=3, node_limit=1000, include_abstract=False` (`:449`) |
-| 6 | `remember` | Write long-term memory | Internally creates a one-shot session (`mcp-store-<uuid12>`) and immediately calls `commit_async` (`:504-523`). This is the only commit entry point on the MCP surface, as there is no explicit commit tool. |
-| 7 | `write` | Write a `viking://` file | `mode=replace\|append\|create`; `replace` falls back to `create` if not found. New files must use an extension from the allowlist: `.md .txt .json .yaml .yml .toml .py .js .ts`. Writable domains are limited to `resources/user/agent`; directories like `skills/`, `peers/`, `privacy/`, and `sessions/` under the user root are read-only. Existing `.abstract.md` / `.overview.md` sidecars may be body-updated, but public APIs cannot create them (`:529`; `content_write.py:60-81`) |
-| 8 | `edit` | Exact string replacement | Supplying an empty `old_string`, finding zero matches, or finding multiple matches without `replace_all` will raise an error and leave the file content unchanged (`:569`) |
-| 9 | `add_resource` | Resource ingestion (remote URL / signed upload of a local file / Connector) | `watch_interval` is defined in minutes (0 disables watching). The local-path branch generates a signed upload URL (default TTL of 600s), and ingestion triggers automatically post-upload without requiring a subsequent API call (`:723-947`) |
-| 10 | `list_watches` | List watch subscriptions; not yet supported on the commercial edition | Returns an error string if the scheduler is not running (`:958`) |
-| 11 | `cancel_watch` | Cancel by `to_uri`; not yet supported on the commercial edition | Deliberately does not expose pause/resume/trigger/update (`:990`) |
-| 12 | `grep` | Regex content search | Multiple patterns run concurrently (semaphore of 10), `node_limit=10` (`:1032`) |
-| 13 | `glob` | Filename glob | `node_limit=100` (`:1084`) |
-| 14 | `forget` | Permanently deletes a URI (unrecoverable) | `recursive=False` by default; type boundaries in [§3.5](#_3-5-type-boundaries-for-writes-and-deletes) (`:1110-1117`) |
-| 15 | `health` | Health check | No parameters (`:1123`) |
+| 1 | `find` | Fast semantic search requiring no session context | `query, target_uri="", limit=10, min_score=0.35, level, context_type, read_content`; `context_type="skill"` on its own routes to `SearchService.find_skills` (package retrieval, `skill_package_retriever.py`): one hit per skill package, the URI rewritten to `<package>/SKILL.md`, the summary read from the package's own abstract, and `read_content` reading that file. Without `target_uri` it searches both `viking://~/skills` and `viking://agent/skills`. Any other `context_type` combination, and a filter-only query with no query text, stay on the generic retrieval path; the URI rewrite and the one-line-per-package collapse still apply when rendering (`:262`) |
+| 2 | `search` | Deep search, featuring optional `session_id` integration and intent analysis | The session is only loaded if the server has `retrieval.enable_intent` enabled (defaults to true) (`:315`). Skills are retrieved per item here and only collapsed when rendering, so a package matching in several files spends several `limit` slots and keeps the matching file's summary |
+| 3 | `read` | Read the full text of one or more `viking://` files | Uses a concurrency semaphore of 10; a single failure yields `(nothing found at <uri>)` rather than raising an exception (`:643`) |
+| 4 | `list` | List a directory (function name `ls`, explicitly registered as `list`) | `recursive=False` (`:784`) |
+| 5 | `tree` | Recursive directory tree | `level_limit=3, node_limit=1000, include_abstract=False`; `include_abstract=true` prints each directory's abstract (up to 1024 chars), so `tree(uri="viking://~/skills", level_limit=1, include_abstract=true)` lists every skill with its description (`:862`) |
+| 6 | `remember` | Write long-term memory | Internally creates a one-shot session (`mcp-store-<uuid12>`) and immediately calls `commit_async` (`:940`). This is the only commit entry point on the MCP surface, as there is no explicit commit tool. |
+| 7 | `write` | Write a `viking://` file | `mode=replace\|append\|create`; `replace` falls back to `create` if not found. New files must use an extension from the allowlist: `.md .txt .json .yaml .yml .toml .py .js .ts`. Writable domains are limited to `resources/user/agent`; directories like `skills/`, `peers/`, `privacy/`, and `sessions/` under the user root are read-only. Existing `.abstract.md` / `.overview.md` sidecars may be body-updated, but public APIs cannot create them. A write under `viking://agent/skills` is not refused but skips skill installation, so use `add_skill` for skills; see [§3.5](#_3-5-type-boundaries-for-writes-and-deletes) (`:965`; `content_write.py:60-81`) |
+| 8 | `edit` | Exact string replacement | Supplying an empty `old_string`, finding zero matches, or finding multiple matches without `replace_all` will raise an error and leave the file content unchanged. Editing a file inside a skill package does not re-run skill installation; see [§3.5](#_3-5-type-boundaries-for-writes-and-deletes) (`:1005`) |
+| 9 | `add_resource` | Resource ingestion (remote URL / signed upload of a local file / Connector) | `watch_interval` is defined in minutes (0 disables watching). The local-path branch generates a signed upload URL (default TTL of 600s), and ingestion triggers automatically post-upload without requiring a subsequent API call (`:1161`) |
+| 10 | `add_skill` | Create, install, or replace skills | `data` (full SKILL.md text) or `path` (Git URL / GitHub tree URL, or a local SKILL.md, directory, or zip — the local branch returns a signed upload URL like `add_resource`); `skills=[...]` selects from a multi-skill source, `list_only=true` previews it; `target_uri="viking://agent/skills"` shares with the account. Same install code as REST `POST /api/v1/skills`. The tool description names it the one entry point for creating and updating a skill, and points deletion at `ov skills remove` or Studio (`:1452`) |
+| 11 | `list_watches` | List watch subscriptions; not yet supported on the commercial edition | Returns an error string if the scheduler is not running (`:1621`) |
+| 12 | `cancel_watch` | Cancel by `to_uri`; not yet supported on the commercial edition | Deliberately does not expose pause/resume/trigger/update (`:1653`) |
+| 13 | `grep` | Regex content search | Multiple patterns run concurrently (semaphore of 10), `node_limit=10` (`:1696`) |
+| 14 | `glob` | Filename glob | `node_limit=100` (`:1765`) |
+| 15 | `forget` | Permanently deletes a URI (unrecoverable) | `recursive=False` by default; type boundaries in [§3.5](#_3-5-type-boundaries-for-writes-and-deletes) (`:1791`) |
+| 16 | `health` | Health check | No parameters (`:1808`) |
Supporting mechanisms:
@@ -473,7 +474,7 @@ There are three primary guards on MCP `write` and REST `content/write` (`content
**Tier 4: No deletion offered by default (LangChain / Open WebUI).** LangChain's `viking_forget` is only exposed as a tool when configured with `profile="admin"` or `allow_forget=True`. Open WebUI does not offer any deletion tools.
-**Add/delete boundary for skills:** The entry points for adding skills are openclaw's `add_skill` (enabled by default), `ov add-skill`, and REST. The delete surfaces that remain entirely read-only for skills (permitting neither addition nor deletion) are openclaw's `memory_forget` and hermes' `viking_forget`. Conversely, the MCP surface, dsh, Pi, and `ov rm` cannot *add* a skill but can *delete* one. This is because addition is blocked by `_USER_MANAGED_SUBTREES` on the write path, whereas deletion succeeds because the delete path does not check that specific constraint.
+**Add/delete boundary for skills:** The entry points for adding skills are the MCP `add_skill` tool, openclaw's `add_skill` (enabled by default), `ov add-skill`, and REST; `add_resource` refuses skill URIs, and MCP `write` refuses the user's own `skills/` subtree (`_USER_MANAGED_SUBTREES`); under `viking://agent/skills`, `write` is not refused yet but bypasses skill installation. The delete surfaces that remain entirely read-only for skills (permitting neither addition nor deletion) are openclaw's `memory_forget` and hermes' `viking_forget`. The MCP `forget` tool, dsh, Pi, and `ov rm` can delete a skill directory because the delete path does not check that constraint, but only `ov skills remove` and the REST `DELETE /api/v1/skills/{name}` also remove the skill's privacy configuration.
## 3.6 Degradation and fault tolerance
### 3.6.1 Decision matrix
@@ -519,7 +520,7 @@ Each card serves as a quick-reference entry point. It records only the facts and
## claude-code
- **Integration docs**: [Claude Code Memory Plugin](./02-claude-code.md)
-- **Form**: A Claude Code plugin (marketplace) featuring a four-in-one architecture: 9 hooks, an MCP proxy (passing through 15 tools), a slash command, a statusline, and 1 experience skill. Version 0.5.1.
+- **Form**: A Claude Code plugin (marketplace) featuring a four-in-one architecture: 9 hooks, an MCP proxy (passing through 16 tools), a slash command, a statusline, and 1 experience skill. Version 0.5.1.
- **Capability highlights**: The harness with the broadest hook coverage — `SessionStart` (120s) / `UserPromptSubmit` (60s) / `PostToolUse:Read` (5s, the skill-experience hook, off by default) / `PreToolUse:Read|Glob|Grep|Edit|Write|Bash` (5s, `uri-guard`: denies a file tool whose path is a `viking://` URI, adds a notice to a Bash command that carries one) / `Stop` (45s) / `PreCompact` (30s) / `SessionEnd` (30s) / `SubagentStart` (10s) / `SubagentStop` (45s). Recall digesting is enabled by default (local `claude -p`, falling back to the server-side rewrite automatically when the local CLI is unavailable, [§3.2.5](#_3-2-5-recall-digest)). Provides full sub-session isolation via `SubagentStart`/`Stop` ([§3.3.5](#_3-3-5-subagent-session-comparison)), along with a statusline, slash command, and `uri-guard`. All shutdown paths except `kill -9` trigger a commit ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).
- **Behavior notes**: The session ID format is `cc-<raw_CC_session_id>`, while subagents use `…__subagent-<agent_id>`. `Stop` commits at a threshold of 20000 (keep 10), and `PreCompact` commits synchronously. Automatic recall excludes resources ([§3.2.1](#_3-2-1-mechanism-foundation-one-shared-pipeline-two-server-side-paths)). The incremental cursor is stored in `/tmp` (if cleared by the system, the entire session is pushed again).
- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.claude_code`), and `ov.conf` (`claude_code` as per [§3.1.4](#_3-1-4-configuration-layers)), offering roughly 70 tunable parameters. The compressor command and model are hardcoded to `claude`/`sonnet`/`low`/30s.
@@ -670,13 +671,13 @@ If your preferred agent or harness is not among the 11 listed previously, you ca
| Path | Effort | Agent-initiated tool surface | Auto recall/capture hooks | Session/commit | Compaction takeover |
|---|---|---|---|---|---|
-| ① [Direct MCP connection](./06-mcp-clients.md) | Minutes (fill in one config block) | ✅ All 15 tools | ❌ The model calls them itself | Only `remember` creates a temporary session | ❌ |
+| ① [Direct MCP connection](./06-mcp-clients.md) | Minutes (fill in one config block) | ✅ All 16 tools | ❌ The model calls them itself | Only `remember` creates a temporary session | ❌ |
| ② HTTP API / SDK / [LangChain](./07-langchain-langgraph.md) | Hours (requires code) | Flexible (call REST as needed) | Custom implementation | Custom implementation (or use the LangChain middleware) | ❌ |
-| ③ Reuse shared-core / the [Agent Plugins portable package](./15-agent-plugins.md) | Days (requires hook adapters) | ✅ 15 tools (through the MCP proxy) | ✅ Full recall/capture/commit/pending set | ✅ | Depends on which events you wire up |
+| ③ Reuse shared-core / the [Agent Plugins portable package](./15-agent-plugins.md) | Days (requires hook adapters) | ✅ 16 tools (through the MCP proxy) | ✅ Full recall/capture/commit/pending set | ✅ | Depends on which events you wire up |
## 6.2 Path ①: Direct MCP connection (recommended starting point)
-Any MCP-capable agent simply needs to point its `mcpServers` configuration to the server's `/mcp` endpoint (refer to [MCP Clients](./06-mcp-clients.md) to locate this configuration for each client). Doing so instantly unlocks all 15 tools ([§2.1](#_2-1-server-side-mcp-tool-surface)). The minimal configuration looks like this:
+Any MCP-capable agent simply needs to point its `mcpServers` configuration to the server's `/mcp` endpoint (refer to [MCP Clients](./06-mcp-clients.md) to locate this configuration for each client). Doing so instantly unlocks all 16 tools ([§2.1](#_2-1-server-side-mcp-tool-surface)). The minimal configuration looks like this:
```json
{
@@ -718,8 +719,8 @@ If you need the full spectrum of automation—recall, capture, commit, and pendi
|---|---|---|---|---|---|
| **A. [Open WebUI](./08-community-plugins.md)** | Standalone FastAPI OpenAPI tool server | 7 local OpenAPI routes (`ov_search`/`ov_recall_memories`/`ov_add_memory`/`ov_list_memories`/`ov_read_resource`/`ov_add_resource`/`ov_session_status`), no deletion tool | No session concept | Most lightweight: bare `httpx`, no retries or negative caching; `/health` only echoes the config and does not probe OpenViking. | Inactive until the process is explicitly started. |
| **B. [LangChain/LangGraph](./07-langchain-langgraph.md)** | Python SDK adapter layer (retriever/tools/store/middleware/recorder) | `create_openviking_tools()` provides 12 StructuredTools (`viking_forget` is not in the agent profile by default) | `thread_id`/`session_id` come from the caller; `CommitPolicy` defaults to `never` | Most robust in this group: read-only methods automatically retry once, writes never retry (to prevent duplicates), and partial successes raise a structured exception that can be retried as a slice. | Requires explicit construction before taking effect. |
-| **C. [Agent Plugins 1.0](./15-agent-plugins.md)** | Portable package: `plugin.json` + `skills/` + `mcp.json` (stdio→HTTP proxy) | MCP passthrough for all 15 tools; intentionally excludes hooks (recall relies on a skill instructing the model). | Only `remember` creates a temporary session | Retries handled at the MCP proxy layer (401/403 triggers credential swap, 400/404 triggers re-initialization; max 1 retry each). | Active as soon as loaded by the client. |
-| **D. [Direct MCP Connection](./06-mcp-clients.md)** | No local components, connects straight to `/mcp` | Same as C (15 tools) | Same as C | Depends entirely on the client. | `/mcp` is always on. |
+| **C. [Agent Plugins 1.0](./15-agent-plugins.md)** | Portable package: `plugin.json` + `skills/` + `mcp.json` (stdio→HTTP proxy) | MCP passthrough for all 16 tools; intentionally excludes hooks (recall relies on a skill instructing the model). | Only `remember` creates a temporary session | Retries handled at the MCP proxy layer (401/403 triggers credential swap, 400/404 triggers re-initialization; max 1 retry each). | Active as soon as loaded by the client. |
+| **D. [Direct MCP Connection](./06-mcp-clients.md)** | No local components, connects straight to `/mcp` | Same as C (16 tools) | Same as C | Depends entirely on the client. | `/mcp` is always on. |
| **E. [Log Ingestion](./09-log-ingestion.md)** | `openviking-server ingest` CLI (runs on the machine hosting the logs, importing them in reverse) | None (write-only, no recall) | Session ID `{prefix}__{harness}__{sanitized native id}`; commit token 6000 / idle 5s / keep 0 | The only integration featuring crash recovery: utilizes a SQLite cursor store, single-instance locking, and a reconciliation process to verify batch delivery. | Disabled by default on two levels (`ingest.enabled` and each harness's individual `enabled` flag are both false); adapters available for claude_code, codex, hermes, opencode, openclaw, and cursor. |
| **F. [OpenViking Helper](./14-openviking-helper.md)** | Closed-source desktop app | — | — | — | Outside the scope of this codebase. |
diff --git a/docs/en/api/04-skills.md b/docs/en/api/04-skills.md
index 57f3c726d..e4762272e 100644
--- a/docs/en/api/04-skills.md
+++ b/docs/en/api/04-skills.md
@@ -174,6 +174,8 @@ Skills are a special type of resource that define actions or tools agents can pe
- `sdk/python/openviking_sdk/client.py:AsyncHTTPClient.add_skill` - Python SDK entry point
- `openviking_cli/client/http.py` - Compatibility import forwarding to the Python SDK
- `openviking/server/routers/resources.py:add_skill` - HTTP router
+- `openviking/server/mcp_endpoint.py:add_skill` - MCP tool
+- `openviking/server/skill_ingest.py:install_skills` - Install implementation shared by the HTTP router, the MCP tool, and signed skill uploads
- `openviking/service/resource_service.py:ResourceService.add_skill` - Core service implementation
- `openviking/server/routers/skills.py` - List, find, read, validate, update, and delete endpoints
- `crates/ov_cli/src/commands/skills.rs` - CLI Skill command handlers
@@ -206,6 +208,7 @@ Supply at least one of `data` or `temp_file_id`. The current server gives upload
- First call `POST /api/v1/resources/temp_upload` to upload a local `SKILL.md` or directory ZIP, then call `POST /api/v1/skills` with `temp_file_id`
- `temp_upload` defaults to local temporary storage; pass `upload_mode=shared` only when you explicitly need distributed shared temporary uploads. Python HTTP clients can set `upload.mode = "shared"` in `ovcli.conf`; the Rust `ov` CLI instead uses `OPENVIKING_UPLOAD_MODE=shared`.
- `POST /api/v1/skills` does not accept direct host filesystem paths in `data`.
+ - MCP clients use the `add_skill` tool: `data` takes SKILL.md text, and `path` takes a Git URL or a local path. For a local path the tool returns a one-time signed `temp_upload` URL; after the client POSTs the SKILL.md or ZIP there, the server installs it with the token-bound `target_uri`, `skills`, and `list_only`, and the upload response carries the install result.
- **Targeting**:
- Add requests use `target_uri` for the skills root; `to`, `parent`, and `root_uri` are not HTTP request fields. CLI `-p/--parent-auto-create` maps to `target_uri`.
@@ -604,7 +607,7 @@ The HTTP equivalent is `GET /api/v1/skills/search-web?include_content=true&inclu
The manifest includes `SKILL.md`, summaries, and auxiliary files/directories, but excludes `.source.json`. Integrity limits are **512 entries (including directories), 16 MiB per file, and 64 MiB total file bytes**, with read concurrency 8. Exceeding a limit returns `RESOURCE_EXHAUSTED`. Content, manifest, and revision are obtained under one tree lock, but later downloads can encounter updates; consumers should verify file hashes and recheck revision.
-Search and `get_skill` return content and manifests without executing scripts or installing files in an Agent sandbox. A Harness can read text remotely and download resources when a tool requires local paths. See [VikingBot Skills](../../../bot/docs/en/concepts/06-skills.md) for the complete consumer workflow.
+Search and `get_skill` return content and manifests without executing scripts or installing files in an Agent sandbox. A Harness can read text remotely and download resources when a tool requires local paths. See [VikingBot Skills](../../../bot/docs/en/concepts/06-skills.md) for the complete consumer workflow. MCP clients reach the same package-level behavior through the `find` tool with `context_type="skill"`; see [MCP Integration](../guides/06-mcp-integration.md).
### Search Skills
@@ -621,7 +624,7 @@ Search and `get_skill` return content and manifests without executing scripts or
Package hits are grouped by their full Skill root URI, ranked by their highest final score, then limited to `limit` Skills. Same-named Skills in different scopes remain distinct. `total` is the returned array length, not a count of all possible matches.
-Each Skill is represented by its highest-scoring package hit. The existing `uri`, `level`, `score`, and `abstract` fields come directly from that hit, without additional response fields. Package grouping and pagination apply only to dedicated `skills/find`; general `find/search` continues to return individual hits.
+Each Skill is represented by its highest-scoring package hit. The existing `uri`, `level`, `score`, and `abstract` fields come directly from that hit, without additional response fields. Package grouping and pagination apply to the dedicated `skills/find` endpoint and to the MCP `find` tool called with `context_type="skill"` alone; REST `find` / `search` continue to return individual hits. MCP `search` retrieves individual hits too, and only collapses them per package when rendering its answer.
| Response field | Meaning |
| --- | --- |
@@ -631,11 +634,11 @@ Each Skill is represented by its highest-scoring package hit. The existing `uri`
| `name` / `description` / `tags` / `allowed_tools` | Metadata read separately from the Skill root by the dedicated `skills/find` endpoint |
| `root_uri` / `skill_md_uri` | The Skill root and main `SKILL.md` addresses returned by the dedicated `skills/find` endpoint |
-The dedicated `skills/find` endpoint now returns the actual hit URI instead of replacing it with the package root. List and get-by-name responses are unchanged. `level=[2]` restricts matching to files and returns `level=2` with the URI of the highest-scoring file in each package.
+The dedicated `skills/find` endpoint now returns the actual hit URI instead of replacing it with the package root; the MCP `find` tool differs and rewrites every Skill hit to `<package root>/SKILL.md`. List and get-by-name responses are unchanged. `level=[2]` restricts matching to files and returns `level=2` with the URI of the highest-scoring file in each package.
-General search with `read_content=true` continues to read the returned URI. The dedicated `skills/find` endpoint does not accept this option.
+General search with `read_content=true` continues to read the returned URI — for MCP `find` with `context_type="skill"` that URI is the package's `SKILL.md`, not the file that matched. The dedicated `skills/find` endpoint does not accept this option.
-The URI rules above apply to semantic search. Filter-only general `find` retains the stored record URI and returns `score=0`, without adding summary-file suffixes for L0 or L1.
+The URI rules above apply to semantic search. A filter-only general `find` retains the stored record URI and returns `score=0`, without adding summary-file suffixes for L0 or L1; MCP `find` keeps such a query on that generic path, since package retrieval requires query text, but still rewrites each skill hit to its `SKILL.md`.
Scope, level, and permission filters apply before grouping; the Skill root must also be accessible.
diff --git a/docs/en/concepts/07-retrieval.md b/docs/en/concepts/07-retrieval.md
index 110432c39..8c8b804a8 100644
--- a/docs/en/concepts/07-retrieval.md
+++ b/docs/en/concepts/07-retrieval.md
@@ -95,7 +95,7 @@ Step 5: Convert to MatchedContext
|--------------|------------------|
| MEMORY | `viking://~/memories` |
| RESOURCE | `viking://resources` |
-| SKILL | `viking://~/skills` |
+| SKILL | `viking://~/skills` and `viking://agent/skills` |
### Recursive Search Algorithm
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index a936b7bf3..9395362d2 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -1774,7 +1774,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` tool 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=...`. | `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.md
index 2b55fd037..a5f3b14d8 100644
--- a/docs/en/guides/06-mcp-integration.md
+++ b/docs/en/guides/06-mcp-integration.md
@@ -129,24 +129,25 @@ If you already have HTTPS configured, just connect to `https://your-server.com/m
## Available MCP Tools
-Once connected, OpenViking exposes 15 tools:
+Once connected, OpenViking exposes 16 tools:
| Tool | Description | Key Parameters |
|------|-------------|----------------|
-| `find` | Fast semantic retrieval without session context | `query`, `target_uri` (optional), `limit`, `min_score`, `level` (optional), `context_type` (optional) |
-| `search` | Deep semantic retrieval; `mode="context"` assembles injection-ready context and replaces the former `recall` tool | `query`, `mode` (`list` or `context`), `target_uri` (list mode only), `session_id` (optional), `limit`, `min_score`, `level` (list mode), `context_type` (optional), 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`) |
+| `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) |
+| `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), 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) |
| `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 file's summary) |
+| `tree` | Show the recursive directory tree under a `viking://` URI, indented by depth — use when you need a full picture of the file tree (prefer `list` for a single level, `glob` for filename patterns) | `uri` (optional), `level_limit` (default 3), `node_limit` (default 1000), `offset`, `limit`, `include_abstract` (optional — also show each directory's summary; for a skill directory that is its name and description) |
| `remember` | Store messages into long-term memory (triggers extraction) | `messages` (list of `{role, content}`) |
-| `write` | Write text to a `viking://` file (create/overwrite/append). Parent directories are created automatically; use `read` first to see current content before overwriting, and prefer `edit` for changing part of an existing file | `uri`, `content`, `mode` (optional: `replace` default — overwrites or creates if missing; `append` — appends or creates if missing; `create` — fails if it exists), `wait` (optional, block until re-indexed), `timeout` (optional) |
-| `edit` | Replace an exact string with new text in an existing `viking://` file — for targeted changes instead of a full rewrite. The file is left unchanged if `old_string` is not found, or matches multiple times while `replace_all` is false | `uri`, `old_string`, `new_string`, `replace_all` (optional), `wait` (optional, block until re-indexed), `timeout` (optional) |
+| `write` | Write text to a `viking://` file (create/overwrite/append). Parent directories are created automatically; use `read` first to see current content before overwriting, and prefer `edit` for changing part of an existing file. Skill packages are not maintained this way: the caller's own `skills/` subtree is refused, and a write under `viking://agent/skills` produces a plain file that skips skill installation — use `add_skill` | `uri`, `content`, `mode` (optional: `replace` default — overwrites or creates if missing; `append` — appends or creates if missing; `create` — fails if it exists), `wait` (optional, block until re-indexed), `timeout` (optional) |
+| `edit` | Replace an exact string with new text in an existing `viking://` file — for targeted changes instead of a full rewrite. The file is left unchanged if `old_string` is not found, or matches multiple times while `replace_all` is false. Editing a file inside a skill package does not re-run skill installation — use `add_skill` | `uri`, `old_string`, `new_string`, `replace_all` (optional), `wait` (optional, block until re-indexed), `timeout` (optional) |
| `add_resource` | Add a local file or URL as a resource (local files trigger a progressive upload flow) | `path`, `temp_file_id` (optional), `description` (optional), `watch_interval` (optional, minutes — auto-refresh cadence for remote URLs), `processing_mode` (optional: `semantic_and_vectors` default, or `vectors_only` to skip VLM semantic understanding and only vectorize current files), `to` (optional, target `viking://resources/...` URI; if omitted when `watch_interval > 0`, the watch auto-binds to the resource's created URI), `args` (optional parser-specific options, including `{"parse_mode":"no_split"}` to parse each source document into one Markdown body, `{"feishu_access_token":"u-..."}` for one-time Feishu user-token imports, or access/refresh tokens plus an optional `feishu_app_id` / `feishu_app_secret` pair for Feishu user-token watches) |
+| `add_skill` | Create, install, or replace an agent skill. New skills pass the full SKILL.md text; Git and GitHub tree URLs install every skill in the source unless `skills` names some; a local SKILL.md, directory, or zip returns a signed upload URL like `add_resource` | `data` (SKILL.md text) or `path` (Git URL or local path), `skills` (optional), `target_uri` (optional; `viking://agent/skills` shares with the account), `list_only` (optional) |
| `list_watches` | List watch tasks (auto-refresh subscriptions) visible to the current agent. Each entry shows target URI, refresh interval (minutes), active/paused status, and next scheduled execution time | none |
| `cancel_watch` | Cancel (delete) a watch task by its target URI. To change the cadence or pause temporarily, cancel and re-add with a new `watch_interval` | `to_uri` (must match the watch task's `to` value, e.g. `viking://resources/...`) |
| `grep` | Regex content search across `viking://` files | `uri`, `pattern` (string or array), `case_insensitive`, `node_limit` |
| `glob` | Find files matching a glob pattern | `pattern`, `uri` (optional scope), `node_limit` |
-| `forget` | Delete any `viking://` URI (use `search` to find it first; pass `recursive=true` to delete a directory) | `uri`, `recursive` (optional) |
+| `forget` | Delete any `viking://` URI (use `search` to find it first; pass `recursive=true` to delete a directory). Deleting a skill directory this way leaves the skill's privacy configuration behind; remove a skill with `ov skills remove` or `DELETE /api/v1/skills/{name}` | `uri`, `recursive` (optional) |
| `health` | Check OpenViking service health | none |
To address your own workspace from an MCP tool, use the home alias `viking://~`. It
diff --git a/docs/zh/agent-integrations/10-opencode.md b/docs/zh/agent-integrations/10-opencode.md
index 6ca8f59bd..8540ff749 100644
--- a/docs/zh/agent-integrations/10-opencode.md
+++ b/docs/zh/agent-integrations/10-opencode.md
@@ -140,11 +140,11 @@ API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`
## 验证
-安装后重启 OpenCode。进入 OpenCode session 后,插件应暴露 `openviking` MCP server,透传服务端完整 MCP 工具集(15 个工具)。OpenCode 会给 MCP 工具加 `openviking_` 前缀:
+安装后重启 OpenCode。进入 OpenCode session 后,插件应暴露 `openviking` MCP server,透传服务端完整 MCP 工具集(16 个工具)。OpenCode 会给 MCP 工具加 `openviking_` 前缀:
- `openviking_find`、`openviking_search`(`openviking_search` 的 `mode="context"` 替代原 recall 工具)
- `openviking_read`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`
-- `openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`
+- `openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`、`openviking_add_skill`
- `openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`
可以让 OpenCode 搜索或浏览 OpenViking memory。运行时状态和错误日志会写入:
diff --git a/docs/zh/agent-integrations/13-trae.md b/docs/zh/agent-integrations/13-trae.md
index f8cab7b03..40da0ddf2 100644
--- a/docs/zh/agent-integrations/13-trae.md
+++ b/docs/zh/agent-integrations/13-trae.md
@@ -68,7 +68,7 @@ TRAE 和 TRAE CN 走 `hooks.json`,重启客户端后直接生效,没有这
- `UserPromptSubmit`:根据当前问题召回并注入相关内容。
- `PreToolUse`:在 TRAE 和 TRAE CN 上,`Read`、`Glob`、`Grep` 的路径是 `viking://` URI 时拒绝调用,并提示改用 OpenViking MCP 工具;`Bash` 或 `RunCommand` 命令带 `viking://` URI 时照常执行,同时附加改用建议。TraeCode CLI 2.0 使用 Codex 插件,它的 `PreToolUse` 只匹配 `Bash`,只附加同样的提示,不拒绝调用。
- `Stop`:捕获本轮消息并立即提交,使短会话也能进入记忆抽取流程。
-- OpenViking MCP Server:透传服务端完整 MCP 工具集(15 个工具):`find`、`search`、`read`、`list`、`tree`、`remember`、`write`、`edit`、`add_resource`、`list_watches`、`cancel_watch`、`grep`、`glob`、`forget`、`health`。其中 `search` 的 `mode="context"` 可返回组装后的上下文。
+- OpenViking MCP Server:透传服务端完整 MCP 工具集(16 个工具):`find`、`search`、`read`、`list`、`tree`、`remember`、`write`、`edit`、`add_resource`、`add_skill`、`list_watches`、`cancel_watch`、`grep`、`glob`、`forget`、`health`。其中 `search` 的 `mode="context"` 可返回组装后的上下文。
## 验证
diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md
index d44c0bba6..1a88c74e4 100644
--- a/docs/zh/agent-integrations/16-capability-reference.md
+++ b/docs/zh/agent-integrations/16-capability-reference.md
@@ -21,31 +21,31 @@
## 1.1 主动工具面(Agentic 调用能力)
-- **MCP 型 harness(claude-code、codex/trae-cli、cursor、trae/trae-cn、zcode、opencode)的主动工具面完全一致,共 15 个工具**:这些工具由服务端统一定义,插件通过代理获得 `~/.openviking/ovcli.conf` 配置后连接服务器定义的 MCP 工具。
+- **MCP 型 harness(claude-code、codex/trae-cli、cursor、trae/trae-cn、zcode、opencode)的主动工具面完全一致,共 16 个工具**:这些工具由服务端统一定义,插件通过代理获得 `~/.openviking/ovcli.conf` 配置后连接服务器定义的 MCP 工具。
- trae-cli 指 TraeCode CLI 2.0(仅支持 2.0),经 codex 插件别名安装,插件与 codex 格式兼容,下文矩阵并入 codex 行。
| harness | 工具面形态 | 工具数(默认开) | 搜 memory | 搜 resource | 搜 skill | 写 memory | 写 resource | 写 skill | 删除类型边界 |
|---|---|---|---|---|---|---|---|---|---|
-| claude-code | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |
-| codex / trae-cli | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |
-| cursor | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |
-| trae / trae-cn | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |
-| zcode | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |
-| opencode | MCP 透传(宿主加 `openviking_` 前缀) | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |
-| dsh | MCP 透传 | 15 | ✅ | ✅ | ✅ | ✅ | ✅ | ❌¹ | 无类型区分² |
+| claude-code | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
+| codex / trae-cli | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
+| cursor | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
+| trae / trae-cn | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
+| zcode | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
+| opencode | MCP 透传(宿主加 `openviking_` 前缀) | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
+| dsh | MCP 透传 | 16 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ `add_skill`¹ | 无类型区分² |
| pi | 原生注册(7 个 `viking_*`) | 7(注册需前置检查⁴) | ✅ | ✅ | ✅ | ✅ `viking_remember` | ✅ `viking_add_resource`(仅 URL) | ❌ | 无类型区分;query 删除需 score>0.8³ |
| openclaw | 原生注册(15 个 `memory_*`/`ov_*` 等) | 15(默认开 14⁵) | ✅ `memory_recall` | ✅ `ov_search`(默认双 scope) | ✅ `ov_search` | ✅ `memory_store` | 默认关⁵ | ✅ `add_skill` | memory-only 白名单 + 单候选 score≥0.85 才自动删 |
| hermes | 原生注册(6 个 `viking_*`) | 6(provider 激活即全开) | ✅ | ✅ | ✅ | ✅ `viking_remember`(直写文件,不走抽取) | ✅ 多协议摄取(HTTP/Git/SSH/本地文件/目录 zip) | ❌ | memory-only + `.md` 叶子校验 |
| ov CLI | CLI 命令 | ~40 命令组 | ✅ `ov find` | ✅ `ov find` | ✅ `ov find` | ✅ `ov add-memory` | ✅ `ov add-resource` | ✅ `ov add-skill` | `ov rm` 直接执行(TUI 删除有确认 + root/scope 禁删) |
-¹ MCP `write` 的可写域是 `viking://resources|user|agent`,暂不支持 MCP 新增 skill;新增 skill 的入口是 openclaw `add_skill`、`ov add-skill` 与 REST。
+¹ MCP `write` 拒绝写用户自己的 `skills/` 子树;写 `viking://agent/skills` 时会生成一个绕过 skill 安装流程的普通文件(没有 frontmatter abstract,也不做 privacy 抽取),所以共享 skill 同样要走 `add_skill`。skill 的新建、安装和替换走 MCP `add_skill` 工具(内联 SKILL.md 文本、Git URL,或本地目录/zip 的签名上传),它和 REST `POST /api/v1/skills` 共用同一套安装实现。
² MCP `forget` 不区分 memory/resource/skill 类型;存储层保留了命名空间根保护机制(裸 `viking://`、`viking://user`、`viking://agent` 根拒删),详见 [§3.5](#_3-5-写入与删除的类型边界)。
³ pi 的 `viking_forget`:其 `recursive` 参数固定为 false(不删除目录),按 query 删除要求匹配分 >0.8。
⁴ pi 工具注册前置:需未命中 `bypassSessionPatterns`、`client.health()` 通过、`ensureSession` 成功(`index.ts:66-108`);health 未通过时本轮不注册工具面。
⁵ openclaw 的 `add_resource` 需经过双重 opt-in 后方可开启。
-**skill 的增删边界**:新增入口包含 openclaw `add_skill`(默认开)、`ov add-skill` 与 REST;删除边界分四档,详见 [§3.5](#_3-5-写入与删除的类型边界)。
+**skill 的增删边界**:新增入口包含 MCP `add_skill`、openclaw `add_skill`(默认开)、`ov add-skill` 与 REST;删除边界分四档,详见 [§3.5](#_3-5-写入与删除的类型边界)。
## 1.2 自动 hook 面(通过 Harness 自动实现)
@@ -88,21 +88,22 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
| # | 工具名 | 功能 | 参数要点(定义行号) |
|---|---|---|---|
-| 1 | `find` | 不依赖会话上下文的快速语义检索 | `query, target_uri="", limit=10, min_score=0.35, level, context_type`(`:259`) |
-| 2 | `search` | 深检索,可带 `session_id` + 意图分析 | `session_id` 仅在服务端 `retrieval.enable_intent`(默认 true)开启时才会加载会话(`:285`,`:302-304`) |
-| 3 | `read` | 读取单个或多个 `viking://` 文件全文 | 并发信号量 10;单条失败返回 `(nothing found at <uri>)` 不抛错(`:389`) |
-| 4 | `list` | 列目录(函数名 `ls`,注册名显式改写为 `list`) | `recursive=False`(`:423`) |
-| 5 | `tree` | 递归目录树 | `level_limit=3, node_limit=1000, include_abstract=False`(`:449`) |
-| 6 | `remember` | 写长期记忆 | 内部建一次性会话 `mcp-store-<uuid12>` 并立即 `commit_async`(`:504-523`)——这是 MCP 面唯一的 commit 入口;MCP 没有显式 commit 工具 |
-| 7 | `write` | 写 `viking://` 文件 | `mode=replace\|append\|create`:replace 覆盖或在缺失时创建,append 追加或在缺失时创建,create 仅创建缺失文件且已存在时返回冲突;显式 create 的文件扩展名白名单为 `.md .txt .json .yaml .yml .toml .py .js .ts`;可写域 `resources/user/agent`;用户根下 `skills/ peers/ privacy/ sessions/` 只读;已存在的 `.abstract.md/.overview.md` sidecar 可改正文,但公共 API 不能创建(`:529`;`content_write.py:60-81`) |
-| 8 | `edit` | 精确字符串替换 | `old_string` 空/0 命中/多命中且非 replace_all 均报错,且文件内容不变(`:569`) |
-| 9 | `add_resource` | 资源摄取(远程 URL / 本地文件签名上传 / Connector) | `watch_interval` 单位为分钟(0=不 watch);本地路径分支返回签名上传 URL(TTL 默认 600s),上传后自动入库,无需二次调用(`:723-947`) |
-| 10 | `list_watches` | 列 watch 订阅,商业版尚未支持 | scheduler 未运行时返回错误串(`:958`) |
-| 11 | `cancel_watch` | 按 `to_uri` 取消,商业版尚未支持 | 刻意不暴露 pause/resume/trigger/update(`:990`) |
-| 12 | `grep` | 正则内容检索 | 多 pattern 并发(信号量 10),`node_limit=10`(`:1032`) |
-| 13 | `glob` | 文件名 glob | `node_limit=100`(`:1084`) |
-| 14 | `forget` | 删除 URI(不可恢复) | 默认 `recursive=False`;类型边界详见 [§3.5](#_3-5-写入与删除的类型边界)(`:1110-1117`) |
-| 15 | `health` | 健康检查 | 无参(`:1123`) |
+| 1 | `find` | 不依赖会话上下文的快速语义检索 | `query, target_uri="", limit=10, min_score=0.35, level, context_type, read_content`;只传 `context_type="skill"` 时改调 `SearchService.find_skills`(包级检索,`skill_package_retriever.py`):一个 skill 包一条命中,URI 改写为 `<包根>/SKILL.md`,摘要取包自身的 abstract,`read_content` 也读这个文件;不传 `target_uri` 时同时检索 `viking://~/skills` 与 `viking://agent/skills`。其它 `context_type` 组合,以及不带 query 只给 filter 的调用,仍走通用检索路径;渲染时的 URI 改写和「一个包一条」合并照常生效(`:262`) |
+| 2 | `search` | 深检索,可带 `session_id` + 意图分析 | `session_id` 仅在服务端 `retrieval.enable_intent`(默认 true)开启时才会加载会话(`:315`)。这里按条目检索 skill,只在渲染时合并,所以一个包在多个文件上命中会占掉多个 `limit` 名额,摘要也取自实际命中的文件 |
+| 3 | `read` | 读取单个或多个 `viking://` 文件全文 | 并发信号量 10;单条失败返回 `(nothing found at <uri>)` 不抛错(`:643`) |
+| 4 | `list` | 列目录(函数名 `ls`,注册名显式改写为 `list`) | `recursive=False`(`:784`) |
+| 5 | `tree` | 递归目录树 | `level_limit=3, node_limit=1000, include_abstract=False`;`include_abstract=true` 时打印每个目录的 abstract(最长 1024 字符),因此 `tree(uri="viking://~/skills", level_limit=1, include_abstract=true)` 能列出全部 skill 及其描述(`:862`) |
+| 6 | `remember` | 写长期记忆 | 内部建一次性会话 `mcp-store-<uuid12>` 并立即 `commit_async`(`:940`)——这是 MCP 面唯一的 commit 入口;MCP 没有显式 commit 工具 |
+| 7 | `write` | 写 `viking://` 文件 | `mode=replace\|append\|create`:replace 覆盖或在缺失时创建,append 追加或在缺失时创建,create 仅创建缺失文件且已存在时返回冲突;显式 create 的文件扩展名白名单为 `.md .txt .json .yaml .yml .toml .py .js .ts`;可写域 `resources/user/agent`;用户根下 `skills/ peers/ privacy/ sessions/` 只读;已存在的 `.abstract.md/.overview.md` sidecar 可改正文,但公共 API 不能创建;写 `viking://agent/skills` 不会被拒绝,但会绕过 skill 安装流程,skill 请改用 `add_skill`,详见 [§3.5](#_3-5-写入与删除的类型边界)(`:965`;`content_write.py:60-81`) |
+| 8 | `edit` | 精确字符串替换 | `old_string` 空/0 命中/多命中且非 replace_all 均报错,且文件内容不变;编辑 skill 包内的文件不会重新触发 skill 安装流程,详见 [§3.5](#_3-5-写入与删除的类型边界)(`:1005`) |
+| 9 | `add_resource` | 资源摄取(远程 URL / 本地文件签名上传 / Connector) | `watch_interval` 单位为分钟(0=不 watch);本地路径分支返回签名上传 URL(TTL 默认 600s),上传后自动入库,无需二次调用(`:1161`) |
+| 10 | `add_skill` | 新建、安装或替换 skill | `data`(完整 SKILL.md 文本)或 `path`(Git URL / GitHub tree URL,或本地 SKILL.md、目录、zip——本地分支和 `add_resource` 一样返回签名上传 URL);`skills=[...]` 从多 skill 源里挑选,`list_only=true` 只预览;`target_uri="viking://agent/skills"` 表示账户共享。与 REST `POST /api/v1/skills` 共用安装代码。工具描述里写明它是新建和更新 skill 的唯一入口,删除请走 `ov skills remove` 或 Studio(`:1452`) |
+| 11 | `list_watches` | 列 watch 订阅,商业版尚未支持 | scheduler 未运行时返回错误串(`:1621`) |
+| 12 | `cancel_watch` | 按 `to_uri` 取消,商业版尚未支持 | 刻意不暴露 pause/resume/trigger/update(`:1653`) |
+| 13 | `grep` | 正则内容检索 | 多 pattern 并发(信号量 10),`node_limit=10`(`:1696`) |
+| 14 | `glob` | 文件名 glob | `node_limit=100`(`:1765`) |
+| 15 | `forget` | 删除 URI(不可恢复) | 默认 `recursive=False`;类型边界详见 [§3.5](#_3-5-写入与删除的类型边界)(`:1791`) |
+| 16 | `health` | 健康检查 | 无参(`:1808`) |
配套机制:
@@ -453,7 +454,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
**第四档:默认不提供删除(LangChain / Open WebUI)**。LangChain `viking_forget` 需配置 `profile="admin"` 或 `allow_forget=True` 才加入工具面;Open WebUI 则完全不提供删除工具。
-**skill 的增删边界**:新增入口是 openclaw `add_skill`(默认开)、`ov add-skill` 与 REST。对 skill 完全只读(不增不删)的删除面是 openclaw `memory_forget` 与 hermes `viking_forget`;相对地,MCP 面、dsh、pi、`ov rm` 加不了 skill 但删得掉——加不了是写路径 `_USER_MANAGED_SUBTREES` 的保护,删得掉是删除路径不检查该集合。
+**skill 的增删边界**:新增入口是 MCP `add_skill`、openclaw `add_skill`(默认开)、`ov add-skill` 与 REST;`add_resource` 拒绝 skill URI,MCP `write` 拒绝用户自己的 `skills/` 子树(`_USER_MANAGED_SUBTREES`);`viking://agent/skills` 下的 `write` 目前没有拦截,但会绕过 skill 安装流程。对 skill 完全只读(不增不删)的删除面是 openclaw `memory_forget` 与 hermes `viking_forget`。MCP `forget`、dsh、pi、`ov rm` 能删掉 skill 目录,因为删除路径不检查该集合,但只有 `ov skills remove` 和 REST `DELETE /api/v1/skills/{name}` 会同时清理该 skill 的 privacy 配置。
## 3.6 降级与容错
@@ -500,7 +501,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
## claude-code
- **集成文档**:[Claude Code 记忆插件](./02-claude-code.md)
-- **形态**:CC 插件(marketplace),采用四合一架构:9 hook + MCP 代理(15 工具透传)+ slash command + statusline + 1 experience skill。版本 0.5.1。
+- **形态**:CC 插件(marketplace),采用四合一架构:9 hook + MCP 代理(16 工具透传)+ slash command + statusline + 1 experience skill。版本 0.5.1。
- **能力亮点**:hook 覆盖最全的 harness——SessionStart(120s) / UserPromptSubmit(60s) / PostToolUse:Read(5s,默认关的 skill-experience) / PreToolUse:Read\|Glob\|Grep\|Edit\|Write\|Bash(5s,uri-guard:文件工具的路径是 `viking://` URI 时拒绝,Bash 命令带 `viking://` URI 时附加提示) / Stop(45s) / PreCompact(30s) / SessionEnd(30s) / SubagentStart(10s) / SubagentStop(45s);默认启用召回再摘要(本地 `claude -p`,本地不可用时自动回落服务端 rewrite,[§3.2.5](#_3-2-5-召回再摘要));支持 SubagentStart/Stop 的完整子会话隔离([§3.3.5](#_3-3-5-subagent-会话对照));statusline + slash + uri-guard;关闭链路除 kill -9 外全部 commit([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。
- **行为要点**:session id 为 `cc-<CC session_id 原文>`,subagent 为 `…__subagent-<agent_id>`;Stop 阈值 commit 20000/keep 10,PreCompact 同步 commit;自动召回排除 resources([§3.2.1](#_3-2-1-机制底座-一条共享管线-两条服务端路径));增量游标存于 `/tmp`(被系统清理后,同一会话会整段重推)。
- **配置**:env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code`([§3.1.4](#_3-1-4-配置体系分层)),约 70 个旋钮;压缩器命令与模型固定为 `claude`/`sonnet`/`low`/30s。
@@ -653,13 +654,13 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
| 路径 | 投入 | agent 主动工具面 | 自动召回/捕获 hook | 会话/commit | 压缩接管 |
|---|---|---|---|---|---|
-| ① [通用 MCP 直连](./06-mcp-clients.md) | 分钟级(填写一段 config 即可) | ✅ 15 工具全量 | ❌ 由模型主动调用 | 仅 `remember` 建临时会话 | ❌ |
+| ① [通用 MCP 直连](./06-mcp-clients.md) | 分钟级(填写一段 config 即可) | ✅ 16 工具全量 | ❌ 由模型主动调用 | 仅 `remember` 建临时会话 | ❌ |
| ② HTTP API / SDK / [LangChain](./07-langchain-langgraph.md) | 小时级(需写代码) | 自选(按需调 REST) | 自己实现 | 自己实现(或用 LangChain middleware) | ❌ |
-| ③ 复用 shared-core / [Agent Plugins 便携包](./15-agent-plugins.md) | 天级(需写 hook 适配) | ✅ 15 工具(经 MCP 代理) | ✅ 召回/捕获/commit/pending 全套 | ✅ | 视接入哪些事件而定 |
+| ③ 复用 shared-core / [Agent Plugins 便携包](./15-agent-plugins.md) | 天级(需写 hook 适配) | ✅ 16 工具(经 MCP 代理) | ✅ 召回/捕获/commit/pending 全套 | ✅ | 视接入哪些事件而定 |
## 6.2 路径①:通用 MCP 直连(推荐起步)
-任何支持 MCP 的 agent,只需在其 `mcpServers` 配置里指向服务端 `/mcp`(各客户端的具体配置位置见 [MCP 客户端](./06-mcp-clients.md)),即可立刻获得全部 15 个工具([§2.1](#_2-1-服务端-mcp-工具面))。最小配置如下:
+任何支持 MCP 的 agent,只需在其 `mcpServers` 配置里指向服务端 `/mcp`(各客户端的具体配置位置见 [MCP 客户端](./06-mcp-clients.md)),即可立刻获得全部 16 个工具([§2.1](#_2-1-服务端-mcp-工具面))。最小配置如下:
```json
{
@@ -701,8 +702,8 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
|---|---|---|---|---|---|
| **A. [Open WebUI](./08-community-plugins.md)** | 独立的 FastAPI OpenAPI 工具服务器 | 7 个本地 OpenAPI 路由(`ov_search`/`ov_recall_memories`/`ov_add_memory`/`ov_list_memories`/`ov_read_resource`/`ov_add_resource`/`ov_session_status`),无删除工具 | 无会话概念 | 最薄:裸 httpx,无 retry/负缓存;`/health` 仅回显配置,不探测 OV | 进程不启动即不存在 |
| **B. [LangChain/LangGraph](./07-langchain-langgraph.md)** | Python SDK 适配层(retriever/tools/store/middleware/recorder) | `create_openviking_tools()` 提供 12 个 StructuredTool(`viking_forget` 默认不在 agent profile 中) | `thread_id`/`session_id` 由调用方给;`CommitPolicy` 默认 `never` | 本组最稳:只读方法自动重试 1 次、写方法不重试(防重复)、部分成功抛结构化异常可切片重试 | 需全部显式构造才生效 |
-| **C. [Agent Plugins 1.0](./15-agent-plugins.md)** | 便携包 `plugin.json` + `skills/` + `mcp.json`(stdio→HTTP 代理) | MCP 透传 15 工具;刻意无 hooks(召回靠 skill 教模型) | 仅 `remember` 建临时会话 | MCP 代理层重试(401/403 换凭据、400/404 重初始化各 1 次) | 客户端加载后工具即用 |
-| **D. [通用 MCP 直连](./06-mcp-clients.md)** | 零本地组件,直连 `/mcp` | 同 C(15 工具) | 同 C | 由客户端自定 | `/mcp` 常驻 |
+| **C. [Agent Plugins 1.0](./15-agent-plugins.md)** | 便携包 `plugin.json` + `skills/` + `mcp.json`(stdio→HTTP 代理) | MCP 透传 16 工具;刻意无 hooks(召回靠 skill 教模型) | 仅 `remember` 建临时会话 | MCP 代理层重试(401/403 换凭据、400/404 重初始化各 1 次) | 客户端加载后工具即用 |
+| **D. [通用 MCP 直连](./06-mcp-clients.md)** | 零本地组件,直连 `/mcp` | 同 C(16 工具) | 同 C | 由客户端自定 | `/mcp` 常驻 |
| **E. [log ingestion](./09-log-ingestion.md)** | `openviking-server ingest` CLI(跑在日志所在机器,反向导入) | 无(只写不召回) | 会话 id `{prefix}__{harness}__{sanitized native id}`;commit token 6000/idle 5s/keep 0 | 唯一有崩溃恢复:SQLite 游标库 + 单实例锁 + reconcile 判定批次落地 | 双重默认关(`ingest.enabled` + 每 harness `enabled` 都 false);支持 claude_code/codex/hermes/opencode/openclaw/cursor 适配器 |
| **F. [OpenViking Helper](./14-openviking-helper.md)** | 闭源桌面 App | — | — | — | 不在本文代码基线内 |
diff --git a/docs/zh/api/04-skills.md b/docs/zh/api/04-skills.md
index 65166a6f3..1f9fc6283 100644
--- a/docs/zh/api/04-skills.md
+++ b/docs/zh/api/04-skills.md
@@ -174,6 +174,8 @@ This tool wraps the MCP tool `search-web`. Call this when the user needs functio
- `sdk/python/openviking_sdk/client.py:AsyncHTTPClient.add_skill` - Python SDK 入口
- `openviking_cli/client/http.py` - 兼容导入入口,转发到 Python SDK
- `openviking/server/routers/resources.py:add_skill` - HTTP 路由
+- `openviking/server/mcp_endpoint.py:add_skill` - MCP 工具
+- `openviking/server/skill_ingest.py:install_skills` - HTTP 路由、MCP 工具与 skill 签名上传共用的安装实现
- `openviking/service/resource_service.py:ResourceService.add_skill` - 核心服务实现
- `openviking/server/routers/skills.py` - 列表、检索、读取、校验、更新和删除
- `crates/ov_cli/src/commands/skills.rs` - CLI Skill 命令处理
@@ -207,6 +209,7 @@ This tool wraps the MCP tool `search-web`. Call this when the user needs functio
4. 先调用 `POST /api/v1/resources/temp_upload` 上传本地 `SKILL.md` 或目录 ZIP,再调用 `POST /api/v1/skills` 并传入 `temp_file_id`
- `temp_upload` 默认使用本地临时存储;只有在明确需要分布式共享临时上传时,才传 `upload_mode=shared`。Python HTTP client 可以在 `ovcli.conf` 中设置 `upload.mode = "shared"`;Rust `ov` CLI 则使用 `OPENVIKING_UPLOAD_MODE=shared`。
- `POST /api/v1/skills` 不接受在 `data` 中直接传宿主机本地路径。
+ - MCP 客户端使用 `add_skill` 工具:`data` 传 SKILL.md 文本,`path` 传 Git URL 或本地路径。传本地路径时工具返回一次性的签名 `temp_upload` URL;客户端把 SKILL.md 或 ZIP POST 上去后,服务端按 token 绑定的 `target_uri`、`skills`、`list_only` 完成安装,上传响应里就是安装结果。
- **目标规则**:
- 新增使用 `target_uri` 指定 skills 根,不接受 `to`、`parent` 或 `root_uri` 作为 HTTP 请求字段。CLI 的 `-p/--parent-auto-create` 映射到 `target_uri`。
@@ -605,7 +608,7 @@ HTTP 对应查询为 `GET /api/v1/skills/search-web?include_content=true&include
清单包含 `SKILL.md`、摘要和辅助文件/目录,不包含 `.source.json`。完整性 API 上限为 **512 个条目(包含目录)、单文件 16 MiB、总文件字节数 64 MiB**,读取并发为 8;超限返回 `RESOURCE_EXHAUSTED`。正文、清单和 revision 在同一次树锁保护的读取中取得,但后续下载仍可能遇到更新,消费方应校验文件哈希并复查 revision。
-检索与 `get_skill` 只返回内容和清单,不会执行脚本或把文件安装到 Agent 沙箱。Harness 可按需远程读文本,在工具需要本地路径时下载资源。VikingBot 的完整流程见 [Skills](../../../bot/docs/zh/concepts/06-skills.md)。
+检索与 `get_skill` 只返回内容和清单,不会执行脚本或把文件安装到 Agent 沙箱。Harness 可按需远程读文本,在工具需要本地路径时下载资源。VikingBot 的完整流程见 [Skills](../../../bot/docs/zh/concepts/06-skills.md)。MCP 客户端通过 `find` 工具传 `context_type="skill"` 得到同样的包级行为,见 [MCP 集成](../guides/06-mcp-integration.md)。
### 搜索技能
@@ -622,7 +625,7 @@ HTTP 对应查询为 `GET /api/v1/skills/search-web?include_content=true&include
包内命中按完整 Skill 根 URI 合并,使用最高最终得分排序,再截取 `limit` 个 Skill。不同空间的同名 Skill 分别保留。`total` 是本次返回数组长度,不是所有匹配项的总数。
-每个 Skill 返回包内最终得分最高的一条命中。`uri`、`level`、`score`、`abstract` 直接使用该命中的原有字段,不增加额外返回字段。按 Skill 合并和补页仅用于专用 `skills/find`;通用 `find/search` 保持按命中内容返回。
+每个 Skill 返回包内最终得分最高的一条命中。`uri`、`level`、`score`、`abstract` 直接使用该命中的原有字段,不增加额外返回字段。按 Skill 合并和补页用于专用 `skills/find`,以及只传 `context_type="skill"` 的 MCP `find` 工具;REST `find` / `search` 仍按命中内容返回。MCP `search` 同样按命中内容检索,只在渲染答案时把同一个包合成一条。
| 返回字段 | 含义 |
| --- | --- |
@@ -632,11 +635,11 @@ HTTP 对应查询为 `GET /api/v1/skills/search-web?include_content=true&include
| `name` / `description` / `tags` / `allowed_tools` | 专用 `skills/find` 从 Skill 主目录单独读取的元数据 |
| `root_uri` / `skill_md_uri` | 专用 `skills/find` 返回的 Skill 根目录和主 `SKILL.md` 地址 |
-专用 `skills/find` 的 `uri` 从原先的包根地址调整为实际命中地址,列表和按名称读取接口保持原样。`level=[2]` 只让文件参与匹配,返回的 `level` 为 `2`、`uri` 指向包内得分最高的文件。
+专用 `skills/find` 的 `uri` 从原先的包根地址调整为实际命中地址;MCP `find` 工具的行为不同,它把每条 Skill 命中改写成 `<包根>/SKILL.md`。列表和按名称读取接口保持原样。`level=[2]` 只让文件参与匹配,返回的 `level` 为 `2`、`uri` 指向包内得分最高的文件。
-通用检索中 `read_content=true` 继续读取实际返回的 `uri`。专用 `skills/find` 不支持该参数。
+通用检索中 `read_content=true` 继续读取实际返回的 `uri`——对只传 `context_type="skill"` 的 MCP `find` 来说,这个 URI 是包的 `SKILL.md`,不是实际命中的文件。专用 `skills/find` 不支持该参数。
-上表的 URI 规则适用于语义检索。通用 `find` 仅按 `filter` 筛选时,仍保留索引记录的 URI、返回 `score=0`,不为 L0、L1 补摘要文件后缀。
+上表的 URI 规则适用于语义检索。通用 `find` 仅按 `filter` 筛选时,仍保留索引记录的 URI、返回 `score=0`,不为 L0、L1 补摘要文件后缀;MCP `find` 遇到这种调用也留在通用路径上,因为包级检索必须带检索文本,但仍会把每条 skill 命中改写成它的 `SKILL.md`。
搜索范围、层级和权限限制先作用于包内命中,再合并 Skill;根目录也必须可访问。
diff --git a/docs/zh/concepts/07-retrieval.md b/docs/zh/concepts/07-retrieval.md
index 5acbf594b..0d38d48b2 100644
--- a/docs/zh/concepts/07-retrieval.md
+++ b/docs/zh/concepts/07-retrieval.md
@@ -95,7 +95,7 @@ Step 5: 转换为 MatchedContext
|--------------|--------|
| MEMORY | `viking://~/memories` |
| RESOURCE | `viking://resources` |
-| SKILL | `viking://~/skills` |
+| SKILL | `viking://~/skills` 与 `viking://agent/skills` |
### 递归搜索算法
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index 8ae3f227b..a59888154 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -1743,8 +1743,8 @@ ov add-resource ./docs --exclude "*.tmp"
| `root_api_key` | str | `api_key` 模式必填的 Root API Key;`trusted` 模式仅在 localhost 可省略,非 localhost 部署必填,不负责解析普通用户身份 | `null` |
| `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?token=...`。 | `600`(10 分钟) |
+| `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 分钟) |
| `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.md
index 03c9eb2ed..c15ec3dec 100644
--- a/docs/zh/guides/06-mcp-integration.md
+++ b/docs/zh/guides/06-mcp-integration.md
@@ -121,24 +121,25 @@ claude mcp add --transport http openviking \
## 可用的 MCP 工具
-连接后,OpenViking MCP 端点暴露 15 个工具:
+连接后,OpenViking MCP 端点暴露 16 个工具:
| 工具 | 说明 | 主要参数 |
|------|------|----------|
-| `find` | 无 session 上下文的快速语义检索 | `query`, `target_uri`(可选), `limit`, `min_score`, `level`(可选), `context_type`(可选) |
-| `search` | 深度语义检索;`mode="context"` 组装可直接注入的上下文,并替代原 `recall` 工具 | `query`, `mode`(`list` 或 `context`), `target_uri`(仅 list 模式), `session_id`(可选), `limit`, `min_score`, `level`(list 模式), `context_type`(可选),以及 context 模式的 `quotas`, `purpose`, `max_tokens`, `detail` 或 `detail_by_category`, `dedup_turns`, `exclude_uris`, `peer_scope`, 标量 `other_peer_penalty` 或按类别设置的 `other_peer_penalties`, `rewrite`(`off` 或 `auto`) |
+| `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`(可选——直接内联每条命中的内容) |
+| `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`(可选),以及 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`(单个字符串或数组) |
| `list` | 列出 `viking://` 目录下的条目 | `uri`, `recursive`(可选) |
-| `tree` | 以缩进形式展示 `viking://` URI 下的递归目录树——当需要全面了解文件树结构时使用(单层列表用 `list`,按文件名查找用 `glob`) | `uri`(可选), `level_limit`(默认 3), `node_limit`(默认 1000), `include_abstract`(可选——同时展示每个文件的摘要) |
+| `tree` | 以缩进形式展示 `viking://` URI 下的递归目录树——当需要全面了解文件树结构时使用(单层列表用 `list`,按文件名查找用 `glob`) | `uri`(可选), `level_limit`(默认 3), `node_limit`(默认 1000), `include_abstract`(可选——同时展示每个目录的摘要;skill 目录的摘要就是它的名字和描述) |
| `remember` | 存储消息到长期记忆(触发记忆提取) | `messages`(`{role, content}` 列表) |
-| `write` | 向 `viking://` 文件写入文本(创建/覆盖/追加)。自动创建缺失的父目录;覆盖前请先用 `read` 查看当前内容;只改文件局部时优先用 `edit` | `uri`, `content`, `mode`(可选:默认 `replace` — 覆盖或在缺失时创建,`append` — 追加或在缺失时创建,`create` — 已存在则失败), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选) |
-| `edit` | 在已有 `viking://` 文件中把精确字符串替换为新文本——用于局部修改,避免整文件重写。若 `old_string` 找不到、或匹配多处且 `replace_all` 为 false,则编辑失败且文件保持不变 | `uri`, `old_string`, `new_string`, `replace_all`(可选), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选) |
+| `write` | 向 `viking://` 文件写入文本(创建/覆盖/追加)。自动创建缺失的父目录;覆盖前请先用 `read` 查看当前内容;只改文件局部时优先用 `edit`。skill 包不要用它维护:调用方自己的 `skills/` 子树会被拒绝,写 `viking://agent/skills` 则生成绕过安装流程的普通文件,请改用 `add_skill` | `uri`, `content`, `mode`(可选:默认 `replace` — 覆盖或在缺失时创建,`append` — 追加或在缺失时创建,`create` — 已存在则失败), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选) |
+| `edit` | 在已有 `viking://` 文件中把精确字符串替换为新文本——用于局部修改,避免整文件重写。若 `old_string` 找不到、或匹配多处且 `replace_all` 为 false,则编辑失败且文件保持不变。编辑 skill 包内的文件不会重新触发 skill 安装流程,请改用 `add_skill` | `uri`, `old_string`, `new_string`, `replace_all`(可选), `wait`(可选,阻塞直到重建索引完成), `timeout`(可选) |
| `add_resource` | 添加本地文件或 URL 作为资源(本地文件触发渐进式上传流) | `path`, `temp_file_id`(可选), `description`(可选), `watch_interval`(可选,分钟数 — 远程 URL 的自动刷新周期), `processing_mode`(可选:默认 `semantic_and_vectors`;传 `vectors_only` 时跳过 VLM 语义理解,只向量化当前文件), `to`(可选,目标 `viking://resources/...` URI;`watch_interval > 0` 时若省略 `to`,watch 将自动绑定到本次 add 创建的资源 URI), `args`(可选,特定 parser 参数,包括 `{"parse_mode":"no_split"}` 用于正常解析但每个源文档只生成一个 Markdown 正文、飞书一次性用户 token 导入使用 `{"feishu_access_token":"u-..."}`,或飞书用户 token watch 使用 access/refresh token,并可选传入 `feishu_app_id` / `feishu_app_secret`) |
+| `add_skill` | 新建、安装或替换 agent skill。新 skill 直接传完整 SKILL.md 文本;Git 与 GitHub tree URL 默认安装源里的全部 skill,可用 `skills` 挑选;本地 SKILL.md、目录或 zip 会和 `add_resource` 一样返回签名上传 URL | `data`(SKILL.md 文本)或 `path`(Git URL 或本地路径), `skills`(可选), `target_uri`(可选;`viking://agent/skills` 表示账户共享), `list_only`(可选) |
| `list_watches` | 列出当前 Agent 可见的 watch 任务(自动刷新订阅),每行显示目标 URI、刷新间隔(分钟)、active/paused 状态以及下一次调度时间 | 无 |
| `cancel_watch` | 按目标 URI 取消(删除)watch 任务。若需调整刷新周期或临时暂停,请取消后使用新的 `watch_interval` 重新添加 | `to_uri`(必须匹配 watch 任务的 `to` 值,例如 `viking://resources/...`) |
| `grep` | 在 `viking://` 文件中进行正则内容搜索 | `uri`, `pattern`(字符串或数组), `case_insensitive`, `node_limit` |
| `glob` | 按 glob 模式匹配文件 | `pattern`, `uri`(可选范围), `node_limit` |
-| `forget` | 删除任意 `viking://` URI(先用 `search` 查找;删除目录需 `recursive=true`) | `uri`, `recursive`(可选) |
+| `forget` | 删除任意 `viking://` URI(先用 `search` 查找;删除目录需 `recursive=true`)。用它删 skill 目录会残留该 skill 的 privacy 配置,请改用 `ov skills remove` 或 `DELETE /api/v1/skills/{name}` | `uri`, `recursive`(可选) |
| `health` | 检查 OpenViking 服务健康状态 | 无 |
在 MCP 工具中访问自己的工作区,请使用家目录别名 `viking://~`。它在所有控制面
diff --git a/examples/codex-memory-plugin/scripts/marketplace.test.mjs b/examples/codex-memory-plugin/scripts/marketplace.test.mjs
index 4e296c233..d1bc2b5c3 100644
--- a/examples/codex-memory-plugin/scripts/marketplace.test.mjs
+++ b/examples/codex-memory-plugin/scripts/marketplace.test.mjs
@@ -30,7 +30,7 @@ const packagedExperienceSkillPath = join(pluginDir, "skills", "ov-experience-mem
const PLUGIN_NAME = "openviking-memory";
const REAL_MCP_TOOLS = [
"find", "search", "read", "list", "tree", "remember", "write", "edit",
- "add_resource", "list_watches", "cancel_watch", "grep", "glob", "forget", "health",
+ "add_resource", "add_skill", "list_watches", "cancel_watch", "grep", "glob", "forget", "health",
];
const LEGACY_TOOL_NAMES = ["openviking_recall", "openviking_store", "openviking_forget", "openviking_health"];
diff --git a/examples/opencode-plugin/INSTALL-ZH.md b/examples/opencode-plugin/INSTALL-ZH.md
index 475b36eb4..18e47fea4 100644
--- a/examples/opencode-plugin/INSTALL-ZH.md
+++ b/examples/opencode-plugin/INSTALL-ZH.md
@@ -164,7 +164,7 @@ OpenCode 的 `mcp.openviking` 配置。
- `openviking_search`、`openviking_find`
- `openviking_read`、`openviking_list`、`openviking_tree`、`openviking_grep`、`openviking_glob`
-- `openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`
+- `openviking_remember`、`openviking_write`、`openviking_edit`、`openviking_add_resource`、`openviking_add_skill`
- `openviking_list_watches`、`openviking_cancel_watch`、`openviking_forget`、`openviking_health`
- `openviking_list_watches`、`openviking_cancel_watch`
diff --git a/examples/opencode-plugin/INSTALL.md b/examples/opencode-plugin/INSTALL.md
index b9c2a8680..0d8541f76 100644
--- a/examples/opencode-plugin/INSTALL.md
+++ b/examples/opencode-plugin/INSTALL.md
@@ -161,7 +161,7 @@ In a new OpenCode session, ask the agent to browse OpenViking memory or search f
- `openviking_search`, `openviking_find`
- `openviking_read`, `openviking_list`, `openviking_tree`, `openviking_grep`, `openviking_glob`
-- `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`
+- `openviking_remember`, `openviking_write`, `openviking_edit`, `openviking_add_resource`, `openviking_add_skill`
- `openviking_list_watches`, `openviking_cancel_watch`, `openviking_forget`, `openviking_health`
- `openviking_list_watches`, `openviking_cancel_watch`
@@ -193,6 +193,7 @@ The plugin registers OpenViking's stdio MCP proxy through OpenCode config. The s
- `openviking_write`: create, overwrite, or append to a `viking://` file.
- `openviking_edit`: exact string replacement in a `viking://` file.
- `openviking_add_resource`: add a URL, local file, sitemap, or feed.
+- `openviking_add_skill`: create, install, or replace an agent skill.
- `openviking_forget`: delete a `viking://` URI after explicit user confirmation.
- `openviking_list_watches` / `openviking_cancel_watch`: inspect or cancel resource watches.
- `openviking_health`: check OpenViking server health.
diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.md
index d096836de..608a140c1 100644
--- a/examples/opencode-plugin/README.md
+++ b/examples/opencode-plugin/README.md
@@ -212,6 +212,7 @@ OpenCode sees the OpenViking MCP server as `openviking`, so tool names are names
- `openviking_write`: create, overwrite, or append to a `viking://` file.
- `openviking_edit`: exact string replacement in a `viking://` file.
- `openviking_add_resource`: add a URL, local file, sitemap, or feed.
+- `openviking_add_skill`: create, install, or replace an agent skill.
- `openviking_forget`: delete a `viking://` URI after explicit user confirmation.
- `openviking_list_watches` / `openviking_cancel_watch`: inspect or cancel resource watches.
- `openviking_health`: check OpenViking server health.
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 671235bdc..b58258361 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -785,9 +785,9 @@ def create_app(
else:
logger.info("Web Studio bundle not found at %s; skipping /studio mount", _studio_dir)
- # MCP endpoint — serves 15 tools (find, search, read, write, edit,
- # list, tree, remember, add_resource, list_watches, cancel_watch, grep,
- # glob, forget, health) via streamable HTTP for MCP clients.
+ # MCP endpoint — serves 16 tools (find, search, read, write, edit,
+ # list, tree, remember, add_resource, add_skill, list_watches, cancel_watch,
+ # grep, glob, forget, health) via streamable HTTP for MCP clients.
from starlette.routing import Match, Route
from openviking.server.mcp_endpoint import create_mcp_app
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index 535c04cf6..d3b6bc5cb 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -39,6 +39,7 @@ from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send
from openviking.core.path_variables import resolve_path_variables
+from openviking.core.retrieval_targets import default_target_directories
from openviking.core.uri_validation import (
validate_content_target_uri,
validate_request_viking_uri,
@@ -51,6 +52,7 @@ from openviking.retrieve.context_assembler import (
AssembleParams,
assemble_context,
)
+from openviking.retrieve.skill_results import skill_root_uri
from openviking.server.auth import (
_build_request_context,
_extract_api_key,
@@ -62,12 +64,21 @@ from openviking.server.identity import RequestContext
from openviking.server.local_input_guard import (
TEMP_FILE_ID_RE,
is_remote_resource_source,
+ looks_like_local_path,
)
from openviking.server.resource_ingest import ingest_temp_upload
+from openviking.server.routers.search import context_only_fields_error
+from openviking.server.skill_ingest import install_skills
from openviking.server.temp_upload_store import TempUploadStore
from openviking.server.upload_token_store import upload_token_store
+from openviking.service.skill_sources import GIT_SKILL_SOURCE_PREFIXES
from openviking.utils.media_limits import MAX_INLINE_TOOL_RESULT_MEDIA_BYTES
-from openviking.utils.search_filters import SearchContextTypeInput, merge_search_filter
+from openviking.utils.search_filters import (
+ SearchContextTypeInput,
+ merge_search_filter,
+ resolve_context_types,
+)
+from openviking.utils.skill_processor import SkillProcessor
from openviking_cli.exceptions import (
InvalidArgumentError,
NotFoundError,
@@ -75,8 +86,8 @@ from openviking_cli.exceptions import (
PermissionDeniedError,
UnauthenticatedError,
)
+from openviking_cli.retrieve import ContextType
from openviking_cli.utils import get_logger
-from openviking.server.routers.search import context_only_fields_error
logger = get_logger(__name__)
@@ -257,20 +268,38 @@ async def find(
context_type: Optional[Union[str, List[str]]] = None,
read_content: bool = False,
) -> str:
- """Fast semantic retrieval without session context. Returns ranked memories, resources, and skills with URI, abstract, and score."""
+ """Fast semantic retrieval without session context. Returns ranked memories, resources, and skills with URI, abstract, and score. context_type="skill" returns one hit per skill package, pointing at its SKILL.md, and without target_uri searches both the user's own and the account-shared skills."""
service = get_service()
ctx = _get_ctx()
+ context_filter = _resolve_context_type_filter(context_type)
+ skill_only = resolve_context_types(context_type) == [ContextType.SKILL.value]
if target_uri:
target_uri = _resolve_mcp_workspace_uri(target_uri, ctx)
- result = await service.search.find(
- query=query,
- ctx=ctx,
- target_uri=target_uri,
- limit=limit,
- score_threshold=min_score,
- filter=_resolve_context_type_filter(context_type),
- level=level,
- )
+ elif skill_only:
+ # The generic default targets stop at the user root and miss viking://agent/skills.
+ target_uri = default_target_directories(ctx, context_type=ContextType.SKILL)
+ # A query-less call is a filter-only listing, which package retrieval does not serve.
+ if skill_only and query.strip():
+ # A skill is indexed as a whole package, so an item-level find returns one hit per
+ # file. find_skills collapses those to the best hit per package.
+ result = await service.search.find_skills(
+ query=query,
+ ctx=ctx,
+ target_uri=target_uri,
+ limit=limit,
+ score_threshold=min_score,
+ level=level,
+ )
+ else:
+ result = await service.search.find(
+ query=query,
+ ctx=ctx,
+ target_uri=target_uri,
+ limit=limit,
+ score_threshold=min_score,
+ filter=context_filter,
+ level=level,
+ )
return await _format_search_result(result, service=service, ctx=ctx, read_content=read_content)
@@ -389,7 +418,8 @@ async def search(
"other_peer_penalties": (other_peer_penalties, None),
"rewrite": (rewrite, "off"),
"rewrite_max_bullets": (rewrite_max_bullets, 6),
- }.items() if value != default
+ }.items()
+ if value != default
}
as_named_by_caller: Dict[str, set] = {}
for name in supplied_by_caller:
@@ -418,19 +448,84 @@ async def search(
return await _format_search_result(result, service=service, ctx=ctx, read_content=read_content)
+def _hit_uri(ctx_type: str, uri: str) -> str:
+ """The URI an agent should read for a hit.
+
+ A skill is indexed as a whole package: the hit may be its .abstract.md, its
+ .overview.md, or any file inside the directory. The skill itself is the
+ package's SKILL.md.
+ """
+ if ctx_type == "skill":
+ root = skill_root_uri(uri)
+ if root:
+ return f"{root}/SKILL.md"
+ return uri
+
+
+def _package_abstract(uri: str, abstract: str) -> str:
+ """The skill's own frontmatter, or "" when the package has no usable abstract."""
+ text = (abstract or "").strip()
+ return "" if text == f"# {uri} [Directory abstract is not ready]" else text
+
+
+async def _describe_skills_by_package(items: List[Dict[str, Any]], *, service, ctx) -> None:
+ """Describe a skill by its own abstract, not by whichever file inside it matched."""
+ import asyncio
+
+ pending = {}
+ for item in items:
+ if item["type"] != "skill" or not item["uri"].endswith("/SKILL.md"):
+ continue
+ root = item["uri"][: -len("/SKILL.md")]
+ if item["hit_uri"] in (f"{root}/.abstract.md", f"{root}/.overview.md", item["uri"]):
+ continue
+ pending[root] = item
+
+ semaphore = asyncio.Semaphore(10)
+
+ async def _describe(root: str) -> None:
+ async with semaphore:
+ try:
+ abstract = _package_abstract(root, await service.fs.abstract(root, ctx=ctx))
+ except Exception:
+ return
+ if abstract:
+ pending[root]["abstract"] = abstract
+
+ await asyncio.gather(*(_describe(root) for root in pending))
+
+
async def _format_search_result(result, *, service, ctx, read_content: bool = False) -> str:
- items = []
+ items: List[Dict[str, Any]] = []
+ seen: dict[str, int] = {}
for ctx_type, contexts in [
("memory", result.memories),
("resource", result.resources),
("skill", result.skills),
]:
for m in contexts:
- items.append((ctx_type, m))
+ uri = _hit_uri(ctx_type, m.uri)
+ item = {
+ "type": ctx_type,
+ "uri": uri,
+ "hit_uri": m.uri,
+ "score": getattr(m, "score", 0.0),
+ "abstract": getattr(m, "abstract", "") or getattr(m, "overview", ""),
+ }
+ # Several files of one skill package can match; keep the best-scored hit.
+ previous = seen.get(uri)
+ if previous is not None:
+ if item["score"] > items[previous]["score"]:
+ items[previous] = item
+ continue
+ seen[uri] = len(items)
+ items.append(item)
if not items:
return "No matching context found."
+ await _describe_skills_by_package(items, service=service, ctx=ctx)
+
contents: dict[str, str] = {}
if read_content:
import asyncio
@@ -444,17 +539,15 @@ async def _format_search_result(result, *, service, ctx, read_content: bool = Fa
except Exception:
pass
- await asyncio.gather(*(_read(m.uri) for _, m in items))
+ await asyncio.gather(*(_read(item["uri"]) for item in items))
lines = []
- for ctx_type, m in items:
- abstract = (
- getattr(m, "abstract", "") or getattr(m, "overview", "") or "(no abstract)"
- ).strip()
- score = getattr(m, "score", 0.0)
- line = f"- [{ctx_type} {score * 100:.0f}%] {m.uri}\n {abstract}"
- if m.uri in contents:
- line += f"\n\n {contents[m.uri]}"
+ for item in items:
+ abstract = (item["abstract"] or "(no abstract)").strip()
+ uri = item["uri"]
+ line = f"- [{item['type']} {item['score'] * 100:.0f}%] {uri}\n {abstract}"
+ if uri in contents:
+ line += f"\n\n {contents[uri]}"
lines.append(line)
return (
@@ -743,6 +836,22 @@ async def ls(
# -- tree ------------------------------------------------------------------
+# Long enough to keep a full skill description (the Agent Skills limit is 1024 chars).
+_TREE_ABSTRACT_LIMIT = 1024
+
+
+def _tree_abstract(entry: Dict[str, Any]) -> str:
+ abstract = (entry.get("abstract") or "").strip()
+ # A directory with no generated .abstract.md (a skill's scripts/, say) comes back as a
+ # placeholder that carries no summary.
+ placeholders = (
+ "[.abstract.md is not ready]",
+ f"# {entry.get('uri', '')} [Directory abstract is not ready]",
+ )
+ if abstract in placeholders:
+ return ""
+ return " ".join(abstract.split())
+
@mcp.tool()
async def tree(
@@ -759,7 +868,8 @@ async def tree(
uri: Directory URI to traverse.
level_limit: Maximum traversal depth.
node_limit: Existing default result limit.
- include_abstract: Whether to include file summaries.
+ include_abstract: Whether to include directory summaries (a skill directory's
+ summary is its name and description).
offset: Number of visible nodes to skip.
limit: Optional result limit that overrides node_limit.
@@ -781,6 +891,7 @@ async def tree(
resolved_uri,
ctx=ctx,
output=output,
+ abs_limit=_TREE_ABSTRACT_LIMIT,
node_limit=effective_limit,
level_limit=level_limit,
offset=offset,
@@ -800,9 +911,9 @@ async def tree(
indent = " " * max(0, depth - 1)
if e.get("isDir"):
lines.append(f"{indent}{name}/")
- continue
- lines.append(f"{indent}{name} ({e.get('size', 0)} B)")
- abstract = (e.get("abstract") or "").strip().replace("\n", " ")
+ else:
+ lines.append(f"{indent}{name} ({e.get('size', 0)} B)")
+ abstract = _tree_abstract(e)
if include_abstract and abstract:
lines.append(f"{indent} - {abstract}")
if len(entries) >= effective_limit:
@@ -860,7 +971,7 @@ async def write(
- Any new file (whether created by "replace" or "create") must end in one of: .md .txt .json .yaml .yml .toml .py .js .ts
- mode="append": append to the end of an existing file; fails if the file does not exist.
- Writable scopes: viking://resources/, viking://user/{user_id}/, viking://agent/. The viking://~ home alias expands to the caller's user root. The managed user subtrees skills/, peers/, privacy/ and sessions/ are read-only. After a write, semantic search indexes refresh in the background; pass wait=true to block until search reflects the change."""
+ Writable scopes: viking://resources/, viking://user/{user_id}/, viking://agent/. The viking://~ home alias expands to the caller's user root. The managed user subtrees skills/, peers/, privacy/ and sessions/ are read-only. Do not write inside a skill package under viking://agent/skills/ either: a plain write skips installation, so the skill's abstract, overview and source metadata go stale. Change a skill with the add_skill tool. After a write, semantic search indexes refresh in the background; pass wait=true to block until search reflects the change."""
service = get_service()
ctx = _get_ctx()
uri = _resolve_mcp_workspace_uri(uri, ctx)
@@ -896,7 +1007,9 @@ async def edit(
) -> str:
"""Replace an exact string with new text in an existing viking:// file. Use this for targeted changes instead of rewriting the whole file with the write tool. old_string must match the file's current content exactly, including indentation and newlines; use the read tool first to see it. The edit fails and the file is left unchanged if old_string is not found, or if it matches more than once and replace_all is false (pass more surrounding context to make it unique, or set replace_all=true to replace every occurrence). Pass new_string="" to delete old_string.
- Editing a memory file preserves its metadata; after an edit, search indexes refresh in the background (pass wait=true to block until search reflects the change)."""
+ Editing a memory file preserves its metadata; after an edit, search indexes refresh in the background (pass wait=true to block until search reflects the change).
+
+ Do not edit files inside a skill package (.../skills/<name>/): read the skill's SKILL.md, revise the whole text, and install it again with the add_skill tool."""
service = get_service()
ctx = _get_ctx()
uri = _resolve_mcp_workspace_uri(uri, ctx)
@@ -1055,6 +1168,9 @@ async def add_resource(
) -> str:
"""Add a resource to OpenViking. Asynchronous — processing happens in the background.
+ For an agent skill, use add_skill instead: a skill added here is stored as an ordinary
+ resource and never becomes an installed skill.
+
Remote URL: pass ``path`` as an http(s)://, git@, ssh://, or git:// URL. A sitemap /
RSS / Atom URL ingests the WHOLE site as one resource tree; pass ``args={"site": true}``
to force whole-site ingestion from a bare domain.
@@ -1298,6 +1414,184 @@ async def add_resource(
return prose
+# -- add_skill -------------------------------------------------------------
+
+
+def _format_skill_install_result(result: Dict[str, Any], *, list_only: bool) -> str:
+ if result.get("status") == "error":
+ return f"Error adding skill: {result.get('message') or 'skill processing failed'}"
+ if list_only:
+ found = result.get("skills") or []
+ lines = [f"Skills in the source ({len(found)}); nothing was installed:"]
+ for item in found:
+ description = " ".join(str(item.get("description") or "").split())
+ lines.append(f"- {item.get('name', '?')} ({item.get('path', '')}): {description}")
+ return "\n".join(lines)
+ installed = result.get("installed") if "installed" in result else [result]
+ lines = [f"Skill added: {item['root_uri']}" for item in installed]
+ lines.append(
+ "Read <uri>/SKILL.md to use it now; semantic search finds it once indexing completes."
+ )
+ return "\n".join(lines)
+
+
+async def add_skill(
+ data: str = "",
+ path: str = "",
+ skills: Optional[list[str]] = None,
+ target_uri: str = "",
+ list_only: bool = False,
+) -> str:
+ """Create, install, or replace an agent skill in OpenViking.
+
+ New skill: pass the full SKILL.md text (YAML frontmatter with ``name`` and
+ ``description``, then the Markdown body) as ``data``.
+
+ Git source: pass a repository URL or a GitHub ``.../tree/<ref>/<dir>`` URL as ``path``.
+ Every skill in the source is installed unless ``skills`` names some; ``list_only=true``
+ lists them without installing.
+
+ Local skill: pass the path of a SKILL.md, a skill directory, or a .zip as ``path``. The
+ response is an upload instruction — zip a directory first, then HTTP POST the file to the
+ returned URL and the server installs it; you do NOT need to call this tool again.
+
+ Installing under an existing name replaces that skill's SKILL.md and adds the new files;
+ files the new version no longer has are kept. Ask the user before installing from a
+ source they did not name.
+
+ This is the only MCP tool that creates or changes a skill. To update one, read its
+ SKILL.md, revise the whole text, and call add_skill again with the same name and the same
+ ``target_uri``; do not use the write or edit tools on files inside a skill package, and do
+ not use forget or a directory move to delete or rename one -- remove a skill with
+ ``ov skills remove <name>`` or ``DELETE /api/v1/skills/{name}``, and rename it by
+ installing it under the new name and removing the old one.
+
+ Args:
+ data: Full SKILL.md text of a skill to create or replace.
+ path: Git URL, or a local path to a SKILL.md, a skill directory, or a .zip.
+ skills: Names of the skill directories to install from a multi-skill source.
+ target_uri: Skill root to install under. Empty installs into the caller's own
+ skills; "viking://agent/skills" shares the skill with the whole account.
+ list_only: Describe the skills in a Git or local source without installing them.
+ """
+ ctx = _get_ctx()
+ path = path.strip()
+ if data.strip() and path:
+ return "Error: pass either 'data' (SKILL.md text) or 'path', not both."
+ if not data.strip() and not path:
+ return "Error: provide 'data' (full SKILL.md text) or 'path' (Git URL or local path)."
+ if data.strip() and looks_like_local_path(data.strip()):
+ return (
+ f"Error: 'data' looks like a file path. Pass it as add_skill(path=\"{data.strip()}\")."
+ )
+ if path.startswith("viking://"):
+ return (
+ "Error: 'path' must be a Git URL or a local path. To copy a skill already in "
+ "OpenViking, read its SKILL.md and pass the text as 'data'."
+ )
+ is_git = path.startswith(GIT_SKILL_SOURCE_PREFIXES)
+ if path and not is_git and is_remote_resource_source(path):
+ return (
+ f"Error: unsupported skill source '{path}'. Pass a Git URL "
+ f"({', '.join(GIT_SKILL_SOURCE_PREFIXES)}) or a local path."
+ )
+ try:
+ target = resolve_path_variables(target_uri).strip() if target_uri else ""
+ if target:
+ target = validate_content_target_uri(target, ctx, kind="skill", field_name="target_uri")
+ # Fail here, not after a one-time upload token is spent on a root the installer rejects.
+ target = SkillProcessor._resolve_skill_root_uri(ctx, target) # noqa: SLF001
+ except (InvalidArgumentError, PermissionDeniedError) as exc:
+ return f"Error: {exc}"
+
+ if data.strip() or is_git:
+ try:
+ result = await install_skills(
+ data or path,
+ ctx,
+ names=skills,
+ list_only=list_only,
+ target_uri=target,
+ source_metadata=(
+ {"type": "mcp", "source": "inline_content", "operation": "add"}
+ if data.strip()
+ else None
+ ),
+ )
+ except (InvalidArgumentError, PermissionDeniedError) as exc:
+ return f"Error: {exc}"
+ except Exception as exc:
+ return f"Error adding skill: {exc}"
+ return _format_skill_install_result(result, list_only=list_only)
+
+ server_config = get_server_config()
+ ttl_seconds = (
+ server_config.upload_signed_ttl_seconds
+ if server_config is not None
+ else _DEFAULT_UPLOAD_TTL_SECONDS
+ )
+ token, expires_at = upload_token_store.issue(
+ ctx.user.account_id,
+ ctx.user.user_id,
+ ttl_seconds=ttl_seconds,
+ actor_peer_id=ctx.actor_peer_id or "",
+ kind="skill",
+ skill_target_uri=target,
+ skill_names=skills,
+ list_only=list_only,
+ )
+ base_url, url_source = _resolve_public_base_url()
+ 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)
+
+ if list_only:
+ headline = "Local skill source detected — upload it to list the skills it contains.\n"
+ outcome = (
+ "The URL's token authorizes this one upload (no OpenViking API key needed). The "
+ "server only lists the skills in the file and installs nothing; the upload response "
+ "carries each skill's name, path, and description. To install, call add_skill again "
+ "without list_only (skills=[...] picks some) and upload to the new URL.\n"
+ )
+ else:
+ headline = "Local skill detected — upload it to install.\n"
+ outcome = (
+ "The URL's token authorizes this one upload (no OpenViking API key needed) and the "
+ "server installs the skill once the file arrives — you do NOT need to call add_skill "
+ "again. The upload response carries the installed skill URIs.\n"
+ )
+ prose = (
+ headline + "\n"
+ "A skill directory must be zipped first (a single SKILL.md can be uploaded as is). "
+ "Every file in the archive is stored with the skill, so leave out VCS data and "
+ "secrets, for example:\n"
+ "\n"
+ " cd <parent dir> && rm -f /tmp/<name>.zip && zip -r /tmp/<name>.zip <name> "
+ "-x '*/.git/*' '*/.env*' '*/node_modules/*' '*/.DS_Store'\n"
+ "\n"
+ 'Then HTTP POST the file (multipart/form-data, field name "file") to:\n'
+ "\n"
+ f" {upload_url}\n"
+ "\n" + outcome + "\n"
+ "If the OpenViking server sits behind a private gateway or reverse proxy that "
+ "requires extra request headers, replay the same headers you use for MCP calls "
+ "when POSTing the file.\n"
+ "\n"
+ f"This upload URL expires in ~{minutes} minutes ({expires_iso})."
+ )
+ if url_source not in ("env", "config"):
+ prose += (
+ "\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 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 and retry."
+ )
+ return prose
+
+
# -- watch management ------------------------------------------------------
# MCP exposes the minimum closure: list + cancel. Pause/resume/trigger and
# the unified `update` verb are intentionally NOT exposed — they're either
@@ -1478,7 +1772,10 @@ async def glob(pattern: str, uri: str = "viking://", node_limit: int = 100) -> s
@mcp.tool()
async def forget(uri: str, recursive: bool = False) -> str:
- """Permanently delete a viking:// URI from OpenViking. Irreversible — confirm with user before calling."""
+ """Permanently delete a viking:// URI from OpenViking. Irreversible — confirm with user before calling.
+
+ Deleting a skill directory this way leaves the skill's stored privacy values behind:
+ remove a skill with ``ov skills remove <name>`` or ``DELETE /api/v1/skills/{name}``."""
service = get_service()
ctx = _get_ctx()
resolved_uri = _resolve_mcp_workspace_uri(uri, ctx)
@@ -1597,8 +1894,9 @@ async def mcp_lifespan():
"""Run the MCP session manager. Call this inside the FastAPI lifespan."""
async with mcp.session_manager.run():
logger.info(
- "MCP endpoint ready (15 tools: find, search, read, write, edit, list, "
- "tree, remember, add_resource, list_watches, cancel_watch, grep, glob, forget, health)"
+ "MCP endpoint ready (16 tools: find, search, read, write, edit, list, tree, "
+ "remember, add_resource, add_skill, list_watches, cancel_watch, grep, glob, forget, "
+ "health)"
)
yield
diff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.py
index a300b87f0..155fd3ae0 100644
--- a/openviking/server/routers/resources.py
+++ b/openviking/server/routers/resources.py
@@ -2,8 +2,6 @@
# SPDX-License-Identifier: AGPL-3.0
"""Resource endpoints for OpenViking HTTP Server."""
-import asyncio
-from pathlib import Path
from typing import Any, Dict, Literal, Optional
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
@@ -18,9 +16,9 @@ from openviking.server.identity import RequestContext
from openviking.server.local_input_guard import require_remote_resource_source
from openviking.server.resource_ingest import ingest_temp_upload
from openviking.server.responses import response_from_result
+from openviking.server.skill_ingest import ingest_temp_upload_skill, install_skills
from openviking.server.telemetry import run_operation
from openviking.server.temp_upload_store import TempUploadStore
-from openviking.service.skill_sources import describe_skill_sources, resolve_skill_source
from openviking.telemetry import TelemetryRequest
from openviking_cli.exceptions import InvalidArgumentError
@@ -181,7 +179,8 @@ async def temp_upload(
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
+ the agent never needs a second call. Tokens minted by the MCP ``add_skill`` tool install
+ the upload as skills instead. The ``?token=`` query param is consumed by the auth
dependency.
"""
signed = getattr(request.state, "signed_upload", None)
@@ -192,6 +191,16 @@ async def temp_upload(
temp_file_id = await store.save_upload(file, effective_upload_mode, _ctx)
if signed is None:
return {"temp_file_id": temp_file_id}
+ if signed.kind == "skill":
+ return await ingest_temp_upload_skill(
+ store,
+ temp_file_id,
+ _ctx,
+ target_uri=signed.skill_target_uri,
+ names=signed.skill_names,
+ list_only=signed.list_only,
+ source_type="mcp",
+ )
return await ingest_temp_upload(
store,
temp_file_id,
@@ -355,7 +364,6 @@ async def add_skill(
_ctx: RequestContext = Depends(get_request_context),
):
"""Add skill to OpenViking."""
- service = get_service()
target_uri = resolve_path_variables(request.target_uri).strip() if request.target_uri else ""
if target_uri:
target_uri = validate_content_target_uri(
@@ -391,43 +399,19 @@ async def add_skill(
async def _add() -> dict[str, Any]:
try:
- async with resolve_skill_source(
+ return await install_skills(
data,
+ _ctx,
names=request.skills,
- allow_local_path_resolution=allow_local_path_resolution,
+ list_only=request.list_only,
+ wait=request.wait,
+ timeout=request.timeout,
+ target_uri=target_uri,
source_metadata=source_metadata,
- ) as targets:
- if request.list_only:
- return await asyncio.to_thread(describe_skill_sources, targets)
- installed = []
- for skill_data, skill_source in targets:
-
- async def _install(skill_data=skill_data, skill_source=skill_source):
- result = await service.resources.add_skill(
- data=skill_data,
- ctx=_ctx,
- wait=request.wait,
- timeout=request.timeout,
- allow_local_path_resolution=isinstance(skill_data, Path),
- source_path_hint=source_path_hint,
- target_uri=target_uri,
- source_metadata=skill_source,
- )
- return result
-
- # Each skill owns its own queue wait tracker and task ID.
- if len(targets) == 1:
- installed.append(await _install())
- else:
- execution = await run_operation(
- operation="resources.add_skill",
- telemetry=request.telemetry,
- fn=_install,
- )
- installed.append(execution.result)
- if len(installed) == 1:
- return installed[0]
- return {"installed": installed, "total": len(installed)}
+ allow_local_path_resolution=allow_local_path_resolution,
+ source_path_hint=source_path_hint,
+ telemetry=request.telemetry,
+ )
finally:
if resolved:
await resolved.cleanup()
diff --git a/openviking/server/routers/skills.py b/openviking/server/routers/skills.py
index ce2a8d94e..25add93de 100644
--- a/openviking/server/routers/skills.py
+++ b/openviking/server/routers/skills.py
@@ -53,6 +53,7 @@ from openviking_cli.utils import get_logger
router = APIRouter(prefix="/api/v1/skills", tags=["skills"])
logger = get_logger(__name__)
+_DEFAULT_SKILL_LIST_LIMIT = 1000
_SKILL_INTEGRITY_MAX_ENTRIES = 512
_SKILL_INTEGRITY_MAX_FILE_BYTES = 16 * 1024 * 1024
_SKILL_INTEGRITY_MAX_TOTAL_BYTES = 64 * 1024 * 1024
@@ -125,7 +126,7 @@ def _agent_skills_root(ctx: RequestContext, target_uri: Optional[str] = None) ->
async def _list_skills_from_root(
- service, ctx: RequestContext, root_uri: str
+ service, ctx: RequestContext, root_uri: str, node_limit: int = _DEFAULT_SKILL_LIST_LIMIT
) -> list[Dict[str, Any]]:
"""List skills from a specific root URI.
@@ -142,7 +143,7 @@ async def _list_skills_from_root(
ctx=ctx,
output="agent",
abs_limit=1024,
- node_limit=1000,
+ node_limit=node_limit,
)
except NotFoundError:
return []
@@ -555,25 +556,26 @@ async def _restore_skill_privacy(
@router.get("")
async def list_skills(
- node_limit: int = 1000,
+ node_limit: int = _DEFAULT_SKILL_LIST_LIMIT,
target_uri: Optional[str] = None,
_ctx: RequestContext = Depends(get_request_context),
):
- """List installed agent skills."""
+ """List installed agent skills; ``node_limit`` caps each skill root (0 keeps the default)."""
service = get_service()
+ limit = node_limit if node_limit > 0 else _DEFAULT_SKILL_LIST_LIMIT
if target_uri:
resolved_uri = validate_request_viking_uri(
resolve_path_variables(target_uri), _ctx, field_name="target_uri"
)
- skills = await _list_skills_from_root(service, _ctx, resolved_uri)
+ skills = await _list_skills_from_root(service, _ctx, resolved_uri, limit)
return Response(
status="ok", result={"root_uri": resolved_uri, "skills": skills, "total": len(skills)}
)
else:
user_skills = await _list_skills_from_root(
- service, _ctx, f"{canonical_user_root(_ctx)}/skills"
+ service, _ctx, f"{canonical_user_root(_ctx)}/skills", limit
)
- agent_skills = await _list_skills_from_root(service, _ctx, "viking://agent/skills")
+ agent_skills = await _list_skills_from_root(service, _ctx, "viking://agent/skills", limit)
# Intentionally concatenate without deduplication: when the same skill
# name exists in both the user-private and the account-shared agent
# scope, both entries should be visible so the caller can tell them
diff --git a/openviking/server/skill_ingest.py b/openviking/server/skill_ingest.py
new file mode 100644
index 000000000..33921c5c3
--- /dev/null
+++ b/openviking/server/skill_ingest.py
@@ -0,0 +1,116 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Shared skill installation for ``POST /api/v1/skills``, the MCP ``add_skill`` tool,
+and signed skill uploads.
+
+One implementation resolves the source (inline SKILL.md, Git URL, or an uploaded
+directory/zip), installs every selected skill, and persists each skill's source
+metadata, so the three entry points cannot drift apart.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from typing import Any, Optional
+
+from openviking.server.dependencies import get_service
+from openviking.server.identity import RequestContext
+from openviking.server.telemetry import run_operation
+from openviking.server.temp_upload_store import TempUploadStore
+from openviking.service.skill_sources import describe_skill_sources, resolve_skill_source
+from openviking.telemetry import TelemetryRequest
+
+
+async def install_skills(
+ data: Any,
+ ctx: RequestContext,
+ *,
+ names: Optional[list[str]] = None,
+ list_only: bool = False,
+ wait: bool = False,
+ timeout: Optional[float] = None,
+ target_uri: str = "",
+ source_metadata: Optional[dict[str, Any]] = None,
+ allow_local_path_resolution: bool = False,
+ source_path_hint: Optional[str] = None,
+ telemetry: TelemetryRequest = False,
+) -> dict[str, Any]:
+ """Install the skills found in ``data``; return one result or ``{"installed", "total"}``.
+
+ ``list_only`` describes the source's skills without persisting anything.
+ ``target_uri`` must already be validated as a skill root by the caller.
+ """
+ service = get_service()
+ async with resolve_skill_source(
+ data,
+ names=names,
+ allow_local_path_resolution=allow_local_path_resolution,
+ source_metadata=source_metadata,
+ ) as targets:
+ if list_only:
+ return await asyncio.to_thread(describe_skill_sources, targets)
+ installed = []
+ for skill_data, skill_source in targets:
+
+ async def _install(skill_data=skill_data, skill_source=skill_source):
+ result = await service.resources.add_skill(
+ data=skill_data,
+ ctx=ctx,
+ wait=wait,
+ timeout=timeout,
+ allow_local_path_resolution=isinstance(skill_data, Path),
+ source_path_hint=source_path_hint,
+ target_uri=target_uri,
+ source_metadata=skill_source,
+ )
+ return result
+
+ # Each skill owns its own queue wait tracker and task ID.
+ if len(targets) == 1:
+ installed.append(await _install())
+ else:
+ execution = await run_operation(
+ operation="resources.add_skill",
+ telemetry=telemetry,
+ fn=_install,
+ )
+ installed.append(execution.result)
+ if len(installed) == 1:
+ return installed[0]
+ return {"installed": installed, "total": len(installed)}
+
+
+async def ingest_temp_upload_skill(
+ store: TempUploadStore,
+ temp_file_id: str,
+ ctx: RequestContext,
+ *,
+ target_uri: str = "",
+ names: Optional[list[str]] = None,
+ list_only: bool = False,
+ source_type: str = "api",
+) -> dict[str, Any]:
+ """Resolve an uploaded SKILL.md, directory archive, or zip and install its skills."""
+ resolved = await store.resolve_for_consume(temp_file_id, ctx)
+ try:
+ source_metadata: dict[str, Any] = {
+ "type": source_type,
+ "source": "temp_upload",
+ "operation": "add",
+ "upload_mode": resolved.mode,
+ }
+ if resolved.original_filename:
+ source_metadata["original_filename"] = resolved.original_filename
+ return await install_skills(
+ resolved.local_path,
+ ctx,
+ names=names,
+ list_only=list_only,
+ target_uri=target_uri,
+ source_metadata=source_metadata,
+ allow_local_path_resolution=True,
+ source_path_hint=resolved.original_filename,
+ )
+ finally:
+ await resolved.cleanup()
diff --git a/openviking/server/upload_token_store.py b/openviking/server/upload_token_store.py
index 811b3a814..c2420c96d 100644
--- a/openviking/server/upload_token_store.py
+++ b/openviking/server/upload_token_store.py
@@ -11,7 +11,9 @@ 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``/``parent``/``reason``/``parse_mode``) 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
+``add_resource``, and the ingest keeps the original peer scope. Tokens minted by the MCP
+``add_skill`` tool carry ``kind="skill"`` plus the skill install params instead, and the upload
+is installed as skills rather than ingested as a resource. 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 shared
TempUploadStore mode without a side-channel.
@@ -52,6 +54,10 @@ class _TokenInfo:
tag_mode: str
parse_mode: str
expires_at: float
+ kind: str = "resource"
+ skill_target_uri: str = ""
+ skill_names: Optional[list[str]] = None
+ list_only: bool = False
@dataclass(frozen=True)
@@ -68,6 +74,10 @@ class ConsumedUploadToken:
tags: Optional[list[str]] = None
tag_mode: str = "replace"
parse_mode: str = "default"
+ kind: str = "resource"
+ skill_target_uri: str = ""
+ skill_names: Optional[list[str]] = None
+ list_only: bool = False
class UploadTokenStore:
@@ -88,8 +98,12 @@ class UploadTokenStore:
tags: Optional[list[str]] = None,
tag_mode: str = "replace",
parse_mode: str = "default",
+ kind: str = "resource",
+ skill_target_uri: str = "",
+ skill_names: Optional[list[str]] = None,
+ list_only: bool = False,
) -> Tuple[str, float]:
- """Mint a fresh token bound to the caller identity and resource ingestion parameters.
+ """Mint a fresh token bound to the caller identity and ingestion parameters.
``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
@@ -110,6 +124,10 @@ class UploadTokenStore:
tag_mode,
parse_mode,
expires_at,
+ kind,
+ skill_target_uri,
+ skill_names,
+ list_only,
)
for _ in range(8):
token = "".join(secrets.choice(_TOKEN_ALPHABET) for _ in range(_TOKEN_LENGTH))
@@ -138,6 +156,10 @@ class UploadTokenStore:
tags=info.tags,
tag_mode=info.tag_mode,
parse_mode=info.parse_mode,
+ kind=info.kind,
+ skill_target_uri=info.skill_target_uri,
+ skill_names=info.skill_names,
+ list_only=info.list_only,
)
def peek(self, token: str) -> Optional[_TokenInfo]:
diff --git a/openviking/service/search_service.py b/openviking/service/search_service.py
index 89b09c415..790201fe4 100644
--- a/openviking/service/search_service.py
+++ b/openviking/service/search_service.py
@@ -179,7 +179,7 @@ class SearchService:
self,
query: str,
ctx: RequestContext,
- target_uri: str,
+ target_uri: Union[str, List[str]],
limit: int = 10,
score_threshold: Optional[float] = None,
level: Optional[List[int]] = None,
diff --git a/openviking/service/skill_sources.py b/openviking/service/skill_sources.py
index b63ddc17f..c5803b71c 100644
--- a/openviking/service/skill_sources.py
+++ b/openviking/service/skill_sources.py
@@ -17,6 +17,8 @@ from openviking.utils.network_guard import ensure_public_remote_target
from openviking.utils.skill_processor import SkillProcessor, validate_skill_name
from openviking_cli.exceptions import InvalidArgumentError
+GIT_SKILL_SOURCE_PREFIXES = ("https://", "http://", "git@", "ssh://", "git://")
+
def parse_git_skill_source(source: str) -> dict:
"""Parse a Git URL into repository, revision, and skill subdirectory."""
@@ -95,7 +97,7 @@ async def resolve_skill_source(
try:
if (
isinstance(data, str)
- and data.startswith(("https://", "http://", "git@", "ssh://", "git://"))
+ and data.startswith(GIT_SKILL_SOURCE_PREFIXES)
and "\n" not in data
):
git_source = git_source or parse_git_skill_source(data)
diff --git a/openviking/utils/skill_processor.py b/openviking/utils/skill_processor.py
index 4ef064c30..515098f9c 100644
--- a/openviking/utils/skill_processor.py
+++ b/openviking/utils/skill_processor.py
@@ -437,7 +437,7 @@ class SkillProcessor:
if normalized == user_root.rstrip("/"):
return user_root
raise InvalidArgumentError(
- f"Unsupported skill root URI: {target_uri}",
+ f"Unsupported skill root URI: {target_uri}; use {user_root} or viking://agent/skills",
details={
"field": "target_uri",
"allowed": [
diff --git a/tests/server/test_api_skills.py b/tests/server/test_api_skills.py
index 7662cfcee..542348e10 100644
--- a/tests/server/test_api_skills.py
+++ b/tests/server/test_api_skills.py
@@ -58,6 +58,19 @@ async def test_skills_api_list_empty_collection(client):
assert listed["total"] == 0
+async def test_skills_api_list_honors_node_limit(client):
+ await _add_skill(client, "limit-skill-a", "First skill")
+ await _add_skill(client, "limit-skill-b", "Second skill")
+
+ limited = await client.get("/api/v1/skills", params={"node_limit": 1})
+ assert limited.status_code == 200, limited.text
+ assert limited.json()["result"]["total"] == 1
+
+ default = await client.get("/api/v1/skills", params={"node_limit": 0})
+ assert default.status_code == 200, default.text
+ assert default.json()["result"]["total"] == 2
+
+
async def test_skills_api_list_show_find_and_delete(client):
added = await _add_skill(client, "api-skill", "API skill for list and show")
assert added["uri"].endswith("/skills/api-skill")
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index 336072e9a..45e76fce9 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -29,6 +29,7 @@ from openviking.server.mcp_endpoint import (
_mcp_ctx,
_resolve_mcp_workspace_uri,
add_resource,
+ add_skill,
cancel_watch,
edit,
forget,
@@ -307,6 +308,318 @@ async def test_find_tool_calls_lightweight_find(service, monkeypatch):
}
+ ("context_type", "expected_targets", "expected_route"),
+ [
+ ("skill", ["viking://user/test_user/skills", "viking://agent/skills"], "find_skills"),
+ (["skill"], ["viking://user/test_user/skills", "viking://agent/skills"], "find_skills"),
+ (["skill", "memory"], "", "find"),
+ (None, "", "find"),
+ ],
+)
+async def test_find_tool_skill_only_searches_both_skill_roots(
+ service, monkeypatch, context_type, expected_targets, expected_route
+):
+ captured = {}
+
+ def _record(route):
+ async def fake(**kwargs):
+ captured["route"] = route
+ captured.update(kwargs)
+ return SimpleNamespace(memories=[], resources=[], skills=[])
+
+ return fake
+
+ monkeypatch.setattr(service.search, "find", _record("find"))
+ monkeypatch.setattr(service.search, "find_skills", _record("find_skills"))
+ token = _mcp_ctx.set(RequestContext(DEFAULT_CTX.user, Role.USER))
+ try:
+ await mcp_endpoint.find(query="review a PR", context_type=context_type)
+ finally:
+ _mcp_ctx.reset(token)
+
+ assert captured["route"] == expected_route
+ assert captured["target_uri"] == expected_targets
+
+
+async def test_find_tool_points_skill_hits_at_their_skill_md(service, monkeypatch):
+ hit = SimpleNamespace(
+ uri="viking://agent/skills/deploy-runbook/.abstract.md",
+ abstract="name: deploy-runbook\ndescription: Shared runbook",
+ score=0.61,
+ )
+ read_uris = []
+
+ async def fake_find_skills(**kwargs):
+ return SimpleNamespace(memories=[], resources=[], skills=[hit])
+
+ async def fake_read_visible(uri, ctx):
+ read_uris.append(uri)
+ return "# Deploy runbook"
+
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
+ monkeypatch.setattr(service.fs, "read_visible", fake_read_visible)
+
+ result = await mcp_endpoint.find(query="roll back", context_type="skill", read_content=True)
+
+ assert "- [skill 61%] viking://agent/skills/deploy-runbook/SKILL.md" in result
+ assert ".abstract.md" not in result
+ assert "# Deploy runbook" in result
+ assert read_uris == ["viking://agent/skills/deploy-runbook/SKILL.md"]
+
+
+async def test_find_tool_points_an_auxiliary_file_hit_at_the_skill_md(service, monkeypatch):
+ hit = SimpleNamespace(
+ uri="viking://user/test_user/skills/pdf-forms/scripts/fill.py",
+ abstract="Fill a PDF form field by field",
+ score=0.52,
+ )
+
+ async def fake_find_skills(**kwargs):
+ return SimpleNamespace(memories=[], resources=[], skills=[hit])
+
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
+
+ result = await mcp_endpoint.find(query="fill a pdf", context_type="skill")
+
+ assert "- [skill 52%] viking://user/test_user/skills/pdf-forms/SKILL.md" in result
+ assert "scripts/fill.py" not in result
+
+
+async def test_find_tool_keeps_same_named_skills_from_both_roots(service, monkeypatch):
+ hits = [
+ SimpleNamespace(
+ uri="viking://user/test_user/skills/review/.abstract.md",
+ abstract="My own review skill",
+ score=0.70,
+ ),
+ SimpleNamespace(
+ uri="viking://agent/skills/review/.abstract.md",
+ abstract="The shared review skill",
+ score=0.60,
+ ),
+ ]
+
+ async def fake_find_skills(**kwargs):
+ return SimpleNamespace(memories=[], resources=[], skills=hits)
+
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
+
+ result = await mcp_endpoint.find(query="review", context_type="skill")
+
+ assert "Found 2 item(s)" in result
+ assert "viking://user/test_user/skills/review/SKILL.md" in result
+ assert "viking://agent/skills/review/SKILL.md" in result
+
+
+async def test_find_tool_collapses_several_hits_from_one_skill_package(service, monkeypatch):
+ hits = [
+ SimpleNamespace(
+ uri="viking://agent/skills/deploy/scripts/rollback.sh",
+ abstract="Roll back the last release",
+ score=0.44,
+ ),
+ SimpleNamespace(
+ uri="viking://agent/skills/deploy/.overview.md",
+ abstract="How the deploy skill works",
+ score=0.71,
+ ),
+ ]
+
+ async def fake_find(**kwargs):
+ return SimpleNamespace(memories=[], resources=[], skills=hits)
+
+ monkeypatch.setattr(service.search, "find", fake_find)
+
+ result = await mcp_endpoint.find(query="roll back", context_type=["skill", "memory"])
+
+ assert "Found 1 item(s)" in result
+ assert "- [skill 71%] viking://agent/skills/deploy/SKILL.md" in result
+ assert "How the deploy skill works" in result
+
+
+async def test_find_tool_forwards_its_bounds_to_find_skills(service, monkeypatch):
+ captured = {}
+
+ async def fake_find_skills(**kwargs):
+ captured.update(kwargs)
+ return SimpleNamespace(memories=[], resources=[], skills=[])
+
+ async def fail_find(**kwargs):
+ raise AssertionError("A skill-only find should call find_skills, not find")
+
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
+ monkeypatch.setattr(service.search, "find", fail_find)
+
+ await mcp_endpoint.find(
+ query="review a PR", limit=3, min_score=0.5, level=[0], context_type="skill"
+ )
+
+ assert captured["query"] == "review a PR"
+ assert captured["ctx"] == DEFAULT_CTX
+ assert captured["limit"] == 3
+ assert captured["score_threshold"] == 0.5
+ assert captured["level"] == [0]
+ # find_skills restricts by context type itself and takes no filter.
+ assert "filter" not in captured
+
+
+async def test_find_tool_forwards_an_explicit_skill_target_to_find_skills(service, monkeypatch):
+ captured = {}
+
+ async def fake_find_skills(**kwargs):
+ captured.update(kwargs)
+ return SimpleNamespace(memories=[], resources=[], skills=[])
+
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
+ token = _mcp_ctx.set(RequestContext(DEFAULT_CTX.user, Role.USER))
+ try:
+ await mcp_endpoint.find(
+ query="review a PR", target_uri="viking://~/skills", context_type="skill"
+ )
+ finally:
+ _mcp_ctx.reset(token)
+
+ assert captured["target_uri"] == "viking://user/test_user/skills"
+
+
+async def test_find_tool_keeps_a_filter_only_skill_query_on_the_generic_find(service, monkeypatch):
+ captured = {}
+
+ async def fake_find(**kwargs):
+ captured.update(kwargs)
+ return SimpleNamespace(memories=[], resources=[], skills=[])
+
+ async def fail_find_skills(**kwargs):
+ raise AssertionError("find_skills rejects an empty query")
+
+ monkeypatch.setattr(service.search, "find", fake_find)
+ monkeypatch.setattr(service.search, "find_skills", fail_find_skills)
+
+ await mcp_endpoint.find(query="", context_type="skill")
+
+ assert captured["filter"] == {"op": "must", "field": "context_type", "conds": ["skill"]}
+
+
+ "hit_uri",
+ [
+ "viking://user/test_user/skills/.review.update-backup-ab12/SKILL.md",
+ "viking://agent/skills",
+ ],
+)
+async def test_find_tool_leaves_a_uri_outside_a_skill_package_alone(service, monkeypatch, hit_uri):
+ hit = SimpleNamespace(uri=hit_uri, abstract="Not an installed skill", score=0.4)
+
+ async def fake_find_skills(**kwargs):
+ return SimpleNamespace(memories=[], resources=[], skills=[hit])
+
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
+
+ result = await mcp_endpoint.find(query="review", context_type="skill")
+
+ assert f"- [skill 40%] {hit_uri}\n" in result
+ assert "SKILL.md/SKILL.md" not in result
+
+
+async def test_find_tool_describes_a_package_file_hit_with_the_skill_abstract(service, monkeypatch):
+ hit = SimpleNamespace(
+ uri="viking://agent/skills/pdf-forms/scripts/fill.py",
+ abstract="Iterate the AcroForm fields and write each value",
+ score=0.52,
+ )
+ abstract_uris = []
+
+ async def fake_find_skills(**kwargs):
+ return SimpleNamespace(memories=[], resources=[], skills=[hit])
+
+ async def fake_abstract(uri, ctx):
+ abstract_uris.append(uri)
+ return "name: pdf-forms\ndescription: Fill in a PDF form"
+
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
+ monkeypatch.setattr(service.fs, "abstract", fake_abstract)
+
+ result = await mcp_endpoint.find(query="fill a pdf", context_type="skill")
+
+ assert abstract_uris == ["viking://agent/skills/pdf-forms"]
+ assert "description: Fill in a PDF form" in result
+ assert "AcroForm" not in result
+
+
+async def test_find_tool_keeps_the_file_abstract_when_the_package_has_none(service, monkeypatch):
+ hit = SimpleNamespace(
+ uri="viking://agent/skills/pdf-forms/scripts/fill.py",
+ abstract="Iterate the AcroForm fields and write each value",
+ score=0.52,
+ )
+
+ async def fake_find_skills(**kwargs):
+ return SimpleNamespace(memories=[], resources=[], skills=[hit])
+
+ async def fake_abstract(uri, ctx):
+ return f"# {uri} [Directory abstract is not ready]"
+
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
+ monkeypatch.setattr(service.fs, "abstract", fake_abstract)
+
+ result = await mcp_endpoint.find(query="fill a pdf", context_type="skill")
+
+ assert "is not ready" not in result
+ assert "Iterate the AcroForm fields" in result
+
+
+async def test_find_tool_keeps_the_package_abstract_of_a_sidecar_hit(service, monkeypatch):
+ hit = SimpleNamespace(
+ uri="viking://agent/skills/pdf-forms/.abstract.md",
+ abstract="name: pdf-forms\ndescription: Fill in a PDF form",
+ score=0.52,
+ )
+
+ abstract_uris = []
+
+ async def fake_find_skills(**kwargs):
+ return SimpleNamespace(memories=[], resources=[], skills=[hit])
+
+ async def fake_abstract(uri, ctx):
+ abstract_uris.append(uri)
+ return ""
+
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
+ monkeypatch.setattr(service.fs, "abstract", fake_abstract)
+
+ result = await mcp_endpoint.find(query="fill a pdf", context_type="skill")
+
+ # A package-level hit already carries the skill's abstract.
+ assert abstract_uris == []
+ assert "description: Fill in a PDF form" in result
+
+
+async def test_search_tool_collapses_skill_package_hits(service, monkeypatch):
+ hits = [
+ SimpleNamespace(
+ uri="viking://agent/skills/deploy/scripts/rollback.sh",
+ abstract="Roll back the last release",
+ score=0.44,
+ ),
+ SimpleNamespace(
+ uri="viking://agent/skills/deploy/.overview.md",
+ abstract="How the deploy skill works",
+ score=0.71,
+ ),
+ ]
+
+ async def fake_search(**kwargs):
+ return SimpleNamespace(memories=[], resources=[], skills=hits)
+
+ monkeypatch.setattr(service.search, "search", fake_search)
+
+ result = await search(query="roll back", context_type="skill")
+
+ assert "Found 1 item(s)" in result
+ assert "- [skill 71%] viking://agent/skills/deploy/SKILL.md" in result
+
+
async def test_find_tool_inlines_visible_content_when_requested(service, monkeypatch):
async def fake_find(**kwargs):
del kwargs
@@ -1030,6 +1343,152 @@ async def test_store_skips_empty_message_content(service, monkeypatch):
service.sessions.commit_async.assert_awaited_once()
+# ---------------------------------------------------------------------------
+# add_skill tool
+# ---------------------------------------------------------------------------
+
+
+def _skill_md(name: str, description: str = "Review a PR diff before approving") -> str:
+ return f"---\nname: {name}\ndescription: {description}\n---\n\n# {name}\n\nSteps.\n"
+
+
+async def test_add_skill_inline_data_installs_into_user_skills(service):
+ ctx = RequestContext(DEFAULT_CTX.user, Role.USER)
+ token = _mcp_ctx.set(ctx)
+ try:
+ result = await add_skill(data=_skill_md("mcp-inline-skill"))
+ finally:
+ _mcp_ctx.reset(token)
+
+ assert "Skill added: viking://user/test_user/skills/mcp-inline-skill" in result
+ body = await service.fs.read(
+ "viking://user/test_user/skills/mcp-inline-skill/SKILL.md", ctx=ctx
+ )
+ assert "# mcp-inline-skill" in body
+
+
+async def test_add_skill_forwards_git_source_to_shared_installer(monkeypatch):
+ captured = {}
+
+ async def fake_install_skills(data, ctx, **kwargs):
+ captured.update(kwargs, data=data)
+ return {
+ "skills": [{"name": "pdf", "description": "Fill PDF\nforms", "path": "pdf"}],
+ "total": 1,
+ }
+
+ monkeypatch.setattr(mcp_endpoint, "install_skills", fake_install_skills)
+
+ result = await add_skill(
+ path="https://github.com/org/skills",
+ skills=["pdf"],
+ target_uri="viking://agent/skills",
+ list_only=True,
+ )
+
+ assert captured["data"] == "https://github.com/org/skills"
+ assert captured["names"] == ["pdf"]
+ assert captured["list_only"] is True
+ assert captured["target_uri"] == "viking://agent/skills"
+ assert captured["source_metadata"] is None
+ assert "nothing was installed" in result
+ assert "- pdf (pdf): Fill PDF forms" in result
+
+
+async def test_add_skill_reports_every_installed_skill(monkeypatch):
+ async def fake_install_skills(data, ctx, **kwargs):
+ return {
+ "installed": [
+ {"root_uri": "viking://user/test_user/skills/a"},
+ {"root_uri": "viking://user/test_user/skills/b"},
+ ],
+ "total": 2,
+ }
+
+ monkeypatch.setattr(mcp_endpoint, "install_skills", fake_install_skills)
+
+ result = await add_skill(path="https://github.com/org/skills")
+
+ assert "Skill added: viking://user/test_user/skills/a" in result
+ assert "Skill added: viking://user/test_user/skills/b" in result
+
+
+async def test_add_skill_local_path_issues_skill_upload_token(service):
+ from openviking.server.upload_token_store import upload_token_store
+
+ upload_token_store.clear()
+ result = await add_skill(
+ path="/tmp/skills/pdf",
+ skills=["pdf"],
+ target_uri="viking://agent/skills",
+ )
+
+ assert "local skill detected" in result.lower()
+ assert "zip -r" in result
+ match = re.search(r"/api/v1/resources/temp_upload\?token=([A-Za-z0-9]+)", result)
+ assert match
+ info = upload_token_store.peek(match.group(1))
+ assert info.kind == "skill"
+ assert info.skill_target_uri == "viking://agent/skills"
+ assert info.skill_names == ["pdf"]
+ upload_token_store.clear()
+
+
+async def test_add_skill_rejects_a_target_below_a_skill_root_before_minting_a_token(service):
+ from openviking.server.upload_token_store import upload_token_store
+
+ upload_token_store.clear()
+ token = _mcp_ctx.set(RequestContext(DEFAULT_CTX.user, Role.USER))
+ try:
+ result = await add_skill(path="/tmp/skills/pdf", target_uri="viking://~/skills/pdf")
+ finally:
+ _mcp_ctx.reset(token)
+
+ assert result.startswith("Error: Unsupported skill root URI")
+ assert "viking://agent/skills" in result
+ assert upload_token_store._store == {}
+
+
+async def test_add_skill_maps_a_shared_subpath_to_the_shared_root(service):
+ from openviking.server.upload_token_store import upload_token_store
+
+ upload_token_store.clear()
+ result = await add_skill(path="/tmp/skills/pdf", target_uri="viking://agent/skills/pdf")
+
+ token = re.search(r"temp_upload\?token=([A-Za-z0-9]+)", result).group(1)
+ assert upload_token_store.peek(token).skill_target_uri == "viking://agent/skills"
+ upload_token_store.clear()
+
+
+async def test_add_skill_list_only_upload_says_nothing_is_installed(service):
+ from openviking.server.upload_token_store import upload_token_store
+
+ upload_token_store.clear()
+ result = await add_skill(path="/tmp/skills", list_only=True)
+
+ assert "upload it to list the skills it contains" in result
+ assert "installs nothing" in result
+ assert "do NOT need to call add_skill" not in result
+ upload_token_store.clear()
+
+
+ ("kwargs", "expected"),
+ [
+ ({"path": "tos://bucket/skills/pdf"}, "unsupported skill source"),
+ ({}, "provide 'data'"),
+ ({"data": _skill_md("x"), "path": "/tmp/x"}, "not both"),
+ ({"data": "/tmp/skills/pdf/SKILL.md"}, 'add_skill(path="/tmp/skills/pdf/SKILL.md")'),
+ ({"path": "viking://agent/skills/pdf"}, "read its SKILL.md"),
+ ({"data": _skill_md("x"), "target_uri": "viking://resources/x"}, "Error:"),
+ ],
+)
+async def test_add_skill_rejects_invalid_arguments(kwargs, expected):
+ result = await add_skill(**kwargs)
+ assert result.startswith("Error:")
+ assert expected in result
+
+
# ---------------------------------------------------------------------------
# add_resource tool
# ---------------------------------------------------------------------------
@@ -1896,6 +2355,62 @@ async def test_tree_node_limit_adds_truncation_note(service):
assert "(truncated at node_limit=1" in result
+async def test_tree_include_abstract_renders_directory_abstracts(service, monkeypatch):
+ captured = {}
+
+ async def fake_tree(uri, **kwargs):
+ captured.update(kwargs)
+ return [
+ {
+ "rel_path": "pr-review",
+ "isDir": True,
+ "abstract": "name: pr-review\ndescription: Review a PR diff",
+ },
+ {"rel_path": "pr-review/SKILL.md", "isDir": False, "size": 42, "abstract": ""},
+ ]
+
+ monkeypatch.setattr(service.fs, "tree", fake_tree)
+
+ result = await tree(uri="viking://user/test_user/skills", include_abstract=True)
+
+ assert "\npr-review/\n - name: pr-review description: Review a PR diff\n" in result
+ assert "\n SKILL.md (42 B)" in result
+ assert captured["output"] == "agent"
+ assert captured["abs_limit"] == 1024
+
+
+async def test_tree_include_abstract_skips_not_ready_placeholders(service, monkeypatch):
+ async def fake_tree(uri, **kwargs):
+ return [
+ {
+ "rel_path": "pdf",
+ "uri": "viking://user/test_user/skills/pdf",
+ "isDir": True,
+ "abstract": "name: pdf\ndescription: Fill PDF forms",
+ },
+ {
+ "rel_path": "pdf/scripts",
+ "uri": "viking://user/test_user/skills/pdf/scripts",
+ "isDir": True,
+ "abstract": "# viking://user/test_user/skills/pdf/scripts [Directory abstract is not ready]",
+ },
+ {
+ "rel_path": "pdf/references",
+ "uri": "viking://user/test_user/skills/pdf/references",
+ "isDir": True,
+ "abstract": "[.abstract.md is not ready]",
+ },
+ ]
+
+ monkeypatch.setattr(service.fs, "tree", fake_tree)
+
+ result = await tree(uri="viking://user/test_user/skills", include_abstract=True)
+
+ assert " - name: pdf description: Fill PDF forms" in result
+ assert "not ready" not in result
+ assert "\n scripts/\n references/" in result
+
+
async def test_tree_include_abstract_still_renders(service):
await write(uri="viking://resources/test_tree_abs/note.md", content="hello tree\n")
diff --git a/tests/server/test_resources_temp_upload_token.py b/tests/server/test_resources_temp_upload_token.py
index 96fb3e8fd..794ca7f8f 100644
--- a/tests/server/test_resources_temp_upload_token.py
+++ b/tests/server/test_resources_temp_upload_token.py
@@ -10,6 +10,8 @@ POST keeps the legacy behavior of just storing the file and returning its ``temp
from __future__ import annotations
+import io
+import zipfile
from pathlib import Path
import httpx
@@ -244,3 +246,54 @@ async def test_apikey_temp_upload_returns_temp_file_id(
assert resp.status_code == 200, resp.text
tfid = resp.json()["result"]["temp_file_id"]
assert (upload_temp_dir / tfid).is_file()
+
+
+def _skill_zip(name: str) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as zf:
+ zf.writestr(
+ f"{name}/SKILL.md",
+ f"---\nname: {name}\ndescription: Zipped skill for upload tests\n---\n\n# {name}\n",
+ )
+ zf.writestr(f"{name}/scripts/run.sh", "#!/bin/sh\necho ok\n")
+ return buffer.getvalue()
+
+
+async def test_skill_token_upload_installs_zipped_skill_directory(
+ client: httpx.AsyncClient, service, upload_temp_dir: Path
+):
+ token, _ = upload_token_store.issue("acct", "user", ttl_seconds=600, kind="skill")
+ resp = await client.post(
+ "/api/v1/resources/temp_upload",
+ params={"token": token},
+ files={"file": ("zip-skill.zip", _skill_zip("zip-skill"), "application/zip")},
+ )
+ assert resp.status_code == 200, resp.text
+ result = resp.json()["result"]
+ assert result["root_uri"].endswith("/skills/zip-skill")
+ assert result["auxiliary_files"] == 1
+
+
+async def test_skill_token_upload_list_only_does_not_install(
+ client: httpx.AsyncClient, service, upload_temp_dir: Path, monkeypatch
+):
+ async def fail_add_skill(**_kwargs):
+ raise AssertionError("list_only must not install")
+
+ monkeypatch.setattr(service.resources, "add_skill", fail_add_skill)
+ token, _ = upload_token_store.issue(
+ "acct", "user", ttl_seconds=600, kind="skill", list_only=True
+ )
+ resp = await client.post(
+ "/api/v1/resources/temp_upload",
+ params={"token": token},
+ files={"file": ("zip-skill.zip", _skill_zip("zip-skill"), "application/zip")},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["result"]["skills"] == [
+ {
+ "name": "zip-skill",
+ "description": "Zipped skill for upload tests",
+ "path": "zip-skill",
+ }
+ ]
diff --git a/tests/server/test_upload_token_store.py b/tests/server/test_upload_token_store.py
index e28a2375c..168e9644a 100644
--- a/tests/server/test_upload_token_store.py
+++ b/tests/server/test_upload_token_store.py
@@ -40,6 +40,36 @@ def test_consume_roundtrip(store):
assert consumed.parse_mode == "default"
+def test_consume_defaults_to_resource_kind(store):
+ token, _ = store.issue("acct", "user", ttl_seconds=60)
+ consumed = store.consume(token)
+ assert consumed.kind == "resource"
+ assert (consumed.skill_target_uri, consumed.skill_names, consumed.list_only) == (
+ "",
+ None,
+ False,
+ )
+
+
+def test_consume_returns_skill_install_params(store):
+ token, _ = store.issue(
+ "acct",
+ "user",
+ ttl_seconds=60,
+ actor_peer_id="bot-a",
+ kind="skill",
+ skill_target_uri="viking://agent/skills",
+ skill_names=["pdf", "xlsx"],
+ list_only=True,
+ )
+ consumed = store.consume(token)
+ assert consumed.kind == "skill"
+ assert consumed.skill_target_uri == "viking://agent/skills"
+ assert consumed.skill_names == ["pdf", "xlsx"]
+ assert consumed.list_only is True
+ assert consumed.actor_peer_id == "bot-a"
+
+
def test_consume_returns_bound_business_params(store):
token, _ = store.issue(
"acct",