Content
# 🧠 MCP Smart Long Context — Wiki-Obsidian
<div align="center">
<p><strong>Persistent, structured long-term memory for multi-agent AI workflows — powered by an Obsidian-compatible wiki vault.</strong></p>
<p>
<a href="https://www.npmjs.com/package/mcp-smart-long-context-wiki-obsidian"><img src="https://img.shields.io/npm/v/mcp-smart-long-context-wiki-obsidian.svg?color=green" alt="NPM Version"></a>
<img src="https://img.shields.io/badge/Node.js-%3E%3D20.0-blue.svg" alt="Node.js 20+">
<img src="https://img.shields.io/badge/MCP-SDK%201.0-orange.svg" alt="MCP SDK 1.0">
<img src="https://img.shields.io/badge/License-MIT-purple.svg" alt="License MIT">
<img src="https://img.shields.io/badge/Obsidian-Compatible-violet.svg" alt="Obsidian Compatible">
</p>
</div>
---
## Table of Contents
1. [The Problem](#-the-problem)
2. [The Solution](#-the-solution)
3. [What Makes This MCP Different](#-what-makes-this-mcp-different)
4. [How It Works — From Prompt to Knowledge](#-how-it-works--from-prompt-to-knowledge)
5. [Knowledge Trust Hierarchy](#-knowledge-trust-hierarchy--t1-wiki-first)
6. [Wiki Agent Operational Protocol](#-wiki-agent-operational-protocol)
7. [Quick Start](#-quick-start)
8. [Commands Reference](#-commands-reference)
9. [System Architecture](#-system-architecture)
10. [CI/CD Integration](#-cicd-integration)
11. [Environment Variables](#-environment-variables)
---
## 🔴 The Problem
Every AI agent — Claude, Cursor, Gemini, GPT — operates under a fundamental constraint: **total memory erasure at session boundaries**.
| Memory Loss Scenario | Impact |
|---|---|
| Context window filled (~100K–200K tokens) | Agent forgets early conversation, loses architectural decisions |
| IDE restart / session timeout | All working context gone; agent starts from zero |
| Multi-agent handoff (Code Agent → Wiki Agent) | No shared state; each agent is isolated |
| Long-running projects (days/weeks) | No cross-session continuity; patterns re-discovered repeatedly |
Existing "solutions" address symptoms, not the root cause:
| Approach | Critical Shortcomings |
|---|---|
| **RAG (Chroma, Pinecone, Weaviate)** | Infrastructure overhead, 50–500ms latency, not human-readable, embedding drift |
| **mem0, Zep, Letta** | External SaaS dependency, cost at scale, privacy concerns with proprietary data |
| **`.cursorrules` / system prompts** | Static — cannot evolve with the codebase; no multi-agent support; not versioned |
| **Paste code into context** | Linear token waste; scales poorly; agents cannot distinguish signal from noise |
| **Conversation history exports** | Unstructured; full re-read required; no semantic indexing |
---
## 💡 The Solution
**MCP Smart Long Context** provides a **structured, stateless, zero-infrastructure knowledge persistence layer** for AI agents.
Knowledge is stored as Obsidian-compatible Markdown files inside a `.brain_wiki/` directory within your project. Agents read from and write to this vault using a single, unified slash-command interface exposed as an MCP tool.
> **Core Insight:** Wiki articles operate like Claude's internal "Skills" system. They inject **structured procedural context** into agent reasoning as *context priming* — helping the agent know *what patterns this project uses* **before** it writes a single line of code.
This is fundamentally different from RAG. RAG helps an agent *discover unknown documents*. This system helps an agent *access deliberately curated, project-specific knowledge* in under 5ms, with zero external dependencies.
---
## ✨ What Makes This MCP Different
### 1. T1 Trust-Ranked Knowledge Source
This MCP establishes a **tiered knowledge trust hierarchy** for AI reasoning chains. Wiki content is treated as the highest-confidence (`T1`) source — taking precedence over web search, code comments, or inferred context:
```
T1 — .brain_wiki/ → Curated, project-specific, human-verified knowledge
T2 — Web search → General knowledge, may be outdated or generic
T3 — LLM inference → Trained priors, may hallucinate
T4 — Code scanning → Syntactically correct but semantically unaware
```
**The agent reads the wiki first. Always.** It supplements reasoning with T2+ sources only when T1 is insufficient — never the other way around.
### 2. Directory-Tree Navigation Protocol
Every interaction with `.brain_wiki/` is **mediated through `Directory-tree.md`** — a structured navigation index that is automatically regenerated after every write operation.
`Directory-tree.md` contains, for each article:
- `title` and `id` (unique slug)
- `purpose` — a single sentence describing what the article stores
- `tags` — canonical taxonomy labels (normalized via `taxonomy.yml`)
- `depends_on` — links to prerequisite articles (Obsidian-style graph)
- `"Read when:"` — explicit natural-language hints guiding the agent when to load the file
This ensures agents **never blindly load the entire vault**. They navigate the tree, identify relevant articles by `purpose` and `"Read when:"` hints, and load only what is necessary.
### 3. Obsidian-Compatible Graph Structure
Articles use YAML frontmatter (`id`, `title`, `purpose`, `tags`, `depends_on`) that renders as a **visual knowledge graph** in Obsidian. Your project's `.brain_wiki/` is simultaneously:
- A live knowledge base consumed by AI agents at runtime
- A human-readable documentation layer editable in any Markdown editor
- A Git-trackable, reviewable, diff-able knowledge graph
### 4. Zero-Vector, Sub-5ms Retrieval
Unlike RAG systems, this MCP performs no embedding computation. Retrieval uses:
- **Trigram + word overlap scoring** — handles typos, abbreviations, partial matches
- **Vietnamese diacritic normalization** — `xác thực` ≈ `xac thuc` ≈ `auth`
- **Tag taxonomy normalization** — `authn` → `auth`, `stripe` → `payment`
- **Content preview indexing** — searches first 500 chars of article body
For wikis under 1,000 articles (typical project scale), linear n-gram scans complete in **<5ms** — outperforming embedding-based retrieval with no infrastructure cost.
### 5. Stateless Command-Driven Architecture
The server maintains **zero background state**. No file watchers, no timers, no auto-triggers. Every action is initiated explicitly by the agent via slash command.
> **"Smart behavior comes from the agent's reasoning, not from the server guessing what to do."**
The server provides deterministic tools. The agent, guided by `Claude.md` protocol, decides when and what to load, write, or update.
### 6. POSIX-Atomic Write Guarantees
All article writes use the `tmp → rename` pattern — a POSIX-atomic operation that guarantees readers see either the complete old file or the complete new file, **never a truncated or corrupted intermediate state**.
### 7. Git-Native Staleness Detection
The `/wiki sync` command compares article `updated_at` timestamps against `git log --since` for referenced source files. Articles that describe code changed after the wiki was last written are **flagged as stale** — preventing agents from reasoning on outdated architectural context.
---
## 🔄 How It Works — From Prompt to Knowledge
```
User Prompt
│
▼
┌─────────────────────────────────────────────────────────┐
│ AI Agent Session │
│ │
│ 1. cmd({ input: "/wiki read-map" }) │
│ ↓ Reads Directory-tree.md │
│ ↓ Identifies relevant articles by purpose/tags │
│ │
│ 2. cmd({ input: "/wiki read <article-id>" }) │
│ ↓ Loads curated knowledge into context (T1) │
│ ↓ Supplements reasoning — does NOT override it │
│ │
│ 3. [Agent executes task using T1 context] │
│ ↓ Code written with project-specific patterns │
│ ↓ Architectural decisions respected │
│ │
│ 4. cmd({ input: '/wiki emit --diff "..."' }) │
│ ↓ Reports completion to wiki queue │
│ │
│ 5. cmd({ input: '/wiki write "Title" "Content..."' }) │
│ ↓ Writes new knowledge to .brain_wiki/ │
│ ↓ Directory-tree.md auto-regenerated │
└─────────────────────────────────────────────────────────┘
│
▼
Persistent Knowledge in .brain_wiki/ (cross-session)
```
**Key behavioral constraint:** Wiki content is consumed as **supplementary context** — it enriches the agent's reasoning without overriding its inference capability. The agent remains the reasoning engine; the wiki provides the domain-specific grounding.
---
## 📊 Knowledge Trust Hierarchy — T1 Wiki-First
When an agent receives a prompt, it consults knowledge sources in strict priority order:
```
Priority 1 (T1) ─── .brain_wiki/ articles
└── Consulted via /wiki read-map → /wiki read
└── Trusted as project ground truth
└── Loaded BEFORE any other research
Priority 2 (T2) ─── Web search / documentation lookup
└── Used only when T1 has no coverage
└── Results cross-referenced against T1
Priority 3 (T3) ─── LLM trained priors / inference
└── Fallback when T1+T2 insufficient
└── Explicitly flagged as "inferred, not verified"
Priority 4 (T4) ─── Real-time code scanning
└── Used for implementation-level detail
└── T1 provides architectural intent; T4 provides code reality
```
**The wiki does not replace the agent's reasoning.** It provides curated, versioned project intelligence that makes the agent's reasoning more accurate and aligned with the project's actual technical decisions.
---
## 📜 Wiki Agent Operational Protocol
Agents using this MCP MUST follow the protocol defined in `Claude.md`. Critical rules:
### Rule W-1: Always Read the Map First
```typescript
cmd({ input: "/wiki read-map" })
// → Loads Directory-tree.md
// → Identifies existing articles by purpose + tags
// → Decision: create new article OR append to existing
```
### Rule W-2: Create vs. Append Decision
| Condition | Action |
|---|---|
| Concept has no existing coverage | `/wiki write "New Title" "..." --purpose "..." --tags t1,t2` |
| Content extends an existing article | `/wiki write "Existing Title" "..." --append` |
| Content is too small for standalone article | Append to most semantically relevant article |
### Rule W-3: Mandatory YAML Frontmatter
Every new article MUST include:
- `--purpose` — one sentence: what knowledge this article stores
- `--tags` — at least one canonical taxonomy tag
- `--depends-on` — IDs of prerequisite articles (if applicable)
### Rule W-4: Only Write Durable Knowledge
Write to `.brain_wiki/` ONLY for:
- ✅ Completed architectural decisions
- ✅ Implemented technical patterns and conventions
- ✅ Resolved integration issues with proven solutions
- ✅ Performance optimization techniques validated in production
**Never write:**
- ❌ Technical debt notes or known bugs (prevents future hallucinations)
- ❌ WIP/in-progress context (creates stale, misleading articles)
- ❌ API keys, secrets, credentials in any form
- ❌ Scratch notes or temporary task context
---
## 🚀 Quick Start
### 1. Install & Initialize
```bash
npx mcp-smart-long-context-wiki-obsidian init
```
Initializes `.brain_wiki/` vault, `taxonomy.yml` tag configuration, and optional Git hooks.
### 2. Start the MCP Server
```bash
npx mcp-smart-long-context-wiki-obsidian
```
### 3. Configure Your AI Client
**Claude Desktop** (`~/Library/Application Support/Claude/claude_desktop_config.json`):
```json
{
"mcpServers": {
"mcp-smart-long-context": {
"command": "npx",
"args": ["-y", "mcp-smart-long-context-wiki-obsidian"],
"env": {
"MCP_WIKI_ROOT": "/absolute/path/to/your/project",
"MCP_WIKI_LANGUAGE": "auto"
}
}
}
}
```
**Cursor** (`.cursor/mcp.json`):
```json
{
"mcpServers": {
"mcp-smart-long-context": {
"command": "npx",
"args": ["-y", "mcp-smart-long-context-wiki-obsidian"],
"env": {
"MCP_WIKI_ROOT": "${workspaceFolder}",
"MCP_WIKI_LANGUAGE": "auto"
}
}
}
}
```
**Windsurf** (`.windsurf/mcp.json`):
```json
{
"mcpServers": {
"mcp-smart-long-context": {
"command": "npx",
"args": ["-y", "mcp-smart-long-context-wiki-obsidian"],
"env": {
"MCP_WIKI_ROOT": "${workspaceFolder}",
"MCP_WIKI_LANGUAGE": "auto"
}
}
}
}
```
**Gemini CLI** (`.gemini/settings.json`):
```json
{
"mcpServers": {
"mcp-smart-long-context": {
"command": "npx",
"args": ["-y", "mcp-smart-long-context-wiki-obsidian"],
"env": {
"MCP_WIKI_ROOT": "${workspaceFolder}",
"MCP_WIKI_LANGUAGE": "auto"
}
}
}
}
```
*(See [`configs/`](./configs/) directory for additional IDE templates.)*
### 4. Open Wiki in Obsidian (Optional)
Point Obsidian's vault to your project root. The `.brain_wiki/` directory renders as a visual knowledge graph with full `depends_on` link resolution.
---
## 💻 Commands Reference
All interactions use the single `cmd` MCP tool with slash syntax.
### Core Knowledge Operations
| Command | Description |
|---|---|
| `/wiki write "<title>" "<content>" --purpose "..." --tags t1,t2` | Create or overwrite an article with full metadata |
| `/wiki write "<title>" "<content>" --append` | Append content to an existing article |
| `/wiki write ... --force` | Override min-content/language policy checks intentionally |
| `/wiki read <id-or-title>` | Load a complete article into context |
| `/wiki search <query>` | Fuzzy search across titles, tags, purpose, and body preview |
| `/wiki list` | List all articles with title, tags, and purpose |
### Navigation & Discovery
| Command | Description |
|---|---|
| `/wiki read-map` | Load `Directory-tree.md` — the canonical navigation index |
| `/wiki suggest "<task-description>"` | Get top-5 most relevant articles for an upcoming task |
### Multi-Agent Coordination
| Command | Description |
|---|---|
| `/wiki emit --diff "<description>" --agent <id>` | Code Agent reports task completion to wiki queue |
| `/wiki status` | View pending queue and session context usage |
### Governance & Maintenance
| Command | Description |
|---|---|
| `/wiki sync` | Detect articles that have fallen behind code changes via `git log` |
| `/wiki report` | Health metrics: orphan articles, staleness scores, read frequency |
| `/wiki delete <id-or-title>` | Soft-delete an article (preserves history in Git) |
| `/health` | Server uptime, RAM usage, and subsystem status |
---
## 🛠️ System Architecture
### Core Design Principles
**1. File-per-Article (Not a Database)**
Each article is one `.md` file in `.brain_wiki/`. No JSON database, no SQLite, no binary formats. This means:
- Fully human-readable and editable in any text editor
- Meaningful Git diffs per article for PR review
- Native Obsidian graph visualization via `depends_on` links
- No schema migrations ever required
**2. No Vector Embeddings (By Design)**
The wiki stores *intentional, curated knowledge* — not a noisy full-codebase corpus. With 50–500 articles (typical project), deterministic trigram scoring is:
- **Faster** (<5ms vs. 50–500ms for embedding APIs)
- **More predictable** (no semantic drift, no model dependency)
- **Zero infrastructure** (no embedding server, no vector DB)
If the wiki grows beyond 1,000 articles, an optional embedding layer can be activated via `MCP_ENABLE_EMBEDDING=true` — explicitly reserved for v2.
**3. Single Slash-Command Router**
One `cmd` MCP tool handles all operations via slash syntax. This prevents "tool explosion" — a known failure mode where agents get confused selecting among dozens of specialized tools.
**4. Stateless, On-Demand Execution**
Zero background processes. The server only computes when explicitly called. Post-commit Git hooks write to `.context/pending-sync.txt`, consumed synchronously on the next `/wiki read-map` call — providing async event bridging without background timers.
**5. POSIX-Atomic Writes**
`writeFileSync(tmp) → renameSync(tmp, final)` guarantees crash safety. Readers see complete files or nothing — never partial writes.
For a complete decision log, see the [Architecture Decision Record](./ARCHITECTURE.md).
---
## 🚦 CI/CD Integration
Lint the wiki in GitHub Actions to prevent knowledge decay:
```yaml
- name: Lint Wiki
run: MCP_WIKI_ROOT=. npx mcp-smart-long-context-wiki-obsidian --wiki-lint
```
Exits non-zero on:
- Articles missing `purpose` frontmatter field
- Circular `depends_on` dependency graphs
- Tags not defined in `taxonomy.yml`
- Orphan articles with no inbound references
---
## ⚙️ Environment Variables
| Variable | Default | Description |
|---|---|---|
| `MCP_WIKI_ROOT` | `process.cwd()` | Absolute path to the directory containing `.brain_wiki/` |
| `MCP_WIKI_LANGUAGE` | `auto` | Enforce wiki write language: `auto \| vi \| en` |
| `MCP_LOG_LEVEL` | `info` | Log verbosity: `debug \| info \| warn \| error` |
| `MCP_DISABLE_INSTANCE_LOCK` | `false` | Allow concurrent instances for multi-agent swarm configurations |
| `MCP_TOKEN_BUDGET` | `100000` | Max token budget for `Directory-tree.md` read operations |
| `MCP_ENABLE_EMBEDDING` | `false` | *(v2)* Enable optional vector layer for wikis >1,000 articles |
---
## 📁 `.brain_wiki/` Vault Structure
```
.brain_wiki/
├── Directory-tree.md # Auto-generated navigation index (read-map)
├── taxonomy.yml # Canonical tag normalization rules
├── auth-jwt-refresh-flow.md # Example article: YAML frontmatter + MD body
├── payment-stripe-integration.md
└── ux-button-hover-animation.md
```
**Article format:**
```markdown
---
id: auth-jwt-refresh-flow-abc123
title: Auth JWT Refresh Flow
purpose: Documents the token refresh strategy and edge cases for the auth module
tags: [auth, jwt, security]
depends_on: [api-rate-limiting-xyz, user-session-management-def]
language: en
created: 2026-04-21T10:00:00Z
updated: 2026-04-21T10:00:00Z
---
## Token Refresh Strategy
[Article body...]
```
---
## License
MIT © [VoTrongHoang-Dyor](https://github.com/VoTrongHoang-Dyor)
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
markitdown
Python tool for converting files and office documents to Markdown.
Filesystem
Node.js MCP Server for filesystem operations with dynamic access control.
TrendRadar
TrendRadar: Your hotspot assistant for real news in just 30 seconds.
mempalace
The highest-scoring AI memory system ever benchmarked. And it's free.
mempalace
The highest-scoring AI memory system ever benchmarked. And it's free.