# How to Use Code-Graph-RAG for Semantic Code Refactoring

> Discover how code-graph-rag enables automated semantic code refactoring across languages. Leverage AST-aware editing and knowledge graph queries for efficient code transformations.

- Repository: [Vitali Avagyan/code-graph-rag](https://github.com/vitali87/code-graph-rag)
- Tags: how-to-guide
- Published: 2026-08-18

---

**Yes, code-graph-rag provides AST-aware editing tools that enable automated refactoring across multiple languages by combining knowledge graph queries with surgical code transformations.**

The `vitali87/code-graph-rag` repository is an open-source RAG (Retrieval-Augmented Generation) platform that transforms multi-language codebases into queryable knowledge graphs. Unlike traditional regex-based refactoring tools, code-graph-rag leverages Tree-sitter parsing and agentic editing to perform semantic transformations that understand code structure rather than just text patterns.

## The Code-Graph-RAG Refactoring Architecture

Code-graph-rag enables refactoring through a two-stage pipeline that bridges static analysis and AI-driven editing.

### Multi-Language Graph Construction

The system first builds a semantic graph of your codebase using a **Tree-sitter based parser**. This extracts functions, classes, modules, and their relationships into a **Memgraph** database, creating a navigable network of code entities. According to the [README](https://github.com/vitali87/code-graph-rag/blob/main/README.md#how-it-works), this graph captures cross-language dependencies and call relationships that traditional refactoring tools often miss.

### Agentic Editing Layer

The second component is an interactive CLI that translates natural-language prompts into **Cypher queries** to locate code, then delegates transformations to an agent equipped with AST-aware editing tools. As documented in [[`docs/guide/interactive-querying.md`](https://github.com/vitali87/code-graph-rag/blob/main/docs/guide/interactive-querying.md)](https://github.com/vitali87/code-graph-rag/blob/main/docs/guide/interactive-querying.md), this agent can modify code without breaking syntax or semantic relationships.

## AST-Aware Refactoring Tools

Code-graph-rag exposes four primary tools for automated refactoring, each designed for specific transformation scenarios.

### replace_code

The **`replace_code`** tool performs surgical block replacements by targeting exact code segments while preserving surrounding context. It provides a visual diff preview before applying changes, ensuring that transformations are reviewed before commitment. This tool is ideal for precise modifications like updating function signatures or replacing specific API calls.

### structural_search and structural_replace

For pattern-based refactoring across multiple files, code-graph-rag integrates **ast-grep** syntax:

- **`structural_search`** finds code using AST patterns (e.g., `def $F($$$ARGS): $$$BODY`) across all supported languages
- **`structural_replace`** performs AST-based find-and-replace operations with optional dry-run mode to preview diffs

These tools support **language-agnostic bulk changes**, such as replacing all instances of `Path.relative_to()` with `os.path.relpath()` as demonstrated in the [[`REWRITE_RECOMMENDATIONS.md`](https://github.com/vitali87/code-graph-rag/blob/main/REWRITE_RECOMMENDATIONS.md)](https://github.com/vitali87/code-graph-rag/blob/main/docs/reports/REWRITE_RECOMMENDATIONS.md) report.

### surgical_replace_code (MCP Server)

For integration with external AI assistants like Claude Code, code-graph-rag exposes **`surgical_replace_code`** through the Model Context Protocol (MCP). This provides the same functionality as `replace_code` but via a standardized protocol, enabling IDE-agnostic refactoring workflows.

## Core Implementation Details

The refactoring capabilities are implemented in specific source files that handle the transformation logic and user interfaces.

### file_editor.py

The core editing logic resides in [`codebase_rag/tools/file_editor.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/tools/file_editor.py). This module contains:

- **`replace_code_block`** – A low-level helper that computes exact diffs and applies patches to source files
- **`replace_code_surgically`** – An async wrapper used by both the CLI and MCP server to handle concurrent editing operations

These functions ensure that edits are **AST-aware**, avoiding the brittleness of plain text search-and-replace that can break syntax or indentation.

### CLI Entry Point

The interactive refactoring interface is implemented in [`codebase_rag/workspaces/cli.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/workspaces/cli.py). This file wires together natural language query processing, graph traversal, and editing commands, providing the `cgr` command-line tool used for interactive sessions.

## Practical Refactoring Workflows

Below are executable examples demonstrating how to use code-graph-rag for common refactoring tasks.

### Interactive CLI Refactoring

Start an interactive session to refactor using natural language prompts:

```bash

# Initialize the graph (must be built first)

cgr start --repo-path /path/to/project

# Inside the REPL, request a refactoring

>>> Refactor the function `process_data` to use `logger.info` instead of `print`.

```

The agent executes a three-step process: it locates `process_data` in the graph, generates a diff replacing `print(` with `logger.info(`, and prompts for confirmation before applying the change.

### Bulk Structural Replacements

Perform language-wide transformations using AST patterns:

```bash
cgr replace_code \
  --pattern "print($MSG)" \
  --rewrite "logger.info($MSG)" \
  --language python \
  --dry-run

```

Remove the `--dry-run` flag to apply changes automatically, or keep it to review diffs across the entire codebase before committing.

### Programmatic Refactoring with the SDK

For automated pipelines, use the Python SDK to query the graph and apply edits:

```python
from code_graph_rag.sdk.graph_loader import GraphLoader
from code_graph_rag.sdk.cypher_generator import CypherGenerator
from code_graph_rag.sdk.semantic_search import SemanticSearch

# Connect to the existing graph

loader = GraphLoader(uri="bolt://localhost:7687")
graph = loader.load()

# Find functions that open files

cypher = CypherGenerator().match_functions_with_call("open")
functions = graph.run(cypher)

# Apply surgical replacements

for fn in functions:
    GraphLoader.replace_code_block(
        node_id=fn["id"],
        old="open(",
        new="Path().open("
    )

```

This example uses the same underlying `replace_code_block` implementation as the CLI, ensuring consistency between interactive and programmatic workflows.

### MCP Server Integration

Integrate with Claude Code or other MCP-compatible clients:

```json
{
  "tool": "surgical_replace_code",
  "arguments": {
    "file_path": "src/utils.py",
    "target": "def foo(...):",
    "replacement": "def foo(..., logger):"
  }
}

```

The MCP server validates the request, previews the diff, and applies the change upon approval, enabling refactoring from within AI-assisted coding environments.

## Summary

- **Code-graph-rag** combines knowledge graph construction with AST-aware editing to enable semantic refactoring across multiple languages.
- The **`replace_code`** and **`structural_replace`** tools provide both surgical precision and bulk transformation capabilities.
- Core editing logic is implemented in [`codebase_rag/tools/file_editor.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/tools/file_editor.py), with `replace_code_block` handling the low-level patch operations.
- The system supports **interactive CLI**, **programmatic SDK**, and **MCP server** interfaces for flexible integration into development workflows.
- All transformations provide diff previews and dry-run modes to ensure refactoring safety.

## Frequently Asked Questions

### Can code-graph-rag refactor multiple programming languages simultaneously?

Yes. Because the system uses Tree-sitter for parsing and ast-grep for structural patterns, it supports refactoring across Python, JavaScript, TypeScript, Rust, and other languages within the same workflow. The graph stores language-agnostic relationships, enabling cross-language refactoring when projects use multiple languages.

### How does code-graph-rag ensure refactoring safety?

The platform provides multiple safety mechanisms: **dry-run modes** that preview diffs without applying changes, **AST-aware parsing** that prevents syntax-breaking edits, and **surgical replacement** logic that targets specific nodes rather than performing global text substitution. The visual diff preview in the CLI allows human review before any file modifications occur.

### What is the difference between replace_code and structural_replace?

**`replace_code`** performs exact block replacements on specific code segments identified through graph queries, making it ideal for targeted changes like updating a single function signature. **`structural_replace`** uses AST patterns to match and transform code structures across the entire codebase, better suited for bulk refactoring like converting all instances of a deprecated API pattern.

### Can I use code-graph-rag with Claude Code or other AI assistants?

Yes. Through the MCP (Model Context Protocol) server implementation documented in [[`docs/guide/mcp-server.md`](https://github.com/vitali87/code-graph-rag/blob/main/docs/guide/mcp-server.md)](https://github.com/vitali87/code-graph-rag/blob/main/docs/guide/mcp-server.md), code-graph-rag exposes the `surgical_replace_code` tool to external AI clients. This allows Claude Code and compatible assistants to request semantic refactoring operations directly within your development environment.