What Is the `build_or_update_graph_tool`? A Deep Dive into the code-review-graph MCP Tool

The build_or_update_graph_tool is the core FastMCP utility in the tirth8205/code-review-graph project that parses repository source code with Tree-sitter to create and maintain a persistent incremental knowledge graph stored in SQLite.

The build_or_update_graph_tool serves as the foundation of the tirth8205/code-review-graph system, transforming raw codebases into queryable graph structures. This async-aware MCP tool enables both full repository indexing and incremental updates, making it essential for AI-powered code review workflows that depend on accurate structural analysis.

Core Purpose and Architecture

The build_or_update_graph_tool functions as the primary ingestion engine for the code-review-graph ecosystem. It traverses the repository filesystem, using Tree-sitter parsers to extract structural elements—including modules, classes, functions, imports, and test relationships—and persists these as nodes and edges in an on-disk SQLite database.

This persistent graph powers downstream analytical capabilities such as:

  • Impact analysis – determining which components affect others
  • Flow detection – tracing execution paths through the codebase
  • Community detection – identifying tightly coupled modules
  • Embedding generation – creating vector representations of code for semantic search

How Incremental Builds Work

First-Time Repository Indexing

When invoked with full_rebuild=True, the tool performs a complete parse of every source file in the repository. This initial build establishes the baseline graph structure and records the current Git commit hash for future differential comparisons.

Incremental Update Strategy

For subsequent invocations, build_or_update_graph_tool defaults to incremental mode. It compares the working tree against the last recorded Git base (or an explicit base reference provided via parameter), re-parsing only files that have changed. This approach significantly reduces processing time for large repositories while keeping the graph synchronized with the current code state.

Async Implementation Details

To maintain responsiveness within the MCP STDIO event loop—particularly critical on Windows platforms—the heavy Tree-sitter parsing workload is dispatched to a background thread using asyncio.to_thread. This implementation detail in code_review_graph/main.py prevents the tool from blocking during intensive graph construction operations.

Tool Parameters and Configuration

The build_or_update_graph_tool accepts several parameters that control its behavior:

  • full_rebuild (bool) – Forces a complete re-parse of all source files, ignoring any cached state.
  • repo_root (Optional[str]) – Explicit path to the repository root; if omitted, the tool auto-detects the repository from the current working directory.
  • base (Optional[str]) – Git reference (commit hash or branch) to diff against; if omitted, the tool resolves the last-synced commit automatically.
  • postprocess (str) – Controls the level of post-processing applied to the graph. Accepts "full" (comprehensive analysis), "minimal" (basic cleanup), or "none" (raw graph output).
  • recurse_submodules (Optional[bool]) – Whether to include Git submodules in the parsing scope; defaults to the value of the CRG_RECURSE_SUBMODULES environment variable.
  • embedding_provider / embedding_model – Optional hooks to trigger a one-off embedding refresh immediately after the graph is built or updated.

Usage Examples

Full Repository Build

Use this pattern when initializing the graph for the first time:

import asyncio
from code_review_graph.main import build_or_update_graph_tool

async def full_build():
    result = await build_or_update_graph_tool(full_rebuild=True)
    print("Graph built:", result["status"])

asyncio.run(full_build())

Incremental Update

For daily synchronization, invoke the tool without parameters to process only changed files:

import asyncio
from code_review_graph.main import build_or_update_graph_tool

async def incremental_update():
    # Uses the last-synced Git ref automatically

    result = await build_or_update_graph_tool()
    print("Updated nodes:", result["updated_node_count"])

asyncio.run(incremental_update())

Fast Build with Minimal Post-Processing

When speed is prioritized over analytical depth:

import asyncio
from code_review_graph.main import build_or_update_graph_tool

async def fast_build():
    result = await build_or_update_graph_tool(postprocess="minimal")
    print(result)

asyncio.run(fast_build())

Integration Interfaces

The tool is exposed through two primary interfaces:

  1. MCP Command Line – Invoke via the slash-command /code-review-graph:build-graph or directly from any MCP client. The parameter definitions in docs/COMMANDS.md document the CLI usage patterns and match the Python API signature.

  2. Python API – Import the async function directly from code_review_graph.main for use in custom scripts, test suites (as demonstrated in tests/test_integration_git.py), or skill workflows outlined in skills/build-graph/SKILL.md.

Summary

  • The build_or_update_graph_tool creates persistent knowledge graphs using Tree-sitter parsing and SQLite storage, enabling structural code analysis.
  • It supports both full rebuilds for initialization and incremental updates based on Git diffs to minimize processing overhead.
  • The async architecture uses asyncio.to_thread to maintain MCP responsiveness during CPU-intensive parsing operations.
  • The tool is defined in code_review_graph/main.py and accessible via both MCP CLI commands and direct Python imports.

Frequently Asked Questions

What is the primary function of build_or_update_graph_tool?

The tool parses repository source code to build a structural knowledge graph of modules, classes, functions, imports, and test relationships. It stores these entities and their connections in an on-disk SQLite database, which downstream tools query for impact analysis, flow detection, and embedding generation.

How does the tool determine which files to parse during incremental updates?

The tool resolves the last-synced Git commit automatically from its internal state (or uses an explicit base reference parameter) to diff against the current working tree. Only files with modifications relative to that base commit are re-parsed and updated in the graph, preserving unchanged nodes to minimize latency.

Can I invoke build_or_update_graph_tool programmatically outside of an MCP client?

Yes. You can import the tool directly from code_review_graph.main and await it in an async Python context. This makes it suitable for custom automation scripts, CI/CD pipelines, and integration tests that need to programmatically rebuild or update the code knowledge graph.

Why does the tool use asyncio.to_thread for parsing operations?

The Tree-sitter parsing workload is dispatched to a background thread via asyncio.to_thread to prevent blocking the MCP STDIO event loop. This architectural choice ensures the tool remains responsive during intensive graph construction, which is particularly important for maintaining protocol stability on Windows systems.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →