Skip to main content
Glama
README.md
# nano-viking

> **Zero-dependency, ~600-line Python reproduction of [OpenViking](https://github.com/volcengine/OpenViking)'s `viking://` L0 / L1 / L2 tiered context filesystem — powered by SQLite FTS5 BM25 retrieval and a built-in stdio MCP Server.**
>
> **零外部依赖、约 600 行纯 Python 极简复刻字节火山开源热榜项目 [OpenViking](https://github.com/volcengine/OpenViking) 核心机制:`viking://` 三层渐进式上下文文件系统(L0 摘要 / L1 结构蓝图 / L2 按需源码切片)+ SQLite FTS5 混合检索 + 开箱即用的 MCP 服务与 Claude Code Skill。**

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
[![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-3776AB.svg)](./pyproject.toml)
[![Zero Dependencies](https://img.shields.io/badge/Dependencies-Zero-success.svg)](./pyproject.toml)
[![MCP Compatible](https://img.shields.io/badge/MCP-stdio%20JSON--RPC%202.0-8A2BE2.svg)](./src/nano_viking/mcp_server.py)

---

## Why `nano-viking`? / 为什么需要它?

Traditional RAG pipelines flatten source code into blind vector chunks, while naive Coding Agents dump entire files into the prompt—burning **20k–100k tokens per turn**.

**OpenViking** introduced a cleaner mental model: treat agent context (**codebase resources, long-term memories, and reusable skills**) as a unified **`viking://` virtual filesystem** with **3 progressive disclosure tiers (L0 → L1 → L2)**.

Full OpenViking deployments involve multi-language backends and external embedding services. **`nano-viking` distills the core paradigm into pure Python standard library (`ast` + `sqlite3` FTS5 BM25)** so you can study, hack, or plug it into Claude Code / Cursor / Codex in **10 seconds with zero API keys and zero `pip` dependency bloat**.

传统 Agent 要么粗暴塞入整份源码瞬间撑爆上下文窗口,要么用切片向量检索丢失代码目录与符号层级结构。`nano-viking` 用纯 Python 标准库完整复刻了 `viking://` 渐进式上下文加载范式,**无需配置任何向量数据库或付费 Embedding Key,实测单轮探索可节省 85%–93% 的 Prompt Token**。

---

## Architecture / 核心分层架构

```mermaid
flowchart LR
    Agent["Coding Agent / CLI / MCP Client"] --> URI["viking:// Router"]
    URI --> NS1["viking://resources/*<br/>(Workspace Code & Docs)"]
    URI --> NS2["viking://memories/*<br/>(Cross-Session Decisions)"]
    URI --> NS3["viking://skills/*<br/>(Reusable Agent Skills)"]

    NS1 & NS2 & NS3 --> Store[("SQLite WAL + FTS5 BM25<br/>.viking/context.db")]

    Store --> L0["L0 Abstract (~60 tok)<br/>Fast tree scan & BM25 filter"]
    L0 --> L1["L1 Overview (~200-500 tok)<br/>AST classes, signatures & line spans"]
    L1 --> L2["L2 Detail Slice (On-Demand)<br/>#Lstart-Lend exact source lines"]
```

| Tier | Layer Name | Typical Budget | How `nano-viking` Compiles It | Agent Usage |
| :--- | :--- | :--- | :--- | :--- |
| **L0** | **Abstract** | `~256 chars` (~60 tok) | Module docstring lead + top exported symbols + directory rollups | `ls`, `tree`, `search --tier L0` |
| **L1** | **Overview** | `~2,000–4,000 chars` | Python `ast` classes/methods/type signatures with `[#Lstart-Lend]` spans; TS/Go/Rust declarations; Markdown outlines; JSON schemas | Confirm structure & exact line ranges before reading raw code |
| **L2** | **Detail** | On-demand slice | Exact raw text or line-sliced window (`viking://resources/a.py#L40-L85`) | Surgical implementation read |

---

## Benchmark (Real Output) / 真实 Token 压缩实测

Running `nano-viking benchmark .` on its own repository:

```text
$ nano-viking benchmark .
=== nano-viking Tiered Context Benchmark (nano-viking) ===
Indexed files         : 13

| Context Layer / Strategy            | Est. Tokens | vs Raw L2 |
| :---------------------------------- | ----------: | --------: |
| Raw Full-Repo Dump (L2 Detail)      |       20140 |     0.0%  |
| Full-Repo Structural Map (L1)       |        2890 |   -85.6%  |
| Full-Repo Abstract Index (L0)       |         498 |   -97.5%  |
| Agent Progressive Flow (L0->L1->L2) |        1184 |   -94.1%  |

Result: Progressive `viking://` navigation saved 18956 tokens (94.1% reduction vs raw file dumping).
```

Inspecting a 650-line module at **Tier L1** costs **434 tokens instead of 6,188 tokens (-93.0%)**, while preserving every class, method signature, type annotation, and line number span:

```text
$ nano-viking read viking://resources/src/nano_viking/store.py --tier L1
--- viking://resources/src/nano_viking/store.py [Tier L1 | 434 tok vs 6188 L2 tok | -93.0%] ---
# src/nano_viking/store.py (Python Module, 657 lines)

## Module Docstring
SQLite + FTS5 BM25 backing store for the `viking://` tiered context filesystem.

## Classes & Methods
- class VikingNode [#L69-L83]
- class SearchHit [#L87-L95]
- class VikingStore [#L98-L657] — Persistent local context store supporting L0/L1/L2 progressive reads and FTS5 search.
  - def index_directory(self, workspace_dir: str | Path, namespace: str, prefix: str) -> dict[str, int]  [#L304-L408]
  - def remember(self, key_path: str, content: str, abstract: str, namespace: str) -> VikingNode  [#L410-L450]
  - def read(self, raw_uri: str, tier: str, record_telemetry: bool) -> dict[str, object]  [#L499-L549]
  - def search(self, query: str, namespace: str | None, tier: str, limit: int) -> list[SearchHit]  [#L551-L607]
```

---

## 30-Second Quickstart / 快速上手

Requires **Python 3.10+** only (zero third-party packages).

```bash
git clone https://github.com/nanyun818/nano-viking.git
cd nano-viking
pip install -e .
```

### 1. Index & Explore a Codebase (`viking://resources`)

```bash
# Incrementally index current repository (SHA-256 cached; re-runs take <20ms)
nano-viking index .

# View hierarchical token map
nano-viking tree viking://resources

# Search across codebase & memories using SQLite FTS5 BM25 (returns compact L0 hits)
nano-viking search "VikingStore FTS5" --tier L0

# Read structural overview (L1) first, then surgical line range (L2)
nano-viking read viking://resources/src/nano_viking/store.py --tier L1
nano-viking read "viking://resources/src/nano_viking/store.py#L98-L145" --tier L2
```

### 2. Persist Cross-Session Agent Memories (`viking://memories`)

```bash
nano-viking remember decisions/storage-engine \
  "Use SQLite WAL + FTS5 unicode61 tokenizer so agents run offline without external vector DBs." \
  --abstract "Offline SQLite WAL + FTS5 storage decision"

nano-viking ls viking://memories/decisions
```

### 3. Check Session Token Telemetry

```bash
nano-viking stats
```

---

## Plug into Claude Code / Cursor / Codex via MCP

`nano-viking` ships with a built-in zero-dependency **Model Context Protocol (MCP)** server (`stdio`, supporting both JSON-lines and `Content-Length` framing).

Add to your `.mcp.json` or `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "nano-viking": {
      "command": "nano-viking",
      "args": ["mcp", "--workspace", "."]
    }
  }
}
```

Exposed MCP Tools:
- `viking_index` — Incrementally index or refresh workspace files
- `viking_tree` — Inspect directory hierarchy and L1/L2 token budgets
- `viking_ls` — List directory entries with L0 abstracts
- `viking_read` — Read any `viking://` URI at `L0`, `L1`, or `L2` (with `#Lstart-Lend` slicing)
- `viking_search` — Ranked BM25 search across `resources`, `memories`, and `skills`
- `viking_remember` — Write persistent cross-session memories or skill notes
- `viking_stats` — Query compression ratios and live session token savings

You can also copy [`SKILL.md`](./SKILL.md) into `.claude/skills/nano-viking/SKILL.md` to teach coding agents the `L0 -> L1 -> L2` progressive reading workflow automatically.

---

## Comparison & Credits / 致敬与对比

**Inspired by [volcengine/OpenViking](https://github.com/volcengine/OpenViking)** — huge credit to the OpenViking team for pioneering the `viking://` virtual context filesystem and L0/L1/L2 tiered context loading architecture.

| Dimension | `volcengine/OpenViking` | `nano-viking` (This Repo) |
| :--- | :--- | :--- |
| **Core Goal** | Production multi-tenant enterprise context database | Minimalist educational & local-first CLI/MCP reproduction |
| **Dependencies** | Multi-service stack + Vector DB + Embedding APIs | **0 external dependencies** (Python 3.10+ stdlib only) |
| **L0 / L1 Generation** | LLM semantic summarization sidecars | Deterministic zero-cost `ast` + outline compiler |
| **Retrieval Engine** | Dense embeddings + AGFS/RAGFS | Local **SQLite WAL + FTS5 BM25** (`<20ms` incremental) |
| **Code Footprint** | Large full-featured codebase | **~600 LOC** readable in 15 minutes |

---

## Running Tests / 运行测试

```bash
python -m unittest discover -s tests -v
```

## License

[MIT](./LICENSE) © nanyun818