Skip to content

About

ContextGraph - Build and query intelligent code graphs for better LLM and AI agent context retrieval. Optimize token usage and accuracy in coding workflows.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ContextGraph

CI License: MIT Python 3.10+

Python-first code graph retrieval for focused LLM and coding-agent context.

ContextGraph scans a repository, extracts Python files, classes, functions, methods, imports, and resolvable call relationships, then ranks source snippets against a query under an approximate token budget.

Project status: early alpha. The public API and graph schema may change before 1.0.

What works today

  • Python AST indexing for files, classes, functions, methods, imports, and local call edges
  • Hybrid ranking using symbol names, file paths, source text, graph degree, and optional local embeddings
  • Token-budgeted source-context output
  • Ranked pack export for agent prompts
  • Optional stdio MCP server for build, query, and pack
  • CLI commands for scanning and bounded source retrieval
  • A small Python API with no required cloud service
  • CI across Python 3.10 through 3.13

Installation

Install the current development version from GitHub:

python -m pip install "git+https://github.com/yniantongtian-oss/contextgraph.git"

The planned PyPI distribution name is contextgraph-ai because the contextgraph distribution name is already used by an unrelated project. After the first release:

python -m pip install contextgraph-ai

Optional semantic retrieval:

python -m pip install "contextgraph-ai[semantic]"

Optional MCP server (official Python SDK, stdio only):

python -m pip install "contextgraph-ai[mcp]"

The distribution name is contextgraph-ai; the Python import remains:

from contextgraph import CodeContextGraph

CLI quick start

Scan a Python project:

contextgraph scan ./my-project

Retrieve context without downloading an embedding model:

contextgraph query "authentication token validation" \
  --project ./my-project \
  --budget 1200

Use optional local semantic retrieval:

contextgraph query "where is user identity verified" \
  --project ./my-project \
  --budget 1200 \
  --semantic

Retrieve the source relevant to a development task:

contextgraph query "rate limiting for login" --project ./my-project --budget 1600

Export an inspectable, tool-neutral source bundle as JSON:

contextgraph bundle "authentication token validation" \
  --project ./my-project \
  --max-tokens 1200 \
  --output ./retrieval-result.json

The exported file records the task, retrieved context, source filenames, token estimate, and candidate count. It does not generate role instructions or require a hosted service.

Export a ranked context pack that stays inside a token budget. The budget applies to the packed source text (about four characters per token), including separators between blocks. Items carry rank, score, path, and line span so the source is not repeated twice. Without --output, the JSON document is the only thing written to stdout; index progress goes to stderr:

contextgraph pack "authentication token validation" \
  --project ./my-project \
  --budget 1200 \
  --output ./context-pack.json

Python API

from contextgraph import CodeContextGraph

cg = CodeContextGraph()
cg.load_project("./my-project")
cg.build_graph()

result = cg.query_context(
    "authentication token validation",
    max_tokens=1200,
)

print(result["context"])
print(result["relevant_files"])
print(result["scores"])

packed = cg.pack_context("authentication token validation", max_tokens=1200)
print(packed["estimated_tokens"], packed["items"][0]["id"])

MCP server

contextgraph mcp speaks MCP over stdio. It exposes three tools:

Tool Purpose
build_graph Index a project path and return graph statistics, including parse and load errors
query_context Preview ranked matches for a query inside a token budget
pack_context Export the ranked pack (budget limits the context text)

The server reads local files and parses Python with ast. It does not execute the project and it does not open a network port. Query and pack reuse the last index for a path until build_graph runs again.

Install the extra, then point the editor at the contextgraph executable on PATH.

Claude Code

Add this to .mcp.json in the project root (or run claude mcp add --transport stdio contextgraph -- contextgraph mcp):

{
  "mcpServers": {
    "contextgraph": {
      "type": "stdio",
      "command": "contextgraph",
      "args": ["mcp"]
    }
  }
}

Claude Code asks before it starts a project-scoped server. If contextgraph is only installed in a virtualenv, set command to that environment's executable.

Cursor

Add this to .cursor/mcp.json in the project, or to ~/.cursor/mcp.json for every workspace:

{
  "mcpServers": {
    "contextgraph": {
      "type": "stdio",
      "command": "contextgraph",
      "args": ["mcp"]
    }
  }
}

Cursor interpolates ${workspaceFolder} if the executable lives inside the project:

{
  "mcpServers": {
    "contextgraph": {
      "type": "stdio",
      "command": "${workspaceFolder}/.venv/bin/contextgraph",
      "args": ["mcp"]
    }
  }
}

How it works

flowchart LR
    A[Source files] --> B[Python AST index]
    B --> C[Directed code graph]
    D[User query] --> E[Lexical and optional semantic scoring]
    C --> E
    E --> F[Token-budgeted source context]
Loading

The graph uses stable repository-relative identifiers such as:

  • file:src/service.py
  • symbol:src/service.py::UserService.login
  • module:sqlite3

Call edges are resolved when a target symbol can be identified unambiguously. Dynamic dispatch, runtime imports, decorators, and reflection are not fully modeled.

Development

git clone https://github.com/yniantongtian-oss/contextgraph.git
cd contextgraph
python -m pip install -e ".[dev]"
ruff check src tests examples
ruff format --check src tests examples
pytest --cov=contextgraph
python -m build

See CONTRIBUTING.md and docs/architecture.md for repository conventions and design details.

Roadmap

  • Persistent graph snapshots and incremental indexing
  • Better import and cross-file call resolution
  • Tree-sitter parsers for TypeScript, JavaScript, C, and C++
  • Context expansion through callers, callees, and neighboring symbols
  • Reproducible retrieval benchmarks
  • Editor plugins that keep a long-lived index beside the stdio MCP server

Security

ContextGraph reads local source files. Review SECURITY.md before using it on untrusted repositories or enabling optional model downloads.

License

MIT. See LICENSE.

About

ContextGraph - Build and query intelligent code graphs for better LLM and AI agent context retrieval. Optimize token usage and accuracy in coding workflows.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages