CogniRepo
CogniRepo is an MCP server that gives AI agents persistent project memory, code intelligence, and cross-repo context.
Memory & learning — store/retrieve semantic memories, record decisions, log episodic events, supersede outdated learnings.
Code intelligence — O(1) symbol lookup, caller tracing, dependency graphs, semantic/vector code search, token search, and knowledge-graph subgraphs.
Context & session tools — token-budgeted context packs, session bootstrap briefs, last-context resume, session history.
User & error adaptation — user behavior profiling (depth/style preferences), error pattern tracking with prevention hints, preference recording.
Cross-repo & org features — org-wide search, repo linking, inter-repo dependency traversal, service endpoint discovery, symbol path finding across services.
Reporting & insights — precomputed architectural summaries and self-contained HTML repo insights reports.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@CogniRepo what did we decide about the caching strategy last sprint?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
CogniRepo
mcp-name: io.github.ashlesh-t/cognirepo
Persistent memory and context for any AI tool. Not a chatbot — infrastructure.

lookup_symbol returns file:line very quickly — grep takes 2–8 seconds. On Python repos ≥ 15K LOC, CogniRepo cuts AI coding agent token usage by ~30–78% vs. a targeted grep+read baseline (up to 96–99% vs. reading every matching file naively) — benchmarked on Flask, FastAPI, Celery, and Ansible (5,900+ files). Works with Claude Code, Cursor, and Gemini CLI. Fully offline. No API keys required for indexing or any of the 36 MCP tools.
What it does
Every AI conversation starts from zero. Claude, Cursor, Gemini — none of them remember what you fixed yesterday, which files relate to which features, or what decisions were made last sprint. CogniRepo fixes that.
It sits between your codebase and any AI tool, providing:
Semantic memory — FAISS vector store with sentence-transformer embeddings. Store decisions, docs, architecture notes. Retrieve them with natural language.
Episodic log — append-only event journal. Know what happened before that error.
Knowledge graph — NetworkX DiGraph linking functions, classes, files, imports, inheritance chains, call relationships, and concepts. All queryable.
AST reverse index — O(1) symbol lookup across your entire codebase in any supported language.
User behavior profiling — tracks how you prompt so Claude adapts its response style without you having to re-explain preferences every session.
Error tracking — records errors with prevention hints so Claude avoids repeating the same mistake across sessions.
Session history — persists conversation exchanges so any session can resume where the last one ended.
Architectural summaries — auto-generated on first init; built entirely from the local AST index (no API key needed). File → directory → repo summary tree, embedded into FAISS for semantic search.
Multi-model orchestration — classify query complexity → build context → route to the right model. Claude for deep reasoning, Gemini Flash for quick lookups. All automatic.
Every AI tool that connects gets the same accumulated project knowledge. Memory persists across sessions, across tools, across time.
Related MCP server: my-memory-mcp
When to use CogniRepo
Most effective on codebases ≥ 15K LOC. On small repos (< 10K LOC), native file reads are fast enough that the MCP tool schema overhead (~3,700 tokens for 36 tools) takes more than you save. Break-even is roughly 4 tool calls on a medium-sized repo.
CogniRepo vs. claude-context / similar tools:
Feature | CogniRepo | claude-context / similar |
Pure code retrieval | ✓ (FAISS + graph + AST) | ✓ Often faster on first use |
Episodic memory (what happened last sprint) | ✓ Persistent BM25 + vector | ✗ |
Cross-agent handoff (Claude → Gemini → Cursor) | ✓ | ✗ |
User behaviour profile (adapts depth/style) | ✓ | ✗ |
Error pattern avoidance (learns from past fails) | ✓ | ✗ |
Architectural decision records | ✓ | ✗ |
Multi-repo org graph (microservices) | ✓ | ✗ |
Conclusion: prefer CogniRepo when you value institutional memory across sessions. Use simpler tools when you just need one-shot code retrieval on a small codebase.
Why it helps — measured numbers
Benchmarked across 6 real open-source repos (FastAPI, Flask, Celery, Ansible, Moby/Docker, Kubernetes) using 30 structured prompts tested against Claude, Gemini, and Cursor/Codex.
Metric | Value | Notes |
Token reduction — Python repos | 50–84% | FastAPI FA-2: 12 000 → 2 500 · FA-4: 2 000 → 450 · FL-4: 8 000 → 1 250 |
Token reduction — average (all tested) | ~60% | Across FA/FL/CE/AN where both baselines were captured |
Token reduction — complex dynamic codebases | 20–35% | Celery CE-4/CE-5; deep async/dynamic-dispatch patterns reduce gains |
Symbol lookup latency | < 1 ms | vs. |
Accuracy vs. baseline | equal or better in 100% of tests | No regression observed; FA-2 accuracy improved Moderate → High |
Cross-agent context handoff | ✅ validated | CE-4: Claude primed index, Gemini CLI consumed it — 35% token saving, same accuracy |
Dynamic dispatch coverage | honest gap | CE-3 (APScheduler beat dispatch) returned NA for both; CogniRepo does not fabricate call chains |
Go/multi-language coverage | grammar now ships | Moby MO-2 showed 67% savings; MO-3-5 / K8-* not yet re-run since Go tree-sitter grammar landed (COGNIREPO-500, 2026-09) |
Honest limits: CogniRepo adds the most value on Python repos with clear static structure. Dynamic dispatch patterns (Celery beat, plugin registries), deep Go codebases, and Ansible's 22-level variable precedence chains reduce retrieval confidence. The tool reports uncertainty rather than hallucinating call chains.
Measured: lookup latency and token reduction (4 external repos)
Indexed 4 real repos, measured with cognirepo index-repo + cognirepo benchmark --json on
v2.4.0+ (2026-09-17). CPU-only, no GPU.
Repo | Files | Lookup latency | Token reduction (naive) | Token reduction (targeted) | context_relevance |
flask | 92 | 0.002 ms | 97.3% | 29.5% | 80.5% |
fastapi | 1,178 | 0.003 ms | 97.6% | 63.5% | 97.1% |
celery | 444 | 0.003 ms | 99.7% | 77.7% | 100.0% |
ansible | 4,196 | 0.008 ms | 96.1% | 28.6% | 56.6% |
Measured 2026-09-17. Lookup latency < 0.1 ms on all repos. "Targeted" is the realistic baseline (grep + read top-2 matching files, approximating what an agent would actually do); "naive" reads every matching file in full and is an upper bound, not a realistic comparison. moby and kubernetes are indexable (Go support confirmed, COGNIREPO-500) but not yet in this table — hours of indexing, scheduled separately. Full numbers and methodology, including precision@k, symbol hit rate, and memory recall: docs/METRICS.md.
Run cognirepo benchmark on your own codebase to reproduce. See docs/METRICS.md.
How it works

Quick start
Requirements
Python 3.11+
API key (optional — only needed for
cognirepo ask):ANTHROPIC_API_KEY,GEMINI_API_KEY,OPENAI_API_KEY, orGROK_API_KEY. Indexing, memory, summarization, and all MCP tools work fully offline.
Install
Recommended — pipx (global, one command, works on all distros)
pipx install cognirepoThat's it. cognirepo setup handles the rest — it installs optional extras (languages,
security, providers) via pipx inject automatically when you enable them in the wizard.
Why pipx? It creates an isolated venv for cognirepo automatically so
fastembedand all deps install cleanly. Thecognirepocommand is then globally available in every directory — no per-repo venv needed.Arch Linux / Debian 12+ / Ubuntu 24.04+: Do NOT
pip installinto system Python. These distros enforce PEP 668 and block system-wide pip installs. Use pipx.
Install pipx first (if needed)
# Arch Linux
sudo pacman -S python-pipx
# Debian / Ubuntu
sudo apt install pipx
# macOS
brew install pipx
# Any platform (fallback)
pip install pipx --userInside a virtual environment (alternative)
python -m venv .venv && source .venv/bin/activate
pip install cognirepo
# extras are installed by the setup wizard automaticallyDevelopment install (from source)
pipx install -e '.[dev,security,languages]'
# or inside a venv: pip install -e '.[dev,security,languages]'Note: CPU-only embeddings are the default (fastembed/ONNX, no PyTorch/CUDA required). For GPU:
pipx inject cognirepo 'cognirepo[gpu]'then install torch separately.
Run
# One-command onboarding (init + index + auto-configure MCP for Claude/Cursor/VS Code):
cognirepo setup
# Or step by step:
cognirepo init --no-index # scaffold .cognirepo/
cognirepo index-repo . # index your codebase (required before MCP tools work)
cognirepo index-repo . --daemon # index and run watcher in background
# Keep the index fresh after every commit (indexes just the changed files, in the background):
cognirepo install-hooks
# Check everything is working:
cognirepo status # shows symbol count, graph nodes, signal warmth
cognirepo doctor # full health check (exit 0 healthy / 1 warnings / 2 errors)
cognirepo doctor --resources # where memory and disk go: processes, store sizes, leftovers
# Query through multi-model orchestrator:
cognirepo ask "why is auth slow?"
# Manage background watchers (one per repo, however many sessions run):
cognirepo watch --ensure-running # start it if it is not running
cognirepo list # show all running watcher daemons
cognirepo list -n <PID> --view # tail the log of a specific watcher
cognirepo list -n <PID> --stop # stop a watcherFirst-time setup:
cognirepo init+cognirepo index-repo .must complete before MCP tools (context_pack,lookup_symbol,who_calls, etc.) return data.
Connect your AI tools
Claude Code / Claude Desktop (recommended — project-scoped)
Run cognirepo init inside your project — it asks if you want to configure Claude and
automatically writes .claude/CLAUDE.md and .claude/settings.json with the correct
project-locked connector.
Each project gets its own isolated connector named cognirepo-<project>:
{
"mcpServers": {
"cognirepo-myproject": {
"command": "cognirepo",
"args": ["serve", "--project-dir", "/abs/path/to/myproject"],
"env": {}
}
}
}The --project-dir flag locks the MCP server to that project's .cognirepo/ directory.
When Claude has multiple projects open simultaneously, each connector reads only its own
memories — never mixing data across projects or teams.
Cursor / Copilot
cognirepo export-spec
cp adapters/cursor_mcp_config.json .cursor/mcp.json
# Restart Cursor — CogniRepo tools appear in the tool selectorDocker
cp .env.example .env # add your API keys
docker compose up mcp # MCP stdio serverMCP Tools — complete reference
All 36 tools are available to Claude, Cursor, and any MCP-compatible client.
Core retrieval
Tool | Description | When to use |
| Token-budget code + memory context | Every session — FIRST call before any file read |
| O(1) symbol lookup → file + line | Before grepping for a function |
| Trace callers + dynamic dispatch fallback | Impact analysis, refactoring |
| Word-level reverse index across names, docs, comments | Finding where a concept lives |
| Semantic similarity search over stored memories | Before answering — pull past context |
| Full-text search in all | Documentation lookups |
| Vector search over code symbols only | Code-specific semantic queries |
| Local knowledge graph neighbourhood | Understand symbol relationships |
| Node/edge count and graph health | Check if graph has data |
| BM25 keyword search in event history | Find past decisions or incidents |
| Import/dependency relationships | Module coupling analysis |
| What changed in a file/function + git cross-ref | Understanding recent changes |
| Pre-computed LLM architectural summaries | Big-picture questions |
User & session intelligence
Tool | Description | When to use |
| User's interaction style: depth pref, question types, vocabulary | Call at session start — calibrates Claude's response style |
| Recent conversation exchanges across sessions | Resuming context from prior sessions |
| Store a style or format preference | When user corrects interpretation or states a preference |
Error tracking & prevention
Tool | Description | When to use |
| Recurring errors with prevention hints | Before proposing a fix — check if it has failed before |
| Log an error for future avoidance | After any error Claude or user encounters |
Session start
Tool | Description | When to use |
| Single-call session start: brief + last context + profile + errors (~300 tokens vs ~900) | Preferred first call — replaces the 4-call sequence |
| Architecture + hot symbols + index health | First call when you need granular parts separately |
| Most recent context_pack snapshot from prior session | Resume where previous agent left off |
Memory & storage
Tool | Description | When to use |
| Persist a memory to the FAISS index | After solving bugs, recording decisions |
| Append event to episodic journal | Track milestones, incidents, deployments |
| Record architectural decision to episodic memory | When making non-obvious design choices |
| Deprecate and replace an outdated memory in one call | When a past decision or fact has changed |
Reporting
Tool | What it returns | When to use |
| Self-contained HTML repo-history report (timeline, decisions, challenges, activity, index health), sourced only from real stored records | "What happened in this repo" / repo-history requests — see Repo insights below |
Grounded pushback
Tool | What it returns | When to use |
|
| Before implementing a non-trivial instruction, to check it against recorded precedent first |
Cross-repo (organization)
Tool | Description | When to use |
| Search memories across all org repos | Multi-repo context queries |
| Search across every project in the org | Broadest cross-repo sweep |
| Bidirectional inter-repo dependency graph | "What does this service depend on?" |
| Project-scoped or org-scoped search | Finding shared components |
| Traverse org graph from a repo or symbol | Tracing bugs across service boundaries |
| Shortest call-graph path between two symbols, across services | Tracing a request flow end-to-end |
| HTTP endpoint registry for a service | Listing a microservice's API surface |
| Org metadata + sibling repos | Understanding repo relationships |
| Record cross-repo dependency | When you discover one repo imports another |
Knowledge graph — what gets indexed
The knowledge graph is significantly richer than a simple call graph.
Node types
Type | Description |
| Every indexed source file |
| Function and method definitions with docstrings |
| Class definitions with base classes |
| Semantic concepts extracted from docstrings and identifiers |
| Recorded query nodes (for retrieval scoring) |
| Conversation session nodes |
| Recurring error pattern nodes |
| Cross-agent memory nodes (synced from Claude/Gemini) |
Edge types
Type | Direction | Description |
| symbol → file | Symbol lives in this file |
| bidirectional | Function call relationships with purpose labels |
| file → file | Python import dependencies |
| class → parent | Inheritance hierarchy |
| file ↔ file | Files edited together (behavioural co-edit signal) |
| concept → symbol | Semantic concept linkage |
| query → symbol | Retrieval tracking for scoring |
IMPORTS and INHERITS edges are built automatically during index-repo from Python AST.
Use subgraph("MyClass", depth=2) or dependency_graph("mymodule") to query them.
User behavior profiling
CogniRepo tracks how you interact across sessions and builds a profile that Claude uses to calibrate its responses — without you having to repeat preferences every session.
What gets tracked
Depth preference — inferred from average query length:
concise/medium/detailedQuestion types — distribution across:
why,what,how,fix,explain,where,refactor,addDomain vocabulary — top terms that appear frequently in your queries
Code focus — percentage of queries referencing code identifiers (symbols, functions)
Sample queries — last 3 queries for Claude to infer framing style
Accessing your profile
# MCP tool (Claude calls automatically at session start):
get_user_profile()
# CLI:
cognirepo user-prefsExample profile output
{
"depth_preference": "detailed",
"top_question_type": "how",
"question_type_distribution": {"how": 12, "why": 8, "fix": 5},
"top_terminology": ["auth", "token", "session", "middleware", "validate"],
"code_focus_percent": 73,
"framing_hints": "prefers detailed responses; often asks 'how' questions; domain vocabulary: auth, token, session",
"total_queries_tracked": 47
}Claude receives framing_hints at session start and adjusts response length, code density,
and terminology accordingly. The profile accumulates over time — more accurate the more you use it.
Error tracking & prevention
CogniRepo logs every error that occurs during sessions — whether it's a Python exception, a failed build step, or a tool call that went wrong. Errors are stored with:
Dedup signature — prevents the same error from inflating the count
Prevention hint — a targeted suggestion to avoid the same error class
Occurrence context — last 5 occurrences with file path and error message
Query context — the query or action that triggered the error
Logging errors
# MCP tool (Claude calls after errors):
record_error("TypeError", "expected str got int", "config/parser.py", "fix config loading")Viewing error patterns
# MCP tool:
get_error_patterns()Returns:
[
{
"error_type": "TypeError",
"count": 7,
"files": ["config/parser.py", "api/handlers.py"],
"last_seen": "2026-04-22T10:30:00Z",
"prevention_hint": "Wrong type — validate inputs at function boundary.",
"recent_context": "expected str got int in parse_config"
}
]Built-in prevention hints
Error class | Prevention hint |
| Undefined variable — check imports and scope before use |
| Import failed — verify package is installed and module path is correct |
| Object missing attribute — check type, None-guard, or spelling |
| Wrong type — validate inputs at function boundary |
| Missing dict key — use |
| List out of range — guard with |
| File/IO error — always guard file ops with |
| Syntax error — run a linter before committing |
| Timeout — add explicit timeout parameter and retry logic |
| Assertion failed — review invariants; do not use assert in prod |
Session history
Every cognirepo ask exchange is persisted to .cognirepo/sessions/.
Sessions are indexed by UUID and retrievable via:
# List recent sessions:
cognirepo sessions
# MCP tool — Claude calls at session start to resume context:
get_session_history(limit=5)Each entry returns: session ID, created timestamp, message count, model used, and the last user/assistant exchange for quick context scan.
Architectural summaries
cognirepo init automatically prompts to run cognirepo summarize after the first index.
This produces a 3-level LLM summary of the entire codebase:
Level 1 — repo-wide summary (what the project does, key modules, entry points)
Level 2 — per-directory summaries (what each package is responsible for)
Level 3 — per-file summaries (what each file contains, key functions/classes)
Summaries are stored in .cognirepo/index/summaries.json and served via the
architecture_overview MCP tool — zero token cost for Claude to understand the big picture.
# Auto-prompted on first init. Run manually anytime:
cognirepo summarize
# Fully local — no API key required. Reads from ast_index.json, runs in < 1 second.
# File summaries are also embedded into FAISS for semantic architecture queries.Repo insights
What CogniRepo can tell you about your repo: generate_insights() (or cognirepo insights)
turns everything CogniRepo has recorded about a project — episodic events, architectural
decisions, open challenges, branch/commit activity, index health — into one self-contained HTML
report. Sourced only from real stored records; nothing fabricated. Screenshots below are from a
real report generated on this repo (cognirepo insights --since 365d), not mockups:
cognirepo insights --since 90d # writes .claude/insights/<repoName>-insights.htmlMulti-model orchestration
cognirepo ask automatically picks the right model for each query:
Tier | Score | Default model | Use case |
QUICK | ≤2 | local resolver | Single-token / trivial — zero API, fastest path |
STANDARD | ≤4 | Haiku | Quick lookup, factual, single symbol |
COMPLEX | ≤9 | Sonnet | Moderate reasoning |
EXPERT | >9 | Opus | Cross-file, architectural, ambiguous — full context, best model |
cognirepo ask "where is verify_token defined?" # → QUICK, answered locally
cognirepo ask "why is auth slow?" # → EXPERT, Claude with full context
cognirepo ask --verbose "explain the circuit breaker" # show tier/score/signalsProvider fallback chain: Grok → Gemini → Anthropic → OpenAI.
All errors are logged to .cognirepo/errors/<date>.log — no raw tracebacks shown to users.
Language support
Language | Extensions | Install |
Python |
| built-in |
Swift |
|
|
Kotlin |
|
|
JavaScript / TypeScript |
|
|
Java |
|
|
C# |
|
|
Go |
|
|
Rust |
|
|
Ruby |
|
|
C / C++ |
|
|
PHP |
|
|
Full details and roadmap: docs/LANGUAGES.md
Storage layout
.cognirepo/
config.json ← project settings (project_id, models, retrieval weights, indexing, behaviour bounds)
cognirepo.lock ← cross-process store lock (OS advisory lock; never delete by hand)
graph/
graph.pkl ← NetworkX DiGraph (optionally Fernet-encrypted)
graph.journal ← append-only journal, present only while `index-repo` runs or after a failed save
behaviour.json ← per-symbol hit counts, user profile, error patterns (bounded, see CONFIGURATION.md)
index/
ast_index.json ← reverse symbol index + file records
ast.index ← FAISS IndexIDMap2 for code symbols
ast_metadata.json ← parallel metadata for ast.index rows
manifest.json ← git SHA, platform info and checksums for integrity checks (`verify-index`)
summaries.json ← LLM architectural summaries (Level 1–3)
last_indexed.json, endpoints.json, http_calls.json, … ← indexing bookkeeping
vector_db/
chroma/ ← default semantic-memory store (ChromaDB); `semantic.index` when `vector_backend: "faiss"`
memory/
episodic.json ← append-only event journal
semantic_metadata.json ← metadata for the local FAISS semantic store (`vector_backend: "faiss"`) and project memory
learnings/
learnings.json ← structured learnings: decisions, bugs, prod issues
watchers/ ← watcher registry (<pid>.json), heartbeat, lease (watcher.writer), logs
sessions/ ← conversation session files
errors/ ← daily error logs (full tracebacks, never shown to users)
hook.log, hook.last ← output and last result of the git post-commit hook (`install-hooks`)Files the loaders set aside are kept, never silently deleted: graph.pkl.corrupt-<ts> (may well hold an
intact graph — see cognirepo graph restore), vector_db/chroma.corrupt-<ts>/, *.stale.
cognirepo doctor --resources lists them with sizes. Expected sizes and tuning knobs:
docs/RESOURCES.md.
Everything under .cognirepo/ is .gitignored by default — never committed.
Fernet encryption is opt-in at storage.encrypt: true in config.json; it covers the graph, behaviour
model, org graph, episodic log and local FAISS store, but not the AST index or the default Chroma
store — see SECURITY.md for exactly what is and isn't covered.
CLI reference
# Setup
cognirepo init # scaffold + configure; auto-indexes + auto-summarizes
cognirepo setup-env # interactive API key wizard
cognirepo test-connection # test API key connectivity
cognirepo migrate-config # migrate deprecated config keys
# Indexing
cognirepo index-repo [path] # AST-index a codebase
cognirepo summarize # generate LLM architectural summaries (auto-prompted on init)
cognirepo seed --from-git # seed behaviour weights from git history
cognirepo verify-index # verify AST index integrity
cognirepo coverage # per-directory symbol counts
# Querying
cognirepo ask <query> # route through multi-model orchestrator
cognirepo retrieve-memory <q> # similarity search
cognirepo search-docs <q> # full-text search in .md files
cognirepo log-episode <event> # append episodic event
cognirepo history # print recent episodic events
cognirepo sessions # list recent conversation sessions
# Memory management
cognirepo store-memory <text> # save a semantic memory
cognirepo user-prefs # view/set global user preferences
cognirepo prune [--dry-run] # prune low-score memories
# Health & monitoring
cognirepo prime # generate session bootstrap brief
cognirepo status # live retrieval signal weights + index health
cognirepo doctor [--fix] # full health check; --fix auto-repairs common issues
cognirepo doctor --resources # processes, store sizes and left-over files (read-only)
cognirepo benchmark # run quantitative value benchmarks
cognirepo install-hooks # git post-commit hook: reindex changed files after each commit
cognirepo graph restore # list quarantined graphs and restore the best intact one (dry-run; --apply)
# Organization
cognirepo org create <name> # create local organization
cognirepo org link <org> [path] # link repo to organization
cognirepo org list # list organizations
# Daemon management
cognirepo list # list MCP servers, running daemons (`-n PID --stop` to stop one)
cognirepo watch --ensure-running # start the background file-watcher (one per repo); `--status` to inspectEvery command, flag and exit code: docs/CLI_REFERENCE.md.
Future Plans
Priorities drawn from the v0.3.0 benchmark findings and community feedback. Now at v2.5.0 — some items below have since landed; each is annotated where that's the case.
Near-term
Go call-graph indexing — done (COGNIREPO-203): Go receiver-qualified method calls (
recv.Method()) now resolve throughwho_calls/CALLS edges — tree-sitter's Goselector_expressionnames its method fieldfield, notproperty(the JS convention the extractor previously assumed), so method calls were silently dropped; fixed in_ts_collect_calls(intelligence/indexer/ast_indexer.py). A second bug in the same function — a call-collection recursion depth cap of 12, too shallow for a Go method wrapping an if-statement around a composite-literal call argument — was also raised (to 60). Go IMPORTS edges fromgo.mod-resolved local package imports are implemented (_extract_imports_go/_resolve_go_import_to_file). Live-verified againstcognirepo_test_repo/advanced/moby: 4/4 hand-verified callers resolved (100%, vs. the 90% target) after both fixes.cognirepo ask— done: multi-model orchestrator (QUICK/STANDARD/COMPLEX/EXPERT tiers) is implemented and wired as a real CLI command (_cmd_ask_local,interface/cli/main.py). Streaming REPL mode (see Longer-term) is not yet built.Incremental re-index on save — done: the file-watcher daemon (
cognirepo watch) debounces writes (config.json→indexing.debounce_ms, default 500ms) and batches indexer/graph saves;tests/test_watcher_debounce.pycovers this including flush-on-shutdown.CLAUDE.md mandatory-call relaxation — benchmark feedback (Moby tests) flagged that forcing
context_packbefore every file read adds latency under memory pressure. A--fastmode that skips the tool-first gate for files under 50 lines is not yet implemented.
Medium-term
Platform (planned for 3.0) — a single per-user daemon, a local control API (
/api/v1) with acognirepo uicommand, and an SQLite (WAL) graph store to replace the resident in-memory graph. The Engram console that consumes the API lives in its own repository. Local-only by design: no hosted relay, no remote access. Tracked in the "Platform" epic.Kubernetes / 2M-LOC scale validation — K8-1 through K8-5 test suite not yet completed. Goal: full scheduling-decision trace at < 8 000 tokens with CogniRepo vs. > 50 000 without.
Plugin-registry pattern detection — done (COGNIREPO-203): a static, annotation-only heuristic pass tags symbols reachable via dynamic dispatch — celery-style
@task/@shared_taskdecorators,register(...)-style plugin-registration calls, Python__init_subclass__hooks, and packaging entry-points (pyproject.toml[project.entry-points.*]/setup.cfg[options.entry_points]) — withdispatch:"dynamic"plus aRELATES_TOedge to adynamic_dispatchCONCEPT node (_detect_dynamic_dispatch,_apply_entry_points_dispatchinintelligence/indexer/ast_indexer.py). Annotation-only by design — never fabricates a CALLS edge. Live-verified againstcognirepo_test_repo/medium/celery's real@shared_taskfunctions.BM25 over symbol names — partially done:
core/_bm25.pyis used byintelligence/retrieval/hybrid.pyas the circuit-breaker fallback ranker (and by episodic search) when embeddings are unavailable, but it isn't yet the primary ranking signal for symbol-name partial-match recall (e.g.HttpClientmatchinghttp_client) in the normal (embeddings-available) retrieval path.Cross-session memory warm-up — Ansible benchmark noted episodic/memory retrieval is low-value on fresh sessions.
cognirepo primeexists but is not run automatically oninit; will make it opt-in default.
Longer-term
cognirepo askstreaming REPL — full interactive session with tier routing, session persistence, and sub-agent delegation.Similarity edges in knowledge graph — done (COGNIREPO-202): post-index FAISS k-NN pass over already-embedded FUNCTION/CLASS symbol vectors adds a
SIMILAR_TOedge (cosine ≥ 0.80, max 5/node, cross-file only) between near-duplicate symbols, both directions. Gated viaconfig.json→indexing.similarity_edges(default on below 20k candidate symbols). Weighted (discounted) intointelligence/retrieval/hybrid.py::_graph_score.VS Code / JetBrains extension — surface
lookup_symbol,context_pack, andwho_callsdirectly in the editor sidebar without requiring an MCP-capable host.
Documentation
Document | Description |
System design, component responsibilities, data flow | |
Technical spec, complexity signals, storage layout | |
Complete CLI, MCP, and Docker reference | |
Every command and flag (checked against the real CLI by a test) | |
| |
Memory and disk footprint, | |
Common problems: stale index, busy store, hook, stray processes | |
What changed in each release, with upgrade notes | |
Quantitative benchmarks: token reduction, lookup speedup, recall | |
How to add adapters, tools, and language support | |
Vulnerability reporting, data handling, trust model | |
Language support details and roadmap |
Community
Questions, feedback, or just want to see what others are building? Join the CogniRepo Discord.
Want to contribute? See CONTRIBUTING.md — issues labeled
good first issue are
scoped for a first PR.
License
CogniRepo is licensed under the MIT License.
Free to use, study, modify, and distribute
Use in proprietary products and commercial services — no restrictions
No requirement to open-source your application
See LICENSE for full details.
Available Tools
35 toolsarchitecture_overviewC
Retrieve pre-computed architectural summaries. scope: 'root' for repo summary, a directory path, or a file path.
repo_path: optional absolute path to the target repository.
Inputs: scope, repo_path. Returns: result
context_packA
Budget-pack the most relevant code + episodic context into a token-bounded block ready for injection into the next prompt. Call this BEFORE reading any source file to avoid wasting tokens on raw file reads. Returns at most max_tokens (default 2000) tokens — much smaller than raw files. Do NOT call for known short files (< 50 lines) — use Read directly instead.
file: optional relative path to scope retrieval to a single file. repo_path: optional absolute path to the target repository. When omitted, defaults to the server's configured project directory.
Inputs: query (required), file, repo_path, max_tokens, +3 more.
cross_repo_searchA
Search knowledge from sibling repositories.
scope="project" — only repos in same project (recommended, high relevance). scope="org" — all repos in organization (broader, use sparingly).
Requires repos linked via cognirepo init (written to org graph).
Returns empty results if no sibling repos are registered.
Claude: call this when:
lookup_symbol returned empty and the symbol may live in a sibling repo
The architecture question spans multiple services in the same project
User asks "how does X work across the system" or "what does repo Y do"
Importing from a sibling repo and need context on its internals
Inputs: query (required), scope, top_k.
cross_repo_traverseA
Traverse the org dependency graph from a repo or symbol to find cross-service relationships.
direction="dependencies" — what does this repo depend on? direction="dependents" — which services depend on this repo? direction="both" — return both directions (default)
If symbol is provided, also reports where that symbol exists in each traversed repo.
Requires repos linked via cognirepo init (written to org graph).
Returns empty if no sibling repos are registered.
Claude: use this when the user asks "which services use X?", "what does auth-service depend on?", or when tracing a bug across service boundaries.
Inputs: depth, symbol, direction, start_repo.
dependency_graphC
Return import/dependency relationships for a module. direction: "imports" | "imported_by" | "both". depth: transitive traversal depth (1 = direct only).
repo_path: optional absolute path to the target repository.
Inputs: module (required), depth, direction, repo_path.
episodic_searchA
Return past episodic events matching a keyword query.
include_archived: also search events rotated out of the live store (episodic_archive.json). Default False — live store only. Archived hits are tagged {"archived": True}. repo_path: optional absolute path to the target repository.
Inputs: query (required), limit, repo_path, include_archived.
explain_changeB
Explain what changed in a file or function recently by cross-referencing git history with episodic memory events mentioning the same target.
repo_path: optional absolute path to the target repository.
Inputs: target (required), since, repo_path, max_commits.
find_symbol_pathA
Find the shortest call-graph path between two symbols, crossing service boundaries via the org graph when needed.
Uses weighted Dijkstra (w=1.0→cost 1, w=0.75→1.3, w=0.5→2.0, cross-service org edge→5) to prefer traversal through core entry-point symbols over indirect paths.
from_symbol : Name of the source symbol. to_symbol : Name of the destination symbol. from_repo : Absolute path to source repo (auto-detected if omitted). to_repo : Absolute path to destination repo (auto-detected if omitted).
Returns {path, hops, crosses_services, services_traversed} or {error}.
Inputs: to_symbol (required), from_symbol (required), to_repo, from_repo.
generate_insightsA
Generate/update the repo insights HTML report — a human-readable "what happened in this repo" summary (timeline, decisions, challenges, branch/ commit activity, index health), sourced only from real stored records.
Returns a small pointer, NOT the report content: {status, path, sections, updated_at}. Claude: surface the path/link in your reply — do not quote or reconstruct the report body from this tool's output.
since: history window, e.g. "90d" (default). repo_path: optional absolute path to the target repository.
Inputs: since, repo_path.
get_agent_bootstrapA
Single-call session bootstrap for AI agents. Replaces the 4-call sequence (get_session_brief → get_last_context → get_user_profile → get_error_patterns) with one ~300-token payload.
Returns: repo — project name architecture — 600-char architecture summary hot_symbols — ["fn:file:line", ...] top 8 symbols by behaviour weight last_focus — {files, query, agent} from last agent's context_pack framing — {depth, vocabulary} from user profile (empty if tracking off) mood — {state, evidence, suggested_adaptation}; neutral/empty on sparse data error_patterns — top 3 recurring errors with prevention hints index_health — {symbols, files, status} recent_timeline — last 5 entries (past 7 days) merged across sessions, episodes, decisions, and errors — {ts, kind, summary, ref} each; see data/memory/timeline.py::merge() for the full query surface (since/include_archived/limit)
Claude: call this ONCE at session start instead of the 4 individual calls. Use individual tools only when you need the full detail each provides.
repo_path: optional absolute path to the target repository.
Inputs: repo_path.
get_error_patternsA
Return recurring error patterns with prevention hints to avoid repeating mistakes.
Each entry has: error_type, count, affected files, last_seen, prevention_hint, and the most recent error message for context.
Use this to guide Claude away from solutions that have historically failed.
min_count: only return errors seen at least this many times (default 1). repo_path: optional absolute path to the target repository.
Inputs: min_count, repo_path.
get_last_contextA
Return the most recent context snapshot written by context_pack.
Call this at the START of a session to resume where the previous agent left off. Returns: query, sections, token_count, generated_at, agent, org_graph_summary. Returns {"status": "no_context"} if no snapshot exists.
Claude: call this automatically at session start when starting work on a known project. It shows what the last agent was looking at, preventing duplicate exploration and token waste.
Do NOT call on a fresh project that has never run context_pack.
repo_path: optional absolute path to the target repository.
Inputs: repo_path.
get_service_endpointsA
Return the HTTP endpoint registry for a service (from endpoints.json).
Endpoints are populated by cognirepo index-repo and include method, path pattern, handler function name, file, and framework.
repo_path: absolute path to the target repo (defaults to current project).
Returns {endpoints, count, scanned_at} or {endpoints: [], count: 0}.
Inputs: repo_path.
get_session_briefA
Generate a session bootstrap brief for agent orientation.
Returns: architecture summary, entry points (most-called symbols), recent decisions from learning store, hot symbols from behaviour tracker, index health (symbol count, file count, last_indexed).
Claude: call this at the START of a session on an unfamiliar project, or when resuming after a long break. Gives you the full project map in one call — faster than reading files or running grep.
Do NOT call this repeatedly; call once at session start only.
repo_path: optional absolute path to the target repository.
Inputs: repo_path.
get_session_historyA
Return recent conversation session exchanges for context continuity.
Each entry has: session_id, created_at, message_count, and last_exchange (the final user/assistant pair). Call at session start to resume context.
limit: number of most-recent sessions to return (default 10). repo_path: optional absolute path to the target repository.
Inputs: limit, repo_path.
get_user_profileA
Return the user's interaction style profile for Claude to adapt its responses.
Includes: depth preference, dominant question types, domain vocabulary, code-focus percentage, framing hints, and a mood signal ({state, evidence, suggested_adaptation} — neutral/empty on sparse data) Claude should apply. Precedence: explicit user request > persona > framing_hints/mood. If the user has opted into a persona (COGNIREPO-402, via record_user_preference), the payload additionally carries active_persona + persona_behavior — absent entirely when no persona is set (byte-identical to pre-402 output otherwise). Caveman persona additionally carries output_contract (COGNIREPO-403) — served ONLY when active. After sustained QUICK-tier query usage, the payload may also carry a one-line, dismissible persona_suggestion nudging toward caveman — never auto-enabled.
Call this at the start of a session to calibrate response style.
repo_path: optional absolute path to the target repository.
Inputs: repo_path.
graph_statsB
Return a health summary of the current graph state.
repo_path: optional absolute path to the target repository.
Inputs: repo_path.
link_reposA
Record a dependency relationship between two repos in the org graph. Call this when you discover that one repo imports from or calls another.
relationship: 'imports' | 'calls_api' | 'shares_schema' | 'discovered' | 'child_of' src_repo / dst_repo: absolute filesystem paths to the repos. service_type: optional — 'rest_api', 'grpc', 'worker', 'frontend', 'library' port: optional — port number the destination service listens on api_base_url: optional — base URL/path prefix for the destination's API
Do NOT call for repos not yet registered via cognirepo init. Returns: {linked: True, edge: {src, dst, kind}}
Inputs: dst_repo (required), src_repo (required), note, port, +3 more.
list_org_contextA
Show what org, project, and sibling repositories the current repo belongs to.
Claude: call this FIRST when the user asks about cross-service or cross-repo topics. Use the returned context to decide whether to call cross_repo_search, and which scope (project vs org) is appropriate.
Inputs: no named parameters.
log_episodeA
Log a structured episodic event to the episodic memory store. Use to record what happened: bugs found, code explored, agent actions. Retrievable via episodic_search in future sessions. Do NOT use for architectural decisions — use record_decision instead.
Inputs: event (required), metadata, repo_path.
lookup_symbolA
Return all locations where a symbol is defined or called, with file, line, and type. If include_org=True, also searches sibling repositories in the same organization. Do NOT call for broad concepts — only exact or near-exact symbol names. For concept queries use semantic_search_code instead.
repo_path: optional absolute path to the target repository. When omitted, defaults to the server's configured project directory.
Inputs: name (required), repo_path, include_org.
org_dependenciesA
Return the bidirectional inter-repo dependency graph for the current organization.
Shows which services this repo depends on (dependencies) and which services
depend on this repo (dependents), up to depth hops. Edge kinds:
IMPORTS — manifest-declared package dependency (auto-detected)
CALLS_API — HTTP client calls to another service's endpoint
SHARES_SCHEMA — shared models/proto repo
Claude: call this when the user asks about service dependencies, "what depends on X", or when investigating cross-service call chains.
Inputs: depth.
org_searchA
FALLBACK ONLY — use org_wide_search first. Text-match search across org repos when org_wide_search returns nothing. Do NOT call as primary cross-repo search — org_wide_search has broader coverage.
Use when: org_wide_search returned 0 results, or the index is sparse. Returns a list of results annotated with source repository.
Inputs: query (required), top_k.
org_wide_searchA
PRIMARY tool for cross-repo queries. Searches memories across ALL registered repos. Use this by default when a query spans multiple services or the answer may live in any repo. Prefer this over org_search (legacy fallback).
Use cross_repo_search when you need explicit scope control (project vs org). Use org_search only as a fallback when this returns empty.
Returns {results, count, repos_searched, repos_skipped} — check repos_skipped if an expected service is missing from results.
Claude: use this as the default cross-repo search.
Inputs: query (required), top_k.
record_decisionA
Record an architectural decision, bug fix rationale, or 'why we did X'. Stored in episodic memory — retrievable via episodic_search in future sessions. Call when a non-obvious architectural decision is made, a bug root-cause is understood, or the user says to 'remember' something. Do NOT call for routine changes — only decisions where WHY is non-obvious. Returns: {stored: True, searchable_via: 'episodic_search'}
Inputs: summary (required), rationale, repo_path, affected_files.
record_errorA
Record an error Claude or the user encountered so future sessions can avoid it.
error_type: exception class name or short label (e.g. "TypeError", "build_failed"). message: error message text (truncated to 300 chars). file_path: source file where the error occurred (optional). query_context: the query or action that triggered the error (optional). repo_path: optional absolute path to the target repository.
Returns: the prevention hint for this error type.
Inputs: error_type (required), message, file_path, repo_path, +1 more.
record_user_preferenceA
Store an explicit user preference or query-rewrite correction.
Standard preferences (preference_key = any label): Store as: record_user_preference("response_format", "code-first, then explanation") Surfaced via get_user_profile()['explicit_preferences'].
Query-rewrite corrections (preference_key = "query_rewrite"): Use when you asked for X but user says they actually meant Y. Store the wrong phrasing as preference_value, intent in context: record_user_preference("query_rewrite", "deploy model", context="user means: update the ML model weights in production, not software deploy") Stored in query_rewrites list; agents apply these before retrieval so future similar queries hit the right code even when phrasing is off.
Persona selection (preference_key = "persona", COGNIREPO-402): Opt-in only — never enable a persona without the user explicitly asking. Valid values: "mentor" (deeper retrieval + full explanations + links to history), "pair" (default-equivalent, mood-aware phrasing), "caveman" (economy/telegraphic output, see COGNIREPO-403). "none" clears a previously-set persona (COGNIREPO-400-D01) — not a 4th persona. An unknown value is rejected, not stored — response includes {"recorded": false, "error": "..."}. Surfaced via get_user_profile()['active_persona'] / ['persona_behavior']. Precedence: explicit user request > persona > framing_hints/mood (see CLAUDE.md).
Claude: call this when:
User corrects your interpretation ("no, I meant X not Y")
User expresses a repeated preference ("always show code first")
User clarifies what a query actually means in this codebase
Do NOT call for one-off answers — only for durable preferences that should persist across sessions.
Inputs: preference_key (required), preference_value (required), context, repo_path.
retrieve_memoryA
Retrieve the top-k memories most similar to the query. If include_org=True, also queries sibling repositories in the same organization.
repo_path: optional absolute path to the target repository. When omitted, defaults to the server's configured project directory.
Inputs: query (required), top_k, repo_path, include_org.
search_docsA
Search indexed documentation files (*.md, *.rst, *.txt) by semantic similarity. Use for: README explanations, architecture docs, decision logs. Do NOT use for code — use semantic_search_code instead.
repo_path: optional absolute path to the target repository.
Inputs: query (required), top_k, repo_path.
search_tokenA
Word-level reverse-index search.
Unlike lookup_symbol() which only matches defined symbol names, search_token() finds any word that appears in symbol names, docstrings, or inline comments across the indexed codebase.
Examples: search_token("background") → files containing 'background' in names/docs search_token("validate") → all functions whose docs mention validation search_token("github") → files where GitHub is referenced in comments
Returns a list of {file, line} dicts sorted by file path.
repo_path: optional absolute path to the target repository.
Inputs: word (required), repo_path.
semantic_search_codeA
Semantic vector search over indexed code symbols only (no episodic memory mixed in). Optionally filter by language: "python", "typescript", "go", etc. Do NOT call for exact string matches — use search_token or grep instead. Use for concepts and natural-language queries about what code does.
repo_path: optional absolute path to the target repository.
Inputs: query (required), top_k, language, repo_path.
store_memoryA
Store a semantic memory with an optional source label.
The response includes a conflicts list — existing learnings with high
word-overlap to the new text. A non-empty list means a potentially
contradictory memory already exists; use supersede_learning to replace
it rather than letting both co-exist.
repo_path: optional absolute path to the target repository. When omitted, defaults to the server's configured project directory.
Inputs: text (required), source, repo_path.
subgraphC
Return the local neighbourhood of a concept or symbol as {nodes, edges}.
repo_path: optional absolute path to the target repository.
Inputs: entity (required), depth, repo_path.
supersede_learningA
Deprecate an existing memory (by ID from store_memory conflicts list) and replace it with corrected text. Use when store_memory returns a conflict that contains incorrect or outdated information.
old_id is the ChromaDB document ID returned in the conflicts list. Returns: {found_old: bool, new_id: str}
repo_path: optional absolute path to the target repository.
Inputs: old_id (required), new_text (required), repo_path, learning_type.
who_callsA
Return every caller of a function across the indexed repo.
First searches the call graph (AST-indexed edges). If empty, falls back to string-literal grep for dynamic dispatch patterns (APScheduler add_job, Django signals, Flask routes, Celery tasks, etc.). Dynamic hits are labelled with found_via=dynamic_dispatch_fallback. Do NOT call if you already know the callers. Expensive on large graphs.
repo_path: optional absolute path to the target repository.
Inputs: function_name (required), repo_path.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 35 tools
Several tools serve overlapping search/retrieval purposes: semantic_search_code vs search_token vs lookup_symbol vs subgraph all handle code discovery, and cross_repo_search vs org_wide_search vs org_search heavily overlap (though descriptions try to establish a hierarchy). The descriptions help differentiate primary vs fallback, but an agent could still confuse episodic_search vs retrieve_memory vs store_memory, and get_session_brief vs get_agent_bootstrap vs get_last_context all serve session-start context.
Naming is mostly verb_noun (retrieve_memory, record_decision, search_docs, explain_change, link_repos), but there are notable inconsistencies: org_search vs org_wide_search vs cross_repo_search have parallel but semantically overlapping structures, and get_session_brief/get_last_context/get_agent_bootstrap/get_session_history all use get_* while also mixing nouns without a clear pattern. Some names are vague (subgraph, context_pack, who_calls) while others are very specific.
35 tools is excessive for a code-knowledge memory server. Many tools overlap or are variants of each other (e.g., three cross-repo search tools, four session-bootstrap tools, multiple memory retrieval tools). A well-scoped server would likely need 15-20 tools; 35 creates navigation burden and redundancy.
The server covers the domain of knowledge capture, retrieval, graph relationships, and session context fairly comprehensively: memory stores, episodic logs, symbol lookup, dependency traversal, service endpoints, error tracking, and user preferences. Minor gaps exist (no obvious tool for deleting memories or removing repos, no direct tool for listing all memories), but agents can work around these via supersede_learning and the existing search tools.
Maintenance
Related MCP Connectors
Persistent memory for AI agents to retain, retrieve, and recall conversation context through MCP.
Cross-tool persistent memory and context for AI assistants over MCP.
Persistent memory, knowledge graph, task management and more for AI agents via MCP.
An MCP memory server. One memory your agents share — across models, devices and apps.
Related MCP Servers
- AlicenseNot gradedqualityNot gradedmaintenanceAn MCP server enabling AI assistants to store, retrieve, and manage contextual information across conversations with features like persistent memory, advanced search, tagging, and privacy controls.MIT
- FlicenseNot gradedqualityDmaintenanceA MCP server that provides persistent memory for AI assistants, storing personal information, relationships, and observations to enable personalized and contextual conversations.4-
- AlicenseNot gradedqualityCmaintenanceMCP server that provides AI agents with persistent memory, cross-agent sharing, and context management, enabling them to remember conversations, track complex tasks, and evolve skills across tools.2MIT
- AlicenseAqualityDmaintenanceMCP server for persistent, semantic memory across AI sessions; store context, decisions, and learnings and recall them with natural language search.244 npmMIT