JSPM

  • Created
  • Published
  • Downloads 197
  • Score
    100M100P100Q94633F
  • License MIT

Self-hosted knowledge graph server for AI coding agents

Package Exports

    This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@ossrandom/kgraph) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

    Readme

    kgraph

    A self-hosted knowledge graph server for AI coding agents

    CI & Publish GitHub Package License: MIT Bun MCP

    Agents naturally build and maintain a graph of interconnected project knowledge as they work.
    The graph persists across sessions, is scoped per project, and is accessible from any device via MCP, REST API, and a web UI.

    Quick StartHow It WorksMCP ToolsREST APIWeb UICLI


    Why kgraph?

    Every AI coding session starts from zero. Your agent discovers the same patterns, re-learns the same decisions, and asks the same questions — session after session.

    kgraph fixes this. It gives your agents persistent, interconnected memory that grows automatically.

    Without kgraph With kgraph
    Agent starts every session from scratch Agent starts with full project context injected
    Decisions are lost when the session ends Decisions are captured as linked notes
    Knowledge lives in one person's head Knowledge is a searchable, navigable graph
    Context must be manually curated in CLAUDE.md Context builds itself via hooks — zero config

    Key Principles

    • Zero-config for developers — Global hooks auto-detect your project via git remote. No marker files, no config files in repos, no CLAUDE.md instructions.
    • One server, one port — Serves MCP + REST API + Web UI + Hook endpoints. Single Bun/TypeScript process on your VPS.
    • Files are the source of truth — Notes are plain markdown with [[wikilinks]]. SQLite is a derived index for search and traversal.
    • Project isolation — Each project gets its own database and notes directory. Completely independent.
    • 2 runtime dependencies@modelcontextprotocol/sdk + gray-matter. Everything else is built-in.

    Architecture

    graph TB
        subgraph clients["Any Machine"]
            CC["Claude Code"]
            VS["VS Code"]
            COP["Copilot CLI"]
            CDX["Codex CLI"]
            MCP_C["Any MCP Client"]
            BR["Browser"]
        end
    
        subgraph hooks["Global Hooks (bash + curl)"]
            H["hook.sh<br/>reads git remote from cwd"]
        end
    
        subgraph server["VPS — kgraph server"]
            subgraph endpoints["Single Port"]
                MCP_E["/mcp<br/>Streamable HTTP"]
                HOOK_E["/api/hook/*<br/>Hook Endpoints"]
                API_E["/api/*<br/>REST API"]
                UI_E["/*<br/>Web UI"]
            end
    
            subgraph core["Core Engine"]
                PM["Project Manager<br/>+ Remote Registry"]
                GE["Graph Engine<br/>+ BFS Traversal"]
                FW["File Watcher<br/>fs.watch"]
            end
    
            subgraph storage["Per-Project Storage"]
                DB["SQLite<br/>notes | links | notes_fts"]
                MD["Markdown Files<br/>source of truth"]
            end
        end
    
        CC --> H
        VS --> H
        COP --> H
        CDX --> H
        H --> HOOK_E
        MCP_C --> MCP_E
        BR --> UI_E
        BR --> API_E
    
        MCP_E --> core
        HOOK_E --> core
        API_E --> core
        UI_E -.-> API_E
    
        PM --> DB
        GE --> DB
        FW --> MD
        FW --> DB
        core --> storage
    
        style clients fill:#1a1a2e,stroke:#6ee7b7,color:#e0e0e0
        style hooks fill:#16213e,stroke:#7dd3fc,color:#e0e0e0
        style server fill:#0f0f0f,stroke:#6ee7b7,color:#e0e0e0
        style endpoints fill:#141414,stroke:#6ee7b7,color:#e0e0e0
        style core fill:#141414,stroke:#7dd3fc,color:#e0e0e0
        style storage fill:#141414,stroke:#fcd34d,color:#e0e0e0

    Quick Start

    1. Deploy

    # Docker (recommended for production)
    docker run -d -p 3000:3000 -v kgraph-data:/data ghcr.io/randomcodespace/kgraph
    
    # Or run directly with Bun
    bun run src/index.ts serve
    
    # Or with Node.js
    node --import tsx src/index.ts serve

    2. Configure

    # Add to ~/.bashrc or ~/.zshrc
    export KGRAPH_SERVER=https://kgraph.yourdomain.com
    export KGRAPH_API_KEY=your-api-key

    3. Install Global Hooks

    kgraph hooks install --global             # all detected platforms
    kgraph hooks install --global --claude     # Claude Code only
    kgraph hooks install --global --vscode     # VS Code Copilot only
    kgraph hooks install --global --codex      # Codex CLI only

    4. Register a Project

    cd ~/projects/trading-platform
    kgraph project register                    # auto-detects git remote

    5. Done

    Open any AI coding tool in the repo. kgraph is invisible — it injects context on session start and captures knowledge on session end. Open the web UI to explore the graph your agents have built.


    How It Works

    Project Identity via Git Remote

    Every project is identified by its git remote URL. No config files needed — every repo already has one, and it's the same on every machine.

    All of these resolve to the same project:

    git@github.com:amit/trading-platform.git        ─┐
    https://github.com/amit/trading-platform.git      ├─► github.com/amit/trading-platform
    https://github.com/amit/trading-platform           │
    ssh://git@github.com/amit/trading-platform.git   ─┘

    Session Lifecycle

    sequenceDiagram
        participant Dev as Developer
        participant Agent as AI Agent
        participant Hook as hook.sh
        participant KG as kgraph Server
        participant DB as Project DB
    
        Dev->>Agent: Opens IDE in ~/projects/trading-platform/
    
        Note over Hook: SessionStart fires
        Hook->>Hook: git remote get-url origin
        Hook->>KG: POST /api/hook/SessionStart<br/>{remote: "git@github.com:..."}
        KG->>DB: Lookup project, query recent notes
        DB-->>KG: Last 10 notes
        KG-->>Hook: {additionalContext: "## Project Knowledge..."}
        Hook-->>Agent: Context injected
    
        Note over Agent: Agent works with full project context
        Agent->>Agent: Makes decisions, discovers patterns
    
        Note over Hook: Stop fires (async)
        Hook->>KG: POST /api/hook/Stop<br/>{remote: "...", transcript_path: "..."}
        KG->>KG: Extract decisions from session
        KG->>DB: Write/update notes with [[wikilinks]]
        KG-->>Hook: {ok: true}
    
        Note over DB: Graph updated automatically

    Data Model

    Notes are plain markdown files with optional YAML frontmatter. [[wikilinks]] create graph edges.

    ---
    author: architect
    tags: [auth, security]
    created: 2026-04-06T10:30:00Z
    ---
    
    Using JWT with refresh tokens for stateless auth.
    
    Decision driven by [[security-constraints]] requirement
    for stateless auth across [[api-gateway]] instances.
    
    See [[api-design]] for endpoint authorization patterns.

    Example Knowledge Graph

    graph LR
        A["auth-strategy<br/><i>architect</i>"] -->|"[[security-constraints]]"| B["security-constraints<br/><i>architect</i>"]
        A -->|"[[api-gateway]]"| C["api-gateway<br/><i>developer</i>"]
        A -->|"[[api-design]]"| D["api-design<br/><i>architect</i>"]
        D -->|"[[database-schema]]"| E["database-schema<br/><i>developer</i>"]
        D -->|"[[api-gateway]]"| C
        C -->|"[[monitoring]]"| F["monitoring<br/><i>reviewer</i>"]
        E -->|"[[migration-plan]]"| G["migration-plan<br/><i>developer</i>"]
        B -->|"[[compliance-audit]]"| H["compliance-audit<br/><i>reviewer</i>"]
    
        style A fill:#1a2e1a,stroke:#6ee7b7,color:#e0e0e0
        style B fill:#1a2e1a,stroke:#6ee7b7,color:#e0e0e0
        style C fill:#1a1a2e,stroke:#7dd3fc,color:#e0e0e0
        style D fill:#1a2e1a,stroke:#6ee7b7,color:#e0e0e0
        style E fill:#1a1a2e,stroke:#7dd3fc,color:#e0e0e0
        style F fill:#2e2e1a,stroke:#fcd34d,color:#e0e0e0
        style G fill:#1a1a2e,stroke:#7dd3fc,color:#e0e0e0
        style H fill:#2e2e1a,stroke:#fcd34d,color:#e0e0e0

    Nodes are colored by author role: architectdeveloperreviewer

    Data Rules

    Rule Detail
    Source of truth Markdown files on disk
    SQLite Derived index — rebuilt from files on startup
    Wikilinks [[key]] creates a directed edge in the graph
    Resolution Wikilinks resolve by filename first, then explicit path
    Folders Notes nest in folders: architecture/auth-strategy
    Frontmatter Optional YAML — author, tags, created, updated, version
    Isolation Each project has its own index.db and notes/ directory

    MCP Tools

    Connect any MCP-compatible client to your server:

    # Claude Code
    claude mcp add kgraph --type streamable-http --url https://kgraph.yourdomain.com/mcp
    
    # Claude Desktop — add to claude_desktop_config.json
    {
      "mcpServers": {
        "kgraph": {
          "type": "streamable-http",
          "url": "https://kgraph.yourdomain.com/mcp"
        }
      }
    }

    Available Tools

    Tool Input Description
    list_projects List all projects with note/link counts
    list_notes project List all notes in a project with metadata
    read_note project, key Read note content + outlinks + backlinks
    search_notes project, query Full-text search with ranked snippets
    write_note project, key, content, author?, tags? Create or update a note
    get_related project, key, depth? BFS traversal — returns subgraph
    delete_note project, key Delete a note and its links

    REST API

    All endpoints under /api/, authenticated via Authorization: Bearer <key> header.

    Projects

    Method Endpoint Description
    GET /api/projects List all projects
    POST /api/projects/register Register project { remote, name? }
    POST /api/projects/:project/add-remote Attach additional remote { remote }

    Notes

    Method Endpoint Description
    GET /api/projects/:project/notes List all notes
    GET /api/projects/:project/notes/*key Read note + backlinks + outlinks
    PUT /api/projects/:project/notes/*key Create/update { content, author?, tags? }
    DELETE /api/projects/:project/notes/*key Delete note
    Method Endpoint Description
    GET /api/projects/:project/graph Full graph { nodes[], edges[] }
    GET /api/projects/:project/tree Nested folder tree
    GET /api/projects/:project/search?q=... Full-text search
    GET /api/projects/:project/related/*key?depth=2 BFS subgraph traversal

    Folders

    Method Endpoint Description
    POST /api/projects/:project/folders Create folder { path }
    DELETE /api/projects/:project/folders/*path Delete folder (recursive)
    POST /api/projects/:project/move Move note/folder { from, to }

    Web UI

    Open https://kgraph.yourdomain.com in any browser.

    Features

    • Force-directed graph — Custom SVG layout with zoom (0.2x-5x), pan, node selection with glow halo, and connected-node highlighting
    • Folder tree sidebar — Collapsible hierarchy with author color dots and link count badges. Right-click for new note, new folder, rename, delete
    • Note viewer — Rendered markdown with clickable [[wikilinks]], tag pills, author badge, breadcrumb navigation
    • Note editor — Monospace markdown editing with author/tags fields
    • Link panel — Outlinks and backlinks displayed as clickable cards
    • Search — Filters both the graph and sidebar in real-time
    • Mobile — Tab-based layout (Graph / Notes / Note) below 720px with pinch zoom

    Theme

    Dark theme optimized for developer workflows:

    Background:  #0a0a0a          Font:  Inter + JetBrains Mono
    Surface:     #0f0f0f          Body:  15px / 1.85 line-height
    Accent:      #6ee7b7          Code:  14px monospace

    Author colors: architectdeveloperreviewer


    CLI Reference

    Usage:
      kgraph serve [--port <port>]              Start server (default: 3000)
      kgraph project register [remote] [--name] Register current repo
      kgraph project add-remote <name> <remote> Attach another remote
      kgraph project list                       List all projects
      kgraph hooks install --global [--platform] Install global hooks
      kgraph --version                          Show version
      kgraph --help                             Show help

    Hook Installation Flags

    --claude      # ~/.claude/settings.json
    --vscode      # VS Code user settings
    --copilot     # Copilot CLI hooks config
    --codex       # ~/.codex/hooks.json
    --all         # All detected platforms (default)

    Platform Compatibility

    Platform SessionStart Stop MCP Tools Hook Format
    Claude Code ✅ async ~/.claude/settings.json
    VS Code Copilot VS Code user settings
    Copilot CLI .github/hooks/
    Codex CLI ~/.codex/hooks.json
    Cursor ⚠️ partial .cursor/mcp.json

    The same hook.sh script works across all platforms — only the settings file format differs.


    Configuration

    Environment Variables

    Variable Default Description
    KGRAPH_DATA_DIR ~/.kgraph Data directory for databases and notes
    KGRAPH_PORT 3000 Server port
    KGRAPH_API_KEY (none) API key for authentication
    KGRAPH_SERVER http://localhost:3000 Server URL (used by client hooks)

    Storage Layout

    ~/.kgraph/
    ├── registry.db                  # git remote -> project mapping
    └── projects/
        ├── trading-platform/        # fully isolated
        │   ├── index.db             # per-project SQLite (FTS5)
        │   └── notes/               # markdown files (source of truth)
        │       ├── architecture/
        │       │   ├── auth-strategy.md
        │       │   └── api-design.md
        │       └── database-schema.md
        └── monitoring-agent/        # completely separate
            ├── index.db
            └── notes/

    Runtime Support

    kgraph runs on both Bun (recommended) and Node.js 20+ with automatic runtime detection:

    Feature Bun Node.js
    SQLite bun:sqlite (built-in) better-sqlite3 (optional dep)
    HTTP server Bun.serve http.createServer
    File I/O Bun.file / Bun.write fs/promises
    UI bundler bun build External bundler needed
    # Bun (recommended — zero extra deps)
    bun run src/index.ts serve
    
    # Node.js (installs better-sqlite3 automatically)
    node --import tsx src/index.ts serve

    Development

    git clone https://github.com/RandomCodeSpace/kgraph.git
    cd kgraph
    bun install
    bun test              # Run 119 tests (280 assertions)
    bun run build         # Build UI bundle (0.36 MB)
    bun run dev           # Start dev server on :3000

    Test Coverage

    Module Tests What's Covered
    Wikilinks 12 Extraction, replacement, edge cases
    Frontmatter 8 Parse, serialize, roundtrip
    Remote normalization 13 SSH, HTTPS, GitLab, Bitbucket, self-hosted
    SQLite DB 24 CRUD, FTS5, links, BFS traversal, cascade
    Notes 11 File I/O, versioning, wikilink extraction
    Graph 13 Build, traverse, reindex, tree structure
    Project management 10 Register, resolve, multi-remote
    Hooks 7 SessionStart context, Stop handling
    REST API 14 All 14 endpoints, error cases
    Integration 7 Full lifecycle, isolation, wikilinks
    Total 119

    Docker

    # Build
    docker build -t kgraph .
    
    # Run
    docker run -d \
      -p 3000:3000 \
      -v kgraph-data:/data \
      -e KGRAPH_API_KEY=your-secret-key \
      kgraph

    Nginx Reverse Proxy

    server {
        listen 443 ssl;
        server_name kgraph.yourdomain.com;
    
        location / {
            proxy_pass http://127.0.0.1:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
        }
    }

    Dependencies

    Package Purpose Required
    @modelcontextprotocol/sdk MCP protocol (Streamable HTTP) Yes
    gray-matter YAML frontmatter parsing Yes
    better-sqlite3 SQLite for Node.js runtime Optional

    Everything else is built-in: bun:sqlite for database, Bun.serve for HTTP, fs.watch for file watching, Bun for UI bundling.


    GitHubIssuesPackages

    MIT License