LeanKG
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
Why LeanKG
Lower agent cost. Agents ask for a targeted subgraph (callers, dependents, impact, tests, docs) instead of running grep-and-read loops over whole files. Measured figures and their source are in Performance.
Traceable answers. Every
queryresponse reports the retrieval rung it answered from (retrieval.rung,retrieval.reason) and afreshnessblock, so a consumer can tell an exact match from a fallback and a current index from a stale one.Access control on the server. Viewer, Contributor and Admin roles are declared and enforced per HTTP route. Network listeners require a bearer token, and a non-loopback bind is refused without one.
Deployment control. One CGO-free binary and a container image. SQLite needs no database server. PostgreSQL with pgvector is the opt-in for shared, server-scale deployments.
Without a code graph | With LeanKG |
Many tool calls and large context windows | A targeted subgraph per question |
No blast radius before a change | Impact analysis (breadth-first search over |
Keyword search only | Exact, keyword, and semantic ladder; degrades to what is indexed when vectors are missing |
One repository at a time | Multi-project server; each request selects its project |
Open access to the code graph | Bearer tokens, role floors per route, refusal of unauthenticated non-loopback binds |
Related MCP server: RAG Knowledge Graph MCP
At a glance
Area | Value | Evidence |
Language profiles | 40 |
|
MCP tools | 4: | |
Access roles | 3: Viewer, Contributor, Admin | |
Storage engines | 2: SQLite (default), PostgreSQL + pgvector (opt-in) | |
Embedding providers | 3: | |
Transports | MCP (stdio, streamable HTTP), REST, ConnectRPC (gRPC, gRPC-Web, JSON), web UI |
|
Agent client targets | 6 JSON-config clients ( | |
Release binaries | linux and darwin, amd64 and arm64, each with a |
Get Started
Three commands take a repository from nothing to an agent that can query it.
# 1. Install the CLI and server (or use a prebuilt archive, see Installation)
go install github.com/FreePeak/LeanKG/cmd/leankg@latest
# 2. Index the repository. Writes .leankg/leankg.db (SQLite). In a git repo root,
# the HEAD commit's objects are read, so uncommitted and ignored files are not indexed.
cd your-project
leankg index .
# 3. Wire an AI client: claude-code | cursor | codex | gemini | opencode | omp
leankg install --target claude-codeRestart the client so it picks up the new MCP entry. The stdio entry is serve --stdio --memory, which gives the agent the code graph and the markdown memory layer (per project, at <project>/.leankg/memory) in one server.
Serve over HTTP instead (one server, many clients):
leankg serve --http 127.0.0.1:9699 --rest 127.0.0.1:8080 --memory
leankg install --target claude-code --http --url http://127.0.0.1:9699/mcpMCP is served at /mcp; GET /health returns 200 when the server is ready. The HTTP server resolves its project from the process working directory, or from --project DIR.
Semantic search (optional). Exact and keyword matches work with no extra setup. Semantic (L3) search needs embeddings: set LEANKG_EMBED_PROVIDER (see docs/embedding.md and .env.example). leankg index then embeds incrementally after indexing; an embedding failure is reported and does not fail the index.
Self-check any deployment: leankg doctor prints the store path, element and file counts, and the write watermark (exit 0 pass, 2 fail). leankg doctor --deep runs the extended checks.
Enterprise readiness
The table lists only capabilities that exist in this repository today. Each row links to the code that implements it. Items that are not implemented are listed under Current limits for enterprise evaluation rather than omitted.
Security and access control
Capability | How it works | Evidence |
Role model | Viewer (read), Contributor (writes such as import and memory writes), Admin (management actions) | |
Role floors per route | Every route on a gated listener declares its role at registration: | |
Bearer tokens | Opaque | |
Admin bootstrap |
| |
Password storage | PBKDF2-HMAC-SHA256 at 600,000 iterations (standard library) | |
Login throttling | After 5 consecutive failures for a username, | |
Exposure guard |
| |
Read-only serving |
|
|
Scale and multi-repo
Capability | How it works | Evidence |
Multi-project server |
| |
Fail-closed project selection | On a multi-project server, the MCP | |
Shared database backend | PostgreSQL with pgvector ( |
|
Per-repository stores | SQLite (WAL) store per repository at |
|
Deployment and operations
Capability | How it works | Evidence |
Single binary | CGO-free build ( | |
Container image | Three-stage build; runs as an unprivileged user (uid 10001); | |
Health endpoint |
| |
Diagnostics |
| |
Self-update channel |
| |
Telemetry | Capture is off by default and needs explicit consent in | |
Embedding providers |
|
Governance and traceability
Capability | How it works | Evidence |
Incidents and ownership |
| |
Environment governance |
| |
Requirement traceability |
| |
Ontology | Concept catalog and workflows shipped in | |
Secret redaction | A shared redaction helper ( |
Current limits for enterprise evaluation
These are the gaps a buyer is likely to ask about. None of them is claimed as implemented.
No SSO. There is no OIDC, SAML or SCIM integration in the repository. Users are local accounts with bearer tokens.
No TLS in the server. The HTTP, REST and RPC listeners do not terminate TLS. Put them behind a TLS-terminating reverse proxy.
Audit ledger is not wired. The store has a hash-chained audit ledger, and
leankg audit exportandleankg audit verifyread and check it. The Go runtime does not append events to it yet:AppendAuditis called only from tests (internal/store/store_audit.go,cmd/leankg/audit.go).No encryption at rest by LeanKG. The SQLite store and the PostgreSQL schema are not encrypted by the application. Use disk or database encryption.
No SIEM export, no compliance attestations. This repository makes no SOC 2, ISO 27001 or GDPR claim.
No hosted service. This repository ships software only. Deployments are self-hosted.
stdio is not gated. The stdio transport is a local subprocess and runs as Admin (
AGENTS.md).
How it works
LeanKG indexes a repository into a graph of elements (files, functions, types, modules) and their relationships (contains, calls, imports, references). Extraction uses a regex tier that is always available; a tree-sitter tier is built behind the tstree build tag, and ast-grep is used when its CLI is on PATH. Language servers, when configured, start lazily at query time and stop after an idle TTL.
Queries go down a ladder. L1 is an exact identifier match. L2 is keyword and fuzzy matching (FTS5 on SQLite, full-text on PostgreSQL). L3 is semantic search over embeddings, with keyword and vector ranks fused by reciprocal rank fusion. A natural-language question starts at L3 when L1 misses. If a rung is unavailable (for example, no embeddings yet), the answer comes from the next rung down and says so in retrieval.
Every transport calls the same core. The stdio and HTTP MCP servers, the REST API, the ConnectRPC service and the web UI are thin layers over one engine, so the same question gets the same answer whichever door it came through. The team layer (memory, incidents, ownership, environments, requirements) lives in the same store as the code graph.
Supported AI clients and MCP surface
The MCP surface is four tools. Discovery goes through query, which routes the ladder by default.
Question | Call |
Any identifier (default) |
|
Who calls X? |
|
Blast radius of a change |
|
How does A reach B? |
|
Element details |
|
Pattern search |
|
Requirement trace |
|
Read a file (compressed) |
|
Session start memory |
|
Session end retain |
|
Health and freshness |
|
Log in over HTTP |
|
Client wiring is one command per client: leankg install --target <client> (or leankg connect <client>, the same writer). Add --http --url <url> for an HTTP entry.
Deployment models
Model | What it is | Notes |
Developer or CI | The | No database server, no Docker |
Shared team server (self-hosted) |
| Non-loopback binds need a token. Put TLS in front of it |
Shared database | PostgreSQL with pgvector ( | Opt-in; the default flow does not touch PostgreSQL |
Container |
| This is the image behind the public demo. It is not a production deployment template |
Hosted or managed | Not provided by this repository |
Performance
Figures below come from the project's own A/B benchmark and are labelled with their source. They were measured on the archived Rust-era vector-engine gate and have not been re-run against the current Go engine for this README.
Metric | Result | Source |
Input tokens | -65.0% | docs/archive/prd.md line 597 (100 tasks, A/B) |
Tool calls | -84.6% | docs/archive/prd.md line 597 (100 tasks, A/B) |
Speedup for agents | 2.50x | docs/archive/prd.md line 597 (100 tasks, A/B) |
Cold time-to-first-value (Go) | 17.8 s with a cold build cache, on the project's macOS ARM64 self-hosted runner; CI budget 300 s |
|
Further analyses are archived: competitive analysis, ROI comparison, research matrix.
Languages
40 language profiles are registered in the engine. Every profile gets the regex extractor. Tree-sitter, ast-grep and language-server tiers apply where available (see internal/langs/langs.go).
Go, Rust, TypeScript, TSX, JavaScript, JSX, Python, Markdown, Java, Kotlin, Swift, Objective-C, Dart (Flutter), C, C++, C#, PHP, Ruby, Scala, Perl, Lua, Haskell, Elixir, Crystal, CUDA, Cypher, Elm, Erlang, F#, GLSL, HLSL, Nim, OCaml, SQL (PostgreSQL, T-SQL and PL/SQL dialects), PowerShell, Q#, Solidity, SystemVerilog, Verilog, Zig
CLI reference
Full usage: leankg help or leankg <command> --help.
leankg index . # index + incremental embed -> .leankg/leankg.db (--no-embed skips the embed)
leankg index <dir> --hook # SessionStart mode: skips over LEANKG_HOOK_MAX_FILES (10000) files or LEANKG_HOOK_MAX_EMBED (500) elements needing vectors
leankg writer --project <dir> # index once, then watch; a git-backed store re-indexes on each new commit
leankg query "parseConfig" # name lookup (exact, then fuzzy), JSON output
leankg query "parseConfig" --compress # one line per result
leankg impact src/main.go --depth 3 # blast radius of a file or element
leankg status # health, inventory, freshness, embed state
leankg doctor # store path, element and file counts, watermark
leankg install --target cursor # client wiring (--register-cwd adds an async claude-code SessionStart hook)
leankg serve --stdio # MCP over stdio (what harnesses spawn)
leankg serve --http 127.0.0.1:9699 # MCP over streamable HTTP (/mcp, /health)
leankg serve --rest 127.0.0.1:8080 # REST API (/health, /api/v1/*)
leankg serve --rpc 127.0.0.1:9090 # ConnectRPC (gRPC + gRPC-Web + JSON)
leankg serve --ui 127.0.0.1:8081 # embedded dashboard (its /api/* data API is served here)
leankg serve --read-only # reader role: store opened read-only
leankg auth token create # mint a bearer token
leankg auth admin init # create the site-admin account (writes LEANKG_ADMIN_* to .env)
leankg audit export | verify # read and check the audit ledger (see Current limits)
leankg prd --source docs/prd.md # ingest requirements
leankg prd-trace FR-3T-01 # trace a requirement to code
leankg incident add | list | show # incidents
leankg team-map # ownership map
leankg update --check # check for a newer release
leankg versionleankg-embed run # incremental embed
leankg-embed full # stamp-guarded full rebuild (after a model or stamp change)
leankg-embed status
leankg-embed export | import # NDJSON offsite flow (pairs with scripts/hf-embed.sh)A non-loopback bind is refused. leankg serve --http/--rest/--rpc <non-loopback> exits with an error unless a bearer token is configured. With no token configured, every caller would resolve to Admin, which would expose the project graph, the file reader and the memory write path to the network. Either bind a loopback address (the default), or configure a token first with leankg auth token create, or with LEANKG_TOKEN_ADMIN, LEANKG_TOKEN_CONTRIBUTOR or LEANKG_TOKEN_VIEWER. A configured site-admin account also counts as a token. See Auth and the HTTP gate.
Authentication flow. A client calls authenticate with {"username": ..., "password": ...} and receives {"token": "lkg_...", "role": "admin", "expires_at": "<RFC3339>"}. Later requests send Authorization: Bearer <token>. With the gate on, a request with no Authorization header can reach only the protocol handshake, tools/list, and authenticate. A request with an invalid or expired token gets HTTP 401. The REST and ConnectRPC surfaces have no login tool, so they need a token minted with leankg auth token create.
Environment variables. LEANKG_DB_ENGINE and LEANKG_PG_URL select the store. LEANKG_PROJECT_DIRS registers several projects. LEANKG_EMBED_PROVIDER and LEANKG_EMBED_* configure embeddings. LEANKG_TOKEN_ADMIN, LEANKG_TOKEN_CONTRIBUTOR and LEANKG_TOKEN_VIEWER configure bearer tokens. The full list, with examples, is in .env.example.
Installation
Prebuilt archives. Releases carry leankg-<os>-<arch>.tgz for linux and darwin on amd64 and arm64. Each archive holds both binaries at its root, with a .sha256 file alongside. leankg update follows the same channel.
Go toolchain. Requires Go 1.25+:
go install github.com/FreePeak/LeanKG/cmd/leankg@latest # server and CLI
go install github.com/FreePeak/LeanKG/cmd/leankg-embed@latest # embedding pipelineFrom a checkout. Requires Go 1.25+ and git. Installs to ~/.local/bin by default; pass a PREFIX to change it:
git clone https://github.com/FreePeak/LeanKG.git && cd LeanKG
scripts/install-go.sh # or: make install-goContainer. Dockerfile builds the demo image (see Deployment models):
docker build -t leankg .
docker run --rm -p 8080:10000 -e PORT=10000 leankg # dashboard and its /api on :8080Known limits
Call edges are resolved by name within a directory. There is no import or type resolution, so a same-name call in the same directory resolves, and cross-package dispatch is best-effort. The upgrade path is tree-sitter symbol tables. See
internal/index/relations.go.Heuristic guards in the indexer: files of 1 MiB or more are skipped as vendored or minified bundles (
internal/index/index.go); call targets shorter than 4 characters are dropped as noise, and outgoing calls are capped per element (40) and per file (500) (internal/index/relations.go).The unit of scope is a repository. A portfolio root (tens of thousands of nested files) is not a project; register its child repositories one at a time.
--uibinds an unauthenticated data API (query, read and import routes). Bind it to loopback or front it with a proxy. The public demo container serves it--read-onlyagainst a disposable baked graph. Its/api/filereader needs a Viewer token when the gate is on, and answers 403 on a non-loopback bind when the gate is off.
Troubleshooting
Issue | Fix |
Wrong project served | Start the server with |
Embeddings or a cold embed |
|
| The server was started with |
Server refuses to start on a non-loopback address | Bind |
Query on a multi-project server is refused | Pass the |
Requirements: macOS or Linux. Go 1.25+ is needed only when building from source. No Docker and no PostgreSQL are needed for the default SQLite store.
Documentation
The documentation set lives in docs/: a single unified PRD (docs/prd.md) and task tracker (docs/prd-task-tracker.md). Historical design documents, analyses, reports and plans are preserved under docs/archive/.
Document | Contents |
Unified product requirements and high-level design (single source of truth) | |
Done, in progress, to do | |
Providers, EmbeddingGemma 2 bulk path, variable list | |
Consent-gated capture and transcript linking | |
Design and data model (historical) | |
Tool catalog (historical) | |
All commands (historical) | |
Methodology (historical) | |
Agent context, build and test commands, auth model | |
How to report a vulnerability |
Enterprise contact
[Contact placeholder - replace with sales email or form URL]
Contributing
Fork, then work on a feature branch (a git worktree is preferred).
Update the docs when behavior changes:
docs/prd.mdanddocs/prd-task-tracker.md.Run
make go-build,make go-testandmake go-vet. Storage-layer changes also needmake dual-engine, which needs a PostgreSQL with pgvector on port 5433.Open a pull request with a summary and a test plan. The
mainbranch is protected and changes land through pull requests.
See CONTRIBUTING.md and CODE_OF_CONDUCT.md.
License
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Cuts coding agent token burn up to 72% continuously via contradiction-free memory & verification.
The open-source knowledge graph for finance: your ledger and 8,000+ public companies' XBRL filings
Deterministic verifier: LLM proposes, graph verifies. Sub-ms, offline, 0 tokens.
100+ pay-per-call tools: token risk, wallet sanctions screening, onchain data, web, company, AI
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceBuild Real-Time Knowledge Graphs for AI Agents32,946Apache 2.0
- AlicenseNot gradedqualityCmaintenanceRAG Knowledge Graph - MCP server providing AI-powered tools and automation by MEOK AI Labs8 npm30 PyPIMIT
- AlicenseNot gradedqualityDmaintenanceEnables AI coding agents to query a pre-built semantic knowledge graph of code, reducing token usage and tool calls. Supports 16 tools for code exploration, analysis, and context building.24 npm9MIT
- AlicenseNot gradedqualityCmaintenanceEnables Claude Code to query codebase knowledge graphs directly, reducing token usage 5x–71x by reading a compact graph.json instead of raw files.3MIT