Skip to main content

SQLite/PostgreSQL codebase knowledge graph and MCP server for Claude Code

Project description

codegraphy

Standalone Python package that parses a codebase into a knowledge graph (PostgreSQL or SQLite) and exposes it as an MCP server for Claude Code. Claude calls graph tools instead of Read + Bash(grep) — cuts exploration token cost by 5–10×.

Python: 3.10+
License: MIT


Why

Claude exploring an unfamiliar codebase today:

Task Without codegraphy With codegraphy
Find where Something is defined Read 10 files (~15k tokens) search_symbol("Something") (~200 tokens)
Understand a file's structure Read full file (~3k tokens) get_file_summary("views.py") (~300 tokens)

Installation

# SQLite-only install (default, zero config):
pip install codegraphy

# For PostgreSQL support:
pip install codegraphy[postgres]

# For JS/TS parsing (planned):
pip install codegraphy[js]

# Everything:
pip install codegraphy[all]

The base PyPI package keeps SQLite support in the standard library path, so PostgreSQL stays opt-in.


Quickstart

# 1. Initialize the database (SQLite by default)
codegraphy init

# 2. Index your project
codegraphy index .

# 3. Start the MCP server (stdio, for Claude Code)
codegraphy serve

That's it. Claude can now query your codebase graph instead of reading files.


CLI Reference

codegraphy init [--db URL]         # Create tables (SQLite default, or pass Postgres URL)
codegraphy index PATH [--exclude]  # Full index of a directory
codegraphy update                  # Incremental re-index via git diff
codegraphy serve                   # Start MCP server over stdio
codegraphy search NAME             # Search symbols (debug, not MCP)
codegraphy usages QUALIFIED_NAME   # Find usages (debug, not MCP)
codegraphy stats                   # Show graph statistics

MCP Tools

When running as an MCP server, codegraphy exposes these tools to Claude:

Tool Description
search_symbol(name, kind?, limit?, fallback_grep?) Find symbols by name — exact, then substring, then grep fallback
get_file_summary(file_path) Classes, functions, imports in a file without reading it
find_usages(qualified_name, limit?, fallback_grep?) Who imports/calls/references this symbol
get_context(file_path, line, radius?) Read N lines around a line number
path_between(from_qualified, to_qualified, max_depth?) BFS shortest path between two symbols
grep_search(pattern, include?, exclude?, limit?) Direct grep — bypass the graph
graph_stats() File/symbol/edge counts, backend type
what_touches_model(model_name) Django: views, admin, signals referencing a model
search_semantic(query, limit?) pgvector semantic search (Postgres only, planned)

All tools return a source field ("graph" or "grep") so Claude can gauge confidence.


Configuration

Priority: CLI flag → environment variable → codegraphy.toml → defaults.

Environment Variables

DATABASE_URL=sqlite:///codegraphy.db    # or postgresql://localhost/codegraphy
REPOLENS_ROOT=.                        # project root for grep fallback
REPOLENS_PLUGINS=repolens.plugins.django

Config File (optional)

# codegraphy.toml (place at project root)
database_url = "postgresql://localhost/codegraphy"
root = "."
exclude = ["migrations", "node_modules", ".venv", "__pycache__"]
plugins = ["repolens.plugins.django"]

Claude Code Integration

Register the MCP server

// .claude/settings.json
{
  "mcpServers": {
    "codegraphy": {
      "command": "codegraphy",
      "args": ["serve"],
      "env": {
        "DATABASE_URL": "sqlite:///codegraphy.db"
      }
    }
  }
}

Auto-update on session end (optional)

// .claude/settings.json
{
  "hooks": {
    "Stop": [{
      "type": "command",
      "command": "codegraphy update"
    }]
  }
}

Architecture

repolens/
├── cli.py              # Click CLI entry points
├── config.py           # DATABASE_URL, REPOLENS_ROOT, plugin list
├── db/
│   ├── schema.py       # CREATE TABLE statements (PG + SQLite)
│   └── store.py        # upsert_symbol, upsert_edge, query helpers
├── indexer/
│   ├── base.py         # BaseIndexer ABC, Symbol/Edge dataclasses
│   ├── python.py       # ast-based Python indexer
│   └── walker.py       # Filesystem walk + git-diff incremental
├── mcp/
│   └── server.py       # FastMCP server + all tool definitions
├── plugins/
│   ├── base.py         # BasePlugin ABC
│   └── django.py       # Django-aware: models, views, signals
└── session/            # (planned) git-diff hook + memory write

Database Schema

Three tables power the graph:

  • cg_files — indexed files with git hash for deduplication
  • cg_symbols — every class, function, method, import with location + summary
  • cg_edges — relationships: imports, calls, inherits, references, registers, handles_signal

Indexing Strategy

  1. Walk files via git ls-files (falls back to os.walk)
  2. SHA-256 content hash skips unchanged files
  3. AST parsing extracts symbols and edges
  4. Plugins post-process symbols (e.g., Django re-tags classmodel)
  5. Upsert into database with cascade delete for clean re-indexing

Plugin System

Plugins implement two hooks:

class BasePlugin:
    def on_symbol(self, symbol: Symbol) -> Symbol:
        """Mutate or re-tag a symbol after parsing."""
        return symbol

    def extra_edges(self, symbols: list[Symbol]) -> list[Edge]:
        """Derive additional edges from the symbol list."""
        return []

Built-in: Django Plugin

Detects Django patterns by file naming convention:

  • Classes in models.pykind = "model"
  • Classes/functions in views.pykind = "view"

Enable via environment variable:

REPOLENS_PLUGINS=repolens.plugins.django

Current Status

Milestone Status
M1 — Schema + Python indexer + codegraphy index ✅ Complete
M2 — search_symbol + get_file_summary + MCP serve ✅ Complete
M3 — find_usages + path_between + get_context + grep fallback ✅ Complete
M4 — codegraphy update (incremental) ✅ Complete
M5 — Django plugin 🔶 Partial (symbol re-tagging, no admin/signal edges)
M6 — Semantic search (pgvector) ⬜ Stub only
M7 — JS/TS indexer (tree-sitter) ⬜ Planned
M8 — HTML/Template indexer ⬜ Planned
M9 — grep_search tool + cross-language edges 🔶 grep_search done, cross-lang edges planned

Development

# Clone and install in editable mode
git clone <repo-url> && cd codegraphy
python -m venv .venv && source .venv/bin/activate
pip install -e .

# Initialize local DB and index this project
codegraphy init
codegraphy index .

# Check stats
codegraphy stats

Publishing

codegraphy is configured to build as a standard PyPI distribution from pyproject.toml.

For PyPI trusted publishing, use publish.yml as the workflow name. The workflow file lives at .github/workflows/publish.yml.

python -m pip install --upgrade build twine
python -m build
python -m twine check dist/*
python -m twine upload dist/*

What It Is NOT

  • Not a code execution sandbox
  • Not a test runner or linter
  • Not a replacement for LSP/IDE features
  • Not AI-generated summaries by default (uses docstrings; AI summaries are opt-in future)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

codegraphy-0.1.0.tar.gz (15.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

codegraphy-0.1.0-py3-none-any.whl (19.2 kB view details)

Uploaded Python 3

File details

Details for the file codegraphy-0.1.0.tar.gz.

File metadata

  • Download URL: codegraphy-0.1.0.tar.gz
  • Upload date:
  • Size: 15.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for codegraphy-0.1.0.tar.gz
Algorithm Hash digest
SHA256 106306e10fdf0e1e9f79aa3ac909efd4258db249c43236d8f566418766cfb84e
MD5 deb7053c6e3f085c57bcfc9d659f2d0c
BLAKE2b-256 e33b4b3aabef8a176303e3ed7646c3c7702b7bd1c96b332ab878b63eb63f5d06

See more details on using hashes here.

Provenance

The following attestation bundles were made for codegraphy-0.1.0.tar.gz:

Publisher: publish.yml on charan-eg/codegraphy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file codegraphy-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: codegraphy-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 19.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for codegraphy-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0ac2b25c8a42df2c2bbd96dd4d2b2b910dff0a88f0bd2753994959b81c249f3c
MD5 103277785a17e424fd6604ffc1ea6f0c
BLAKE2b-256 f320a54c1554b5fbe7003d418cee33975a90d32d1e74c74759036c15bc8c1c15

See more details on using hashes here.

Provenance

The following attestation bundles were made for codegraphy-0.1.0-py3-none-any.whl:

Publisher: publish.yml on charan-eg/codegraphy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page