Kairn

io.github.primeline-aiPublished by GitHub account primeline-aiv0.3.2Updated Nov 7, 2026

Local-first knowledge engine for AI agents: memory, graph, and recall over MCP.

VerifiedSTDIODesktop onlyDatabasesKnowledge & Memory

Overview

AI-generated overview

Local-first knowledge engine that gives an AI assistant a persistent knowledge graph, decaying experience memory and context recall over MCP.

What you can do
  • Store and recall knowledge: learn facts with confidence routing, recall past knowledge, find similar past solutions, and load a relevant subgraph from keywords.
  • Manage the knowledge graph: add nodes, create typed edges, record relationship judgments, query by text, type, tags or namespace, traverse related nodes, and soft-delete.
  • Handle experience memory: save experiences with decay, capture user preferences, search decay-aware memories, prune expired ones, and promote frequently accessed ones to permanent nodes.
  • Track projects and ideas: create or update projects, switch the active project, log progress or failures, and create or list ideas.
  • Inspect health: read-only diagnostics and graph…
When to use it
Use it when you want an assistant to carry decisions, gotchas, patterns and preferences across sessions and projects without re-explaining them, and to retrieve the right context rather than a flat list of notes. It suits developers working in Claude Code, Codex, Cursor, VS Code or Claude Desktop who want memory kept entirely on their own machine.
Requirements
Runs as a local process: install the kairn-ai Python package, or use the one-click bundle, which resolves the same package through uv. A workspace directory holds the SQLite database; KAIRN_WORKSPACE sets where config is read from, and the serve command defaults to ~/.kairn. Optional semantic recall needs a local Ollama server with an embedding model. Team features need KAIRN_JWT_SECRET.
Before you install
The server writes to a local database: tools add, connect, promote and soft-delete nodes, and kn_prune deletes experiences below a recency threshold, so pruning is destructive. Import commands read local git history and Claude Code session transcripts; a secret redactor runs first, but review with --dry-run before a real import. Team features require KAIRN_JWT_SECRET, a secret to keep private. Pre-1.0, so interfaces may change between releases.

Installation

In SourceWeft

  1. Open Kairn in the dashboard and add it to a workspace.
  2. Enable the server for the chats that should use its tools.

Desktop only via STDIO. STDIO servers start a local process, so they need the SourceWeft desktop host.

Other MCP clients

Follow the launch instructions in the repository.

README

Kairn

[kairn]

Watch the 30-second tour on GitHub.

Context-aware knowledge engine for AI assistants.

Status: pre-1.0. In daily use since February 2026, with a test suite that runs on Linux, macOS and Windows (see Development) and a published LongMemEval-S benchmark (measured before 0.3.0). Interfaces may still change between releases until 1.0. Feedback and issues welcome.

Other tools give your AI a memory. Kairn gives it a knowledge graph with intelligent context routing. It knows what to load, when to load it, and how much - so your AI stays focused, not overwhelmed.

bash
pip install kairn-aikairn init ~/brainkairn serve ~/brain

Claude Code and Codex each take one line; --init creates ~/brain and its database on first start, so this works even without kairn init:

bash
claude mcp add kairn -- kairn serve --init ~/braincodex mcp add kairn -- kairn serve --init ~/brain

Or install it as a one-click bundle, no Python setup required: download the .mcpb file from the latest release and open it with a bundle-aware app such as Claude Desktop.

For other clients, see Quick Start below. New to Kairn? Jump to First 5 Minutes.

Install routes

RouteWho it is forCommand
PyPIanyone with Python, and every MCP clientpip install kairn-ai
MCP Bundle (.mcpb)Claude Desktop and other bundle-aware apps; no Python install neededdownload from Releases and open it
Claude Codeone line, uses the PyPI installclaude mcp add kairn -- kairn serve --init ~/brain
Codexone line, uses the PyPI installcodex mcp add kairn -- kairn serve --init ~/brain

The bundle carries no Kairn source of its own. It declares kairn-ai as a dependency and the host resolves it with uv, so a bundle install and a pip install run identical code. Where the database lives is configurable when you install the bundle; it defaults to ~/.kairn and never leaves your machine.

Why Kairn?

Every AI conversation starts from scratch. Previous insights, decisions, and patterns - gone. Existing memory tools store flat key-value pairs that can't represent relationships or surface the right context at the right time.

Kairn is different:

  • Context Router + Progressive Disclosure - Automatically loads relevant subgraphs based on keywords, starting with summaries and drilling into details only when needed. No other tool does this.
  • Knowledge Graph with FTS5 - Not flat storage. Typed relationships (depends-on, resolves, causes) between nodes with provenance tracking and full-text search across everything.
  • Experience Decay + Auto-Promotion - Experiences lose relevance over time (biological decay model). Frequently-accessed experiences auto-promote to permanent knowledge. Your AI naturally forgets what doesn't matter.
  • 22 MCP Tools - Works with Claude Code, Codex, Claude Desktop, Cursor, VS Code, Windsurf, and any MCP client. Includes kn_judge for 5-verb relationship judgments and kn_doctor for read-only health diagnostics.
  • Per-Workspace Isolation - Each workspace is its own isolated SQLite store. JWT auth and role-based access control (owner / maintainer / contributor / reader) ship for team deployments.

Quick Start

Claude Desktop

Add to ~/Library/Application Support/Claude/claude_desktop_config.json on macOS or %APPDATA%\Claude\claude_desktop_config.json on Windows:

json
{  "mcpServers": {    "kairn": {      "command": "kairn",      "args": ["serve", "--init", "~/brain"]    }  }}

Cursor

Add to .cursor/mcp.json:

json
{  "mcpServers": {    "kairn": {      "command": "kairn",      "args": ["serve", "--init", "~/brain"]    }  }}

VS Code

Add to .vscode/mcp.json:

json
{  "servers": {    "kairn": {      "type": "stdio",      "command": "kairn",      "args": ["serve", "--init", "~/brain"]    }  }}

Windsurf

Add to ~/.codeium/windsurf/mcp_config.json:

json
{  "mcpServers": {    "kairn": {      "command": "kairn",      "args": ["serve", "--init", "~/brain"]    }  }}

Restart your editor. Kairn's 22 tools appear in the MCP section.

First 5 Minutes

A guided first run, end to end:

bash
pip install kairn-aikairn init ~/brain              # creates the workspace + database (optional: serve --init does it on first start)

Add the one-liner from above (or your client's Quick Start snippet), then restart the client. Once connected, ask your assistant to remember something:

"Remember that we chose Postgres over SQLite for the analytics service because we needed concurrent writers."

That calls kn_learn under the hood and returns a JSON envelope like this (captured from a real run, via kairn learn, the CLI mirror of the tool):

json
{"_v": "1.0", "stored_as": "node", "node_id": "002d9c22", "experience_id": "d0710c2f", "type": "decision", "confidence": "high", "namespace": "knowledge", "candidates": []}

Start a new session and ask it to recall the same thing - that calls kn_recall and surfaces what you just stored, no re-explaining required:

json
{"_v": "1.0", "count": 2, "results": [  {"source": "node", "id": "002d9c22", "name": "Decision: we chose Postgres over SQLite for the analytics service beca", "type": "learned_decision", "namespace": "knowledge", "description": "we chose Postgres over SQLite for the analytics service because we needed concurrent writers", "relevance": 1e-06, "relevance_kind": "match"},  {"source": "experience", "id": "d0710c2f", "type": "decision", "namespace": "knowledge", "content": "we chose Postgres over SQLite for the analytics service because we needed concurrent writers", "confidence": "high", "relevance": 1e-06, "relevance_kind": "match_recency"}]}

kn_learn stored both a permanent graph node and a decaying experience (high confidence does both, see Confidence routing); kn_recall found both from a three-word topic.

Read relevance_kind before you read relevance. match is lexical match strength (bm25). match_recency is match strength with a small recency nudge, a factor between 0.9 and 1.1, on an experience found by a text search. recency is pure time-decay on an experience listed with no search text: it says how old the row is, not whether it matched. similarity is embedding cosine on the semantic-recall path, and unscored marks a row the surface had no ranking for and filled in with a constant, from crossref or a text-less browse query. Both rows above show 1e-06 because SQLite's bm25 gives almost no weight to a word that appears in most entries. On a store with one fact every word does, so the score sits at SQLite's floor. It is not a bad match. After eight more unrelated facts, the same recall measured about 0.5 for both rows. On a store this small, a topic with a word the fact does not contain can score 0.0, and the row is still returned. Scores are only comparable within one result set and are not comparable across kinds, so do not sort a mixed result set on relevance alone. Same caution for min_relevance on kn_recall: it gates nodes on match strength and experiences on recency, one number against two scales. On a small store, a value such as 0.1 drops the node and keeps the experience (measured). On kn_memories and kn_prune, which see experiences only, it is recency - and on kn_prune it deletes.

Run kairn status ~/brain any time as a smoke test - if it prints a JSON stats block (nodes/edges/experiences counts), the workspace is healthy. For a scripted tour, kairn demo adds sample data (two nodes, one edge and two experiences, measured) to the workspace it is given, so give it a throwaway one: kairn init ~/kairn-tour && kairn demo ~/kairn-tour.

Which tool when

22 tools is a lot to hold in your head on day one. Most sessions only need these:

You want to...UseWhy
Remember something new (a decision, gotcha, pattern, solution)kn_learnDefault entry point - auto-routes to a permanent node (high confidence) or a decaying experience (medium/low), no need to decide yourself
Capture a stated user preference the moment it is expressedkn_preferenceDedicated preference write path - you (the calling model) state the preference as one explicit sentence; stored with the longest half-life of any type
Add a permanent named concept you already know is durablekn_addSkips decay entirely - for structural knowledge, not day-to-day experience
Log a one-off experience with explicit confidence/decay controlkn_saveLower-level primitive kn_learn wraps - reach for it when you want to set confidence/decay yourself
Search the permanent knowledge graph by text, type, tags, or namespacekn_queryYou're looking for nodes, not decaying experiences
Search saved experiences, ranked by relevance and decaykn_memoriesYou're looking for experience content (solutions, gotchas, workarounds), not graph nodes
Surface everything relevant to a topic in one callkn_recall (flat list) or kn_context (subgraph, progressive disclosure: summary first, full detail on demand)You don't know yet whether the answer is a node or an experience - let Kairn search both

Everything else (kn_crossref, kn_related, kn_connect, kn_judge, kn_project/kn_projects/kn_log, kn_idea/kn_ideas, kn_promote_pending, kn_prune, kn_remove, kn_status, kn_doctor) is advanced usage - see the full 22 Tools reference below once you're past the basics.

22 Tools (kn_ prefix)

All tools follow MCP protocol with JSON responses.

Graph (6)

ToolDescription
kn_addAdd node to knowledge graph
kn_connectCreate typed edge between nodes (lax-mode vocabulary)
kn_judgeRecord 5-verb judgment edge (strict mode: conflicts_with / supersedes / compatible / scoped / related)
kn_querySearch by text, type, tags, namespace
kn_removeSoft-delete node or edge (undo-safe)
kn_statusGraph stats, health, system overview

Project Memory (3)

ToolDescription
kn_projectCreate or update project
kn_projectsList projects, switch active
kn_logLog progress or failure entry

Experience Memory (5)

ToolDescription
kn_saveSave experience with decay
kn_preferenceCapture a stated user preference at utterance time (longest half-life)
kn_memoriesDecay-aware experience search
kn_pruneRemove expired experiences
kn_promote_pendingPromote high-access experiences to permanent nodes

Ideas (2)

ToolDescription
kn_ideaCreate or update idea
kn_ideasList/filter ideas by status, category

Intelligence (5)

ToolDescription
kn_learnStore knowledge with confidence routing
kn_recallSurface relevant past knowledge
kn_crossrefFind similar past solutions in the current workspace
kn_contextKeywords → relevant subgraph with progressive disclosure
kn_relatedGraph traversal (BFS) to find connected nodes

Diagnostic (1)

ToolDescription
kn_doctorRead-only health checks (lock mode, FTS5 parity, promotion backlog, namespace sprawl, orphan edges) - returns structured envelope with per-check verdicts and roll-up summary

Resources & Prompts

Resources (read-only context for MCP clients):

  • kn://status - Graph overview, active project
  • kn://projects - All projects with recent progress
  • kn://memories - Recent high-relevance experiences

Prompts (session management):

  • kn_bootup - Load active project, recent progress, and top memories (session start)
  • kn_review - Summarize session and suggest next steps (session end)

How It Works

Architecture

Any MCP Client (Claude, Cursor, VS Code)        │        ▼ MCP Protocol (stdio)FastMCP Server (22 tools)        │   ┌────┼────┐   ▼    ▼    ▼Graph  Memory  IntelligenceEngine Engine  Layer   │    │      │   └────┼──────┘        ▼   SQLite + FTS5   (per-workspace)

Decay Model

Experiences decrease in relevance exponentially:

relevance(t) = initial_score × e^(-decay_rate × days)
TypeHalf-lifeNotes
solution120 daysStable, durable
pattern90 daysArchitectural knowledge
decision100 daysContext-dependent
workaround40 daysTemporary fixes fade fast
gotcha70 daysTricky pitfalls stay relevant
preference180 daysDurable user preferences - initial estimate, not yet tail-calibrated

Half-lives are calibrated against the real access tail of a production experience store, not guessed (one exception: preference is a new type with no access history yet, so its value is a documented initial estimate until real data accumulates).

Confidence routing via kn_learn:

  • high → Permanent node + experience (no decay)
  • medium → Experience with 2× decay
  • low → Experience with 4× decay
  • Auto-promotion: 5+ accesses → permanent node
  • Node access tracking: kn_recall, kn_context, and kn_crossref log which nodes were accessed, feeding the decay and promotion pipeline

Benchmarks

[Kairn benchmark scorecard: 56.2% overall on LongMemEval-S, 500 questions scored, per-category accuracy from 91.4% down to a published 10.0% weak cell]

Kairn scored 56.2% overall on LongMemEval-S in the 2026-06-12 run (500/500 questions scored, GPT-4o reader + judge, single run, 0 errors). These are the real per-category numbers, including the bad ones - each red cell links to its diagnosis:

CategorynAccuracyDiagnosis
single-session-user7091.4%-
single-session-assistant5683.9%-
knowledge-update7870.5%-
temporal-reasoning13342.9%why
multi-session13341.4%why
single-session-preference3010.0%why

The 500 questions include 30 abstention variants (the right answer is to decline); they are counted inside their categories above and scored separately: Kairn declines correctly on 96.7% of them.

Recall latency was ~1.4 ms per query in that run (FTS5, in-process, no network). Protocol, honesty notes, and reproduction steps: BENCHMARKS.md.

These numbers were measured on 2026-06-12, before the recall changes in 0.3.0 (match-aware experience scoring, coverage-weighted node relevance), and have not been re-measured on 0.3.0 yet. A weak cell stays on the board until the number actually moves. No cherry-picked runs, no hidden categories.

CLI

bash
kairn init [<path>]            # Initialize workspace; defaults to ~/.kairnkairn serve [<path>]           # Start MCP server (stdio); defaults to ~/.kairnkairn serve --init [<path>]    # Create workspace if needed and start MCP server; defaults to ~/.kairnkairn status <path>            # Graph statskairn workspace create <name>  # Team feature: separate store under ~/.kairn/workspaces, not usable by the <path> commandskairn workspace join <workspace_id> --token TOKEN  # Team feature: needs KAIRN_JWT_SECRETkairn workspace leave <workspace_id>  # Leave workspacekairn demo <path>              # Scripted tour that adds sample datakairn benchmark [--nodes N]  # Performance benchmarks in a temporary workspacekairn token-audit <path>       # Audit tool token usage
kairn learn <path> --content TEXT --type TYPE  # Store knowledge; TYPE is decision, pattern, solution, workaround, gotcha or preferencekairn recall <path> --topic TEXT  # Recall knowledge from nodes and experienceskairn context <path> --keywords TEXT  # Get relevant contextkairn memories <path>          # Search or list experienceskairn crossref <path> --problem TEXT  # Find related solutions
kairn add <path> --name TEXT --type TYPE  # Add nodekairn connect <path> --source-id ID --target-id ID --edge-type TYPE  # Connect nodeskairn judge <path> --source-id ID --target-id ID --relation RELATION  # Record relationship judgmentkairn doctor <path>            # Check graph healthkairn remove <path>            # Remove node or edge using optionskairn query <path>             # Query nodeskairn related <path> --node-id ID  # Traverse related nodeskairn prune <path>             # Delete experiences below recency thresholdkairn promote-pending <path>   # Promote pending knowledge
kairn project <path> --name TEXT  # Create or update projectkairn projects <path>          # List or select projectskairn log <path> --project-id ID --action TEXT  # Record project progress or failurekairn idea <path> --title TEXT  # Create or update ideakairn ideas <path>             # List ideas
kairn import git <path> <repos>...  # Import git commit history (zero-LLM, offline)kairn import claude-code <path>    # Import Claude Code session history (zero-LLM, offline)

Run kairn <command> --help for every option.

Importing your history

kairn import git <workspace> <repo>... backfills a Kairn store from one or more local git repositories at $0 - no LLM calls, no network calls. Conventional-commit prefixes map to experience types (fix: -> solution, feat:/refactor:/perf: -> pattern, everything else -> decision); merge commits are skipped. Imported experiences land in a dedicated imported-git namespace, separate from your organic knowledge, so they're always distinguishable and a bad import is fully reversible.

bash
kairn import git ~/brain ~/code/my-project --dry-run   # Preview firstkairn import git ~/brain ~/code/my-project              # Then import for realkairn import git ~/brain ~/code/proj-a ~/code/proj-b --since 2026-01-01

Idempotent - re-running only imports commits that weren't already imported, so it's safe to run again as a repo's history grows.

Claude Code transcripts

kairn import claude-code <workspace> backfills your Kairn store from your existing Claude Code session history, also at $0 and fully offline. With no --root given it scans ~/.claude/projects; --root PATH is a repeatable override for any other folder. Imported experiences land in their own imported-claude-code namespace, so they stay distinct from your organic knowledge and a bad import is reversible.

bash
kairn import claude-code ~/brain --dry-run              # Review exactly what would be storedkairn import claude-code ~/brain                        # Import (prompts once before writing)kairn import claude-code ~/brain --root ~/other/projects --since 2026-01-01 --yes

What gets stored (coarse mode): one experience per session - the session's title plus your first prompt of that session. This is deliberately a low-detail, high-precision summary rather than a fine-grained per-decision extraction: a zero-LLM rule-based extractor cannot reliably tell a captured decision from ordinary planning chatter, so import claude-code imports a clean session-level pointer instead of noisy fragments. It is not a full transcript archive, and it is not a one-time migration - it is idempotent and meant to be re-run as your history grows.

Privacy. Every stored string is passed through a deterministic secret redactor first (API keys, Authorization/Bearer headers, password=/token=/secret= assignments, common vendor key shapes, private-key blocks, URL-embedded credentials). Tool outputs and tool-call blocks are never read, only your own prompt text. The redactor is defense in depth, not the only control: a real (non-dry-run) run is gated behind an explicit confirmation, and --dry-run shows you the exact post-redaction text before anything is written. Redaction is bounded by its rule set, so --dry-run review before a first real import is recommended; nothing ever leaves your machine.

Install as a plugin

The plugin needs uv.

Claude Code:

bash
claude plugin marketplace add primeline-ai/kairnclaude plugin install kairn@kairn

Codex:

bash
codex plugin marketplace add primeline-ai/kairncodex plugin add kairn@kairn

If you already added Kairn with claude mcp add kairn or codex mcp add kairn, remove that entry first with claude mcp remove kairn or codex mcp remove kairn, or keep only one installation route, because both use the name kairn.

See the plugin README for what it does and the codex exec approval note.

Configuration

bash
KAIRN_WORKSPACE=~/brain               # Sets where config.yaml is read from and where 'kairn workspace' keeps team data; 'kairn serve' opens the store at the given path, or ~/.kairn without one, regardless of KAIRN_WORKSPACEKAIRN_JWT_SECRET=<your-secret>        # Required for team featuresKAIRN_LOG_LEVEL=WARNING               # Level of Kairn's log lines on stderr: DEBUG, INFO, WARNING, ERROR or CRITICAL; default INFO; overrides log_level in config.yaml

Settings live in <workspace>/config.yaml; kairn init writes it and serve --init does not, so create it by hand if you started with serve --init. Without it the defaults apply. Semantic recall is opt-in and off by default. It reranks recall with embeddings from a local Ollama server, so stored content never leaves your machine.

yaml
semantic_recall: trueembedding_model: bge-m3                 # ollama pull bge-m3embedding_host: http://localhost:11434semantic_recall_floor: 0.5              # cosine floor below which semantic recall abstainssemantic_recall_top_n: 30               # keyword candidates reranked by embeddingsexperience_min_match: 0.0              # match floor for experience recall, 0.0-1.0; 0 turns it off

Development

bash
git clone https://github.com/primeline-ai/kairncd kairnpip install -e ".[dev,team]"pytest tests/ -v --covruff check src/ && ruff format src/

Cutting a release: see RELEASING.md.

Project Structure

src/kairn/├── server.py              # FastMCP server + 22 tools├── cli.py                 # CLI commands├── config.py              # Configuration├── core/│   ├── graph.py           # GraphEngine (6 tools)│   ├── memory.py          # ProjectMemory (3 tools)│   ├── experience.py      # ExperienceEngine (4 tools)│   ├── ideas.py           # IdeaEngine (2 tools)│   ├── intelligence.py    # IntelligenceLayer (5 tools)│   └── router.py          # ContextRouter├── storage/│   ├── base.py            # Storage interface│   └── sqlite_store.py    # SQLite + FTS5 implementation├── models/                # Data models├── events/                # Event bus└── auth/                  # JWT + RBAC (team feature)

Performance

Measure it yourself rather than trusting this table:

bash
kairn benchmark --nodes 100

It runs in a temporary workspace that it removes afterwards, so your data is not touched. The numbers come from a fresh, empty store in the system temp folder, so they show the shape of Kairn's speed, not the speed of your own store or disk.

One run of that command, 100 nodes, on an Apple M4 Pro:

OperationMeasured
Insert0.8ms per node (1,252 ops/sec)
FTS5 query0.2ms (5,121 ops/sec)
Graph traversal6.3ms (160 ops/sec)

Single run on one machine, so treat it as a shape rather than a spec - which is why the command is above the table. kn_connect and kn_crossref used to appear here with figures the benchmark does not produce; they have been removed rather than estimated.

Used By

ProjectWhat It Uses Kairn For
Quantum LensPersistent insight storage, cross-analysis pattern tracking, lens effectiveness metrics
Claude Code Starter SystemSession memory, project state, learning persistence

License

MIT


Part of the PrimeLine Ecosystem

ToolWhat It DoesDeep Dive
Evolving LiteSelf-improving Claude Code plugin - memory, delegation, self-correctionBlog
KairnPersistent knowledge graph with context routing for AIBlog
tmux OrchestrationParallel Claude Code sessions with heartbeat monitoringBlog
UPF3-stage planning with adversarial hardeningBlog
Quantum Lens7 cognitive lenses for multi-perspective analysisBlog
PrimeLine Skills5 production-grade workflow skills for Claude CodeBlog
Starter SystemLightweight session memory and handoffsBlog

@PrimeLineAI · primeline.cc · Free Guide

Source: README.md at commit 435753e

Tools

0
SourceWeft has not started this package in its sandbox yet, so its tools are not known.

Version history

4
  1. v0.3.2LatestNov 7, 2026
  2. v0.3.1Oct 11, 2026
  3. v0.3.0Oct 11, 2026
  4. v0.2.1Sep 16, 2026

Score

50% of the applicable checks met

How complete this listing is, computed from the registry entry, the endpoint and public sources. Not a rating of the server and not a statement that it is safe or working today: reachability is a dated check, and no installs or reviews go into the score.

  • Reached in the last 30 days25 pts

    Keep the endpoint answering the MCP handshake; SourceWeft probes it every 30 days.

  • Auth declared10 pts

    Declare the credential headers in the registry entry, or keep the endpoint answering the probe so its auth can be classified.

  • Tools listed15 pts

    Answer tools/list without a credential, or ship a package that starts in a sandbox without one.

  • DescriptionRequired15 pts
  • Logo10 pts
  • Documentation15 pts
  • License10 pts