kgn

March 31, 2026 · View on GitHub

English | 한국어

KGN — Knowledge Graph Node

CI PyPI version Python 3.12+ License: MIT codecov Tests Code style: ruff

Manage your AI agent's knowledge — parse, store, query, and collaborate.

KGN is a developer-friendly CLI + MCP server for teams building with AI agents. Write knowledge nodes in simple YAML+Markdown files (.kgn), define relationships between them (.kge), and let KGN handle storage, similarity search, conflict detection, and multi-agent task handoffs — all backed by PostgreSQL + pgvector.

Hybrid architecture: PostgreSQL is the local working engine; GitHub is the long-term source of truth. Export, commit, and push in one command.


Table of Contents


Architecture

For a deep dive into KGN's internal design — layer structure, module dependencies, database schema, data flows, and more — see the full Architecture Guide with 16 interactive Mermaid diagrams.

graph LR
    A[".kgn / .kge"] --> B["Parser"]
    B --> C["IngestService"]
    C --> D[("PostgreSQL<br/>+ pgvector")]
    D --> E["CLI · MCP · LSP · Web"]
    E --> F["Git / GitHub Sync"]

Why KGN?

AI agents are powerful, but they forget everything between sessions — and when multiple agents collaborate, they can conflict, duplicate work, or lose track of decisions.

KGN gives your agents a shared, queryable memory:

ProblemKGN Solution
Agents forget past decisionsPersistent knowledge graph in PostgreSQL
Duplicate work across agentsConflict detection + similarity search
No task coordinationBuilt-in task queue with lease management
Hard to audit agent actionsStructured activity log per agent
Context window overflowSubgraph extraction — only what's relevant
IDE friction for .kgn filesVS Code extension with LSP support

Quick Start

📖 New to KGN? Follow the step-by-step Getting Started Guide ( 한국어 ) — no prior experience required.

Install

pip install kgn-mcp

Start Database

git clone https://github.com/baobab00/kgn.git && cd kgn
docker compose -f docker/docker-compose.yml up -d postgres

First Run

kgn init --project my-project
kgn ingest examples/ --project my-project --recursive
kgn status --project my-project
Embedding Provider Setup

To use embedding features, set your OpenAI API key in the .env file:

# .env
KGN_OPENAI_API_KEY=sk-your-api-key-here
KGN_OPENAI_EMBED_MODEL=text-embedding-3-small    # default

If the API key is not set, ingest works normally and embedding is silently skipped (graceful degradation).

# Test provider connection
kgn embed provider test
Docker All-in-One

Run PostgreSQL + kgn CLI together with Docker:

docker compose -f docker/docker-compose.yml up -d --build
docker compose -f docker/docker-compose.yml exec kgn kgn init --project my-project
docker compose -f docker/docker-compose.yml exec kgn kgn --help

Place .kgn/.kge files in docker/workspace/ directory.


MCP Server (Claude Integration)

The MCP (Model Context Protocol) server enables Claude to directly read, write, and manage tasks in the knowledge graph.

# stdio mode (Claude Desktop / Claude Code default)
kgn mcp serve --project my-project

# HTTP SSE mode
KGN_MCP_TRANSPORT=sse KGN_MCP_PORT=8000 kgn mcp serve --project my-project

# streamable-http mode
KGN_MCP_TRANSPORT=streamable-http kgn mcp serve --project my-project

Claude Desktop integration — add to claude_desktop_config.json:

{
  "mcpServers": {
    "kgn": {
      "command": "uv",
      "args": ["run", "kgn", "mcp", "serve", "--project", "my-project"]
    }
  }
}
MCP Tools (12 tools)
ToolCategoryDescription
get_nodeReadGet node by ID
query_nodesReadSearch nodes in project (type/status filter)
get_subgraphReadBFS subgraph extraction from node
query_similarReadVector similarity Top-K search
task_checkoutTaskCheck out highest-priority task (with auto lease recovery)
task_completeTaskMark task as complete (auto-unblocks dependent tasks)
task_failTaskMark task as failed
workflow_listWorkflowList registered workflow templates
workflow_runWorkflowExecute a workflow template (creates subtask DAG)
ingest_nodeWriteIngest node from .kgn string
ingest_edgeWriteIngest edge from .kge string
enqueue_taskWriteEnqueue TASK node
Git/GitHub Sync
# Export DB → filesystem (+ auto-generate Mermaid README)
kgn sync export --project my-project --target ./sync

# Import filesystem → DB
kgn sync import --project my-project --source ./sync

# Push/pull to GitHub
kgn sync push --project my-project --target ./sync
kgn sync pull --project my-project --target ./sync

# Mermaid visualization
kgn graph mermaid --project my-project
kgn graph readme --project my-project --target ./sync

# Branch/PR management
kgn git branch list --target ./sync
kgn git pr create --project my-project --target ./sync --title "PR title"
Web Dashboard
pip install kgn-mcp[web]
kgn web serve --project my-project --port 8080

Open http://localhost:8080 — Graph View, Task Board, Health Dashboard, Search & Filter.

VS Code Extension
code --install-extension baobab00.vscode-kgn
pip install kgn-mcp[lsp]    # for LSP features

Syntax Highlighting, Diagnostics, Auto-completion, Hover, Go to Definition, CodeLens, Subgraph Preview.

Error Code System

All MCP error responses are returned as structured JSON:

{
  "error": "Error message",
  "code": "KGN-300",
  "detail": "Detailed description",
  "recoverable": false
}
CodeCategoryDescriptionRetryable
KGN-100InfrastructureDatabase connection failed
KGN-101InfrastructureEmbedding provider unavailable
KGN-200IngestYAML front matter parse error
KGN-201IngestRequired field missing
KGN-202IngestInvalid field value
KGN-300QueryNode not found
KGN-301QueryInvalid UUID format
KGN-302QuerySubgraph depth limit exceeded
KGN-400TaskNo READY tasks available
KGN-401TaskTask not in expected state
KGN-402TaskLease expired
KGN-999InternalUnexpected server error

Multi-Agent Orchestration

KGN supports multi-agent collaborative workflows where multiple AI agents work together on a knowledge graph with role-based access control, task handoff, and conflict resolution.

  • 5 Agent Roles — genesis, worker, reviewer, indexer, admin with role-based access control
  • 3 Workflow Templates — design-to-impl, issue-resolution, knowledge-indexing
  • Task Handoff — Automatic context propagation between workflow steps
  • Advisory Locking — Prevents concurrent modifications to the same node
  • Conflict Resolution — Detects conflicts and auto-creates review tasks
  • Observability — Agent activity timeline, task flow stats, bottleneck detection
Agent Roles & Workflow Details
RoleCreateCheckoutDescription
genesisGOAL, SPEC, ARCH, CONSTRAINT, ASSUMPTIONProject bootstrapping
workerSPEC, ARCH, LOGIC, TASK, SUMMARY✅ (role-filtered)Implementation work
reviewerDECISION, ISSUE, SUMMARY✅ (role-filtered)Code review & decisions
indexerSUMMARYKnowledge indexing
adminAll types✅ (all tasks)Full access
TemplateStepsDescription
design-to-implGOAL → SPEC → ARCH → TASK(impl) → TASK(review)Full design-to-implementation pipeline
issue-resolutionISSUE → TASK(fix) → TASK(verify)Bug fix workflow
knowledge-indexingGOAL → TASK(index) → TASK(review)Knowledge capture pipeline
kgn agent list --project my-project
kgn agent role --project my-project --agent-id <uuid> --role worker
kgn agent stats --project my-project --agent-id <uuid>
kgn agent timeline --project my-project --agent-id <uuid>

CLI Commands

Run kgn --help for the full command list.

Key commands summary:

GroupExampleDescription
Corekgn init, kgn ingest, kgn status, kgn healthInitialize, ingest, status, health
Querykgn query nodes, kgn query subgraph, kgn query similarSearch, subgraph, similarity
Taskkgn task enqueue/checkout/complete/fail/list/logTask orchestration
Embedkgn embed, kgn embed provider testEmbedding management
Conflictkgn conflict scan/approve/dismissConflict detection/management
Synckgn sync export/import/status/push/pullDB ↔ file ↔ GitHub sync
Gitkgn git init/status/diff/log/branch/prGit/GitHub management
Graphkgn graph mermaid/readmeMermaid visualization
MCPkgn mcp serveMCP server (stdio/sse/streamable-http)
Agentkgn agent list/role/stats/timelineMulti-agent orchestration
Webkgn web serveWeb visualization dashboard
LSPkgn lsp serveLanguage Server (VS Code integration)
Expired Task Recovery

When a checked-out task exceeds its lease_expires_at, it is considered expired. requeue_expired resets expired IN_PROGRESS tasks to READY and increments attempts.

  • MCP: checkout automatically calls requeue_expired beforehand
  • CLI: Manual invocation or cron schedule required
  • When max_attempts (default 3) is exceeded, the task transitions to FAILED

File Formats

.kgn — Knowledge Graph Node
---
kgn_version: "0.1"
id: "new:my-node"        # UUID or new:slug
type: SPEC               # GOAL, ARCH, SPEC, LOGIC, DECISION, ISSUE, TASK, CONSTRAINT, ASSUMPTION, SUMMARY
title: "Node title"
status: ACTIVE            # ACTIVE, DEPRECATED, SUPERSEDED, ARCHIVED
project_id: "my-project"
agent_id: "my-agent"
tags: ["tag1", "tag2"]
confidence: 0.9
---

## Context
...
## Content
...
.kge — Edge Definition
---
kgn_version: "0.1"
project_id: "my-project"
agent_id: "my-agent"
edges:
  - from: "new:node-a"
    to:   "new:node-b"
    type: DEPENDS_ON      # DEPENDS_ON, IMPLEMENTS, RESOLVES, SUPERSEDES, DERIVED_FROM, CONTRADICTS, CONSTRAINED_BY
    note: "Edge description"
---

See examples/ directory for practical .kgn and .kge file examples.

Development

# Lint
uv run ruff check .

# Format
uv run ruff format .

# Test
uv run pytest --tb=short -q

# Coverage
uv run pytest --cov=kgn --cov-report=term-missing

Tech Stack

LayerTechnology
LanguagePython 3.12+
CLITyper + Rich
DBPostgreSQL 16 + pgvector
ORM/SQLpsycopg3 (native async-ready)
ValidationPydantic v2
AI ProtocolMCP 1.26.0 via FastMCP
EmbeddingsOpenAI text-embedding-3-small (optional)
Git/GitHubbidirectional sync (DB \u2194 GitHub)
Loggingstructlog (JSON / console)
WebFastAPI + Uvicorn + Jinja2 + Cytoscape.js (optional extra)
IDEVS Code extension + pygls LSP (optional extra)
InfraDocker Compose + GitHub Actions CI
Qualityruff + pytest (2081+ tests, 93%+ coverage)

License

MIT