Content
# CodeGraph4j
> Java code semantic knowledge graph, providing code understanding capabilities for AI coding assistants
[](https://adoptium.net/)
[](https://maven.apache.org/)
[](https://opensource.org/licenses/MIT)
---
## Why Do We Need a Code Knowledge Graph?
When AI coding assistants need to understand code—answering questions, locating bugs, or implementing requirements—they can only search through files like humans: grep → glob → Read, piecing together call chains and dependencies one file at a time. Before truly working, a large number of tool calls and back-and-forth conversations have already consumed tokens and time. The larger the codebase, the slower this blind exploration.
**CodeGraph turns the entire codebase into precise context available in one query.** It pre-constructs a semantic knowledge graph of each line of code, each symbol, each call relationship, and each dependency—no longer requiring AI assistants to crawl through files one by one. With just one question, they can get:
- **Complete source code of relevant code** (with line numbers)
- **Call paths between symbols** (including dynamic dispatch and polymorphic jumps that grep cannot track)
- **Impact scope of modifications** (which modules will be affected)
**Precise confirmation instead of file-by-file search** means fewer tool calls, faster response times, and lower token consumption, benefiting stably across codebases of any size.
> **About cost**: On any codebase, CodeGraph's core value lies in precision and speed—fewer tool calls and faster responses. It also reduces token and cost but saves more significantly with larger codebases and more extensive usage.
> Detailed benchmark data (7 open-source projects, 7 languages, 58% fewer tool calls, 22% faster) can be found in [codegraph official benchmark →](https://github.com/colbymchenry/codegraph#why-codegraph)
---
## Why Choose CodeGraph4j?
CodeGraph4j is the Java port of [codegraph](https://github.com/colbymchenry/codegraph), maintaining consistent core semantic graph logic while providing deeper support in the Java ecosystem.
| | codegraph (TypeScript) | CodeGraph4j (Java) |
|---|---|---|
| **Runtime** | TypeScript / Node.js | **JDK 8+**, compatible with most enterprise projects |
| **Framework awareness** | General language parsing | **Deep Java framework awareness**: Spring Boot, Dubbo, OpenFeign |
| **AI tools** | Claude, Cursor, Codex, opencode, etc. (8 tools) | Claude, Cursor, **Trae** (more friendly for Chinese IDEs) |
| **Distribution** | npm / standalone binary | **Maven / Fat JAR** (`java -jar` for one-click execution) |
| **Microservice support** | Single project indexing | **Custom database path**, naturally supporting multi-project isolated indexing |
| **Code parsing** | Tree-sitter | **Tree-sitter (JNA bridging)**, same level of AST parsing |
**Applicable scenarios**:
- Java enterprise projects, Spring microservice systems
- Distributed systems with Dubbo / OpenFeign RPC calls
- Teams needing precise Java code context understanding for AI assistants
- Developers using Trae, Claude Code, Cursor, etc.
---
## Core Features
- **Java code parsing** — High-performance AST parser based on Tree-sitter, JNA bridging native C library
- **Framework awareness** — Identifies call relationships of frameworks like Spring Boot MVC, Dubbo RPC, OpenFeign
- **Knowledge graph** — Constructs semantic relationships between code symbols (11 types: CALLS, INHERITS, IMPLEMENTS, REFERENCES, etc.)
- **MCP toolset** — 8 MCP tools for AI assistants (with `codegraph_explore` as the core)
- **Incremental synchronization** — FileWatcher automatic listening + Git hooks optional, index updated in real-time
- **SQLite local storage** — FTS5 full-text search, zero external dependencies, customizable database path
- **JDK 8 compatibility** — Covers most enterprise-level Java projects
- **One-click installation** — `install` command automatically configures MCP connections for Claude, Cursor, Trae
---
## Quick Start
### Prerequisites
- JDK 8 or higher
- Maven 3.6+
### 1. Build the Project
```bash
git clone https://github.com/codegraph/codegraph4j.git
cd codegraph4j
mvn clean package
```
The Fat JAR is located at `target/codegraph4j-1.0-SNAPSHOT.jar` after building.
### 2. Install MCP Configuration to AI Assistants
```bash
# Install to all supported AI assistants (global configuration)
java -jar target/codegraph4j-1.0-SNAPSHOT.jar install --target all --global -p /path/to/your/project
```
Supported targets (`--target`): `claude`, `cursor`, `trae`, `all`, `auto`
### 3. Initialize the Project
```bash
java -jar target/codegraph4j-1.0-SNAPSHOT.jar init -p /path/to/your/project
```
This creates `.codegraph/codegraph4j.db` in the project root.
### 4. Index Code
```bash
java -jar target/codegraph4j-1.0-SNAPSHOT.jar index -p /path/to/your/project
```
### 5. Start MCP Service (automatically called by AI assistants)
Restart the AI assistant, and the MCP configuration takes effect. The assistant will automatically start the CodeGraph service.
Alternatively, test manually:
```bash
java -jar target/codegraph4j-1.0-SNAPSHOT.jar serve --mcp -p /path/to/your/project
```
---
## Command Explanation
### install — Install MCP Configuration
Automatically configures CodeGraph MCP connections for AI assistants.
```bash
java -jar codegraph4j.jar install [options]
```
| Option | Description |
|------|------|
| `--target <targets>` | Target AI assistants (default `all`): `claude`, `cursor`, `trae` (comma-separated) |
| `--global` | Global installation (user-level configuration), otherwise project-level |
| `-p, --project <path>` | Project path (default current directory). Trae requires explicit specification |
| `--print-config` | Prints configuration status only, without modifying files |
**Configuration paths for each target**:
| Target | Global Path | Project Path | Additional Files |
|------|---------|----------|----------|
| Claude | `~/.claude.json` | `./.mcp.json` | `~/.claude/CLAUDE.md` |
| Cursor | `~/.cursor/mcp.json` | `./.cursor/mcp.json` | — |
| Trae | `~/Library/Application Support/Trae CN/User/mcp.json` | — | `./.trae/rules/codegraph.md` |
```bash
# Example: Install only to Trae and Claude
java -jar codegraph4j.jar install --target trae,claude --global -p /path/to/project
# View current configuration status
java -jar codegraph4j.jar install --print-config --target all --global
```
### uninstall — Uninstall MCP Configuration
```bash
java -jar codegraph4j.jar uninstall --target all
```
| Option | Description |
|------|------|
| `--target <targets>` | Target AI assistants (default `all`) |
### init — Initialize Database
```bash
java -jar codegraph4j.jar init -p <project-path> [options]
```
| Option | Description |
|------|------|
| `-p, --project` | Project root directory (default current directory) |
| `-f, --force` | Overwrite existing database |
### index — Full Indexing
Scans all source files in the project, parses, and constructs the knowledge graph.
```bash
java -jar codegraph4j.jar index -p <project-path> [options]
```
| Option | Description |
|------|------|
| `-p, --project` | Project root directory (default current directory) |
| `--force` | Force re-indexing of all files (ignore hash cache) |
| `--watch` | Start file watching after indexing (to be implemented) |
### sync — Incremental Synchronization
Reconciles the file system with the database, processing only changed files (additions, modifications, deletions). Suitable for use as Git hooks or CI steps.
```bash
java -jar codegraph4j.jar sync -p <project-path> [options]
```
| Option | Description |
|------|------|
| `-p, --project` | Project root directory (default current directory) |
| `-q, --quiet` | Silent mode (for Git hooks, no output) |
Example output:
```
========== Synchronization completed ==========
✓ Sync completed in 1234ms
Files checked: 156
New files: 3
Modified files: 2
Deleted files: 1
Updated nodes: 45
==============================
```
**Automatic synchronization with Git hooks**: Install `post-commit`, `post-merge`, and `post-checkout` hooks in `.git/hooks/`:
```bash
# Install Git hooks
java -jar codegraph4j.jar git-hooks install -p /path/to/project
# Uninstall Git hooks
java -jar codegraph4j.jar git-hooks uninstall -p /path/to/project
```
### status — View Status
```bash
java -jar codegraph4j.jar status -p <project-path>
```
| Option | Description |
|------|------|
| `-p, --project` | Project root directory (default current directory) |
Example output:
```
CodeGraph Status
================
Project: /path/to/your/project
Database: /path/to/your/project/.codegraph/codegraph4j.db
Nodes: 1234
Edges: 5678
```
### serve — Start MCP Service
```bash
java -jar codegraph4j.jar serve --mcp -p <project-path>
```
| Option | Description |
|------|------|
| `-p, --project` | Project root directory (default current directory) |
| `--mcp` | Run in MCP mode (stdio JSON-RPC 2.0 transport) |
### traverse — Graph Traversal
Explore call relationships, impact scopes, etc., of nodes in the code graph.
```bash
java -jar codegraph4j.jar traverse -p <project-path> [options]
```
| Option | Description |
|------|------|
| `-n, --node-id <id>` | Starting node ID |
| `--search <query>` | Search for the starting node by name (替代 --node-id) |
| `-d, --depth <n>` | Traversal depth (default 3) |
| `--direction` | Direction: `outgoing`, `incoming`, `both` (default outgoing) |
| `--limit <n>` | Maximum nodes to visit (default 100) |
| `--edge-kinds <kinds>` | Limit edge types, comma-separated (e.g., `CALLS,CONTAINS`) |
| `--callers` | Find caller mode |
| `--callees` | Find callee mode |
| `--impact` | Impact scope analysis mode |
```bash
# BFS traversal
java -jar codegraph4j.jar traverse --search "UserService" -d 2
# Find who calls the login method
java -jar codegraph4j.jar traverse --search "login" --callers
# Analyze the impact scope of the authenticate method
java -jar codegraph4j.jar traverse --search "authenticate" --impact
```
---
## MCP Tools
CodeGraph4j exposes 8 tools via the MCP protocol for AI coding assistants:
| Tool Name | Function |
|--------|------|
| `codegraph_explore` | **Core tool** — Natural language query, hybrid search + graph expansion + RWR relevance ranking |
| `codegraph_search` | Search for code symbols by name |
| `codegraph_callers` | Find callers of a specified symbol |
| `codegraph_callees` | Find callees of a specified symbol |
| `codegraph_impact` | Impact scope analysis |
| `codegraph_node` | View detailed information of a single symbol (location, signature, references) |
| `codegraph_status` | Check indexing health status |
| `codegraph_files` | List indexed files |
---
## Framework Awareness
CodeGraph4j has a built-in framework parsing system, extensible via the `FrameworkResolver` interface.
### Spring / Spring Boot
- Identifies annotations like `@RestController`, `@Service`, `@Repository`
- Constructs call chains: `Controller → Service → Repository`
- Extracts `@RequestMapping` routes as ROUTE nodes
- Identifies `@Value("${...}")` configuration key bindings
### Dubbo
- Detects `@DubboService` annotations marking RPC providers
- Extracts exposed interface methods as ROUTE nodes
- Parses `@DubboReference` marked consumer references
- Supports Dubbo projects based on XML configuration and annotations
### OpenFeign
- Detects `@FeignClient` annotations for remote HTTP clients
- Extracts remote endpoint paths and methods as ROUTE nodes
- Parses `@Autowired` injected Feign client references
- Supports tracking cross-file remote service dependencies
### Extending Frameworks
Implement the `FrameworkResolver` interface and register it with `FrameworkRegistry`:
```java
public class MyBatisResolver implements FrameworkResolver {
@Override public String getName() { return "MyBatis"; }
@Override public List<Language> getLanguages() { return List.of(Language.JAVA); }
@Override public boolean detect(ResolutionContext ctx) { /* Detect pom.xml */ }
@Override public FrameworkExtractionResult extract(String path, String src, ResolutionContext ctx) { /* Extract Mapper */ }
// ...
}
```
---
## Data Model
### Node
Code symbols like classes, methods, fields, etc.
| Field | Type | Description |
|------|------|------|
| id | String | Unique identifier (SHA-256) |
| kind | NodeKind | Symbol type |
| name | String | Symbol name |
| qualifiedName | String | Fully qualified name |
| filePath | String | File path where located |
| startLine / endLine | int | Line number range |
| docstring | String | Documentation comment |
**NodeKind enum** (22 kinds): `FILE`, `MODULE`, `CLASS`, `INTERFACE`, `ENUM`, `METHOD`, `CONSTRUCTOR`, `FIELD`, `PARAMETER`, `VARIABLE`, `CONSTANT`, `IMPORT`, `ROUTE`, `COMPONENT`, etc.
### Edge
Relationships between symbols.
| Field | Type | Description |
|------|------|------|
| source | String | Source node ID |
| target | String | Target node ID |
| kind | EdgeKind | Relationship type |
| provenance | String | Edge source (`parsed` / `heuristic` / `framework`) |
**EdgeKind enum** (11 kinds): `CONTAINS`, `CALLS`, `IMPORTS`, `IMPLEMENTS`, `EXTENDS`, `OVERRIDES`, `REFERENCES`, `INSTANTIATES`, `RETURNS`, `TYPE_OF`, `DECORATES`.
### FileRecord
Indexed file tracking records (path, hash, size, mtime).
---
## Project Structure
```
codegraph4j/
├── src/main/java/com/codegraph/
│ ├── cli/ # Command Line Interface
│ │ └── commands/ # 8 subcommands: init, index, sync, status,
│ │ # serve, traverse, install, uninstall
│ ├── core/ # Core data models (Node, Edge, FileRecord)
│ │ └── types/ # Enums: NodeKind, EdgeKind, Language, Visibility
│ ├── db/ # Database layer (SQLite + FTS5)
│ ├── extraction/ # Code parsing and extraction
│ │ ├── bridge/ # JNA bridge to Tree-sitter C library
│ │ ├── tree_sitter/ # AST traversal extractors
│ │ └── languages/ # Language-specific extractors (Java with Lombok support)
│ ├── resolution/ # Symbol resolution
│ │ ├── frameworks/ # Framework parser interfaces and registry
│ │ └── supportedframeworks/ # Spring, Dubbo, OpenFeign parsers
│ ├── graph/ # Graph traversal engine (BFS, call chains, impact analysis)
│ ├── context/ # AI context construction (RWR relevance, adaptive budgeting)
│ ├── mcp/ # MCP protocol implementation (JSON-RPC 2.0 + stdio)
│ ├── sync/ # Incremental synchronization engine (FileWatcher + Git hooks)
│ ├── install/ # AI assistant configuration management
│ └── utils/ # Utility classes (Mutex, FileLock, LRU Cache)
├── src/main/resources/
│ ├── db/schema.sql # Database DDL (nodes, edges, files, unresolved_refs)
│ └── logback.xml # Logging configuration
└── src/test/ # Unit tests
```
---
## Database
Uses SQLite for local storage, with the database file defaulting to `<project>/.codegraph/codegraph4j.db`. The path can be customized using the `-p` option, naturally supporting multi-project isolated indexing.
### Main Tables
| Table | Description |
|------|------|
| `nodes` | Code symbol nodes (with FTS5 full-text search) |
| `edges` | Symbol relationships (foreign key constraints, cascading deletes) |
| `files` | File tracking (path, hash, mtime) |
| `unresolved_refs` | Unresolved cross-file references |
| `project_metadata` | Project metadata (framework detection results, etc.) |
| `schema_versions` | Schema version tracking |
---
## Multi-Project Support
In a multi-project microservices architecture, each subproject can independently initialize its own `.codegraph/codegraph4j.db`:
```bash
# Initialize separate indexes for each microservice
java -jar codegraph4j.jar init -p /workspace/order-service
java -jar codegraph4j.jar init -p /workspace/user-service
java -jar codegraph4j.jar init -p /workspace/gateway-service
```
Framework parsers (Dubbo, OpenFeign) automatically track cross-service RPC call relationships, establishing reference nodes in their respective databases.
---
## Future Plans
### Additional Framework Support
| Framework | Scenario | Planned Relationships |
|------|------|---------------|
| **MyBatis** | ORM framework | Mapper XML → DAO method SQL mapping relationships |
| **gRPC** | RPC | `@GrpcService` → proto-defined bidirectional references |
| **Motan** | RPC | Dubbo-like provider/consumer parsing |
| **Quarkus** | Cloud-native | JAX-RS routing, CDI injection relationships |
### Multi-Project Graph
Cross-repository call chain tracking, microservice topology graphs, and establishing joint indexes across multiple `.codegraph/` databases.
### Additional AI Tool Support
Extending installer support for Gemini CLI, Codex, opencode, and other tools' MCP configurations.
### Performance Optimization
- Large project (100k+ files) incremental indexing performance optimization
- Parsing result caching (avoiding repeated parsing of unchanged files)
---
## Development
### Running Tests
```bash
mvn test
```
### Running Specific Tests
```bash
mvn test -Dtest=InstallerModuleTest
mvn test -Dtest=SyncOrchestratorUnitTest
```
### Building
```bash
mvn clean package -DskipTests
```
### Tech Stack
| Dependency | Purpose |
|------|------|
| picocli 4.7.5 | CLI framework |
| sqlite-jdbc 3.45 | SQLite driver |
| jackson-databind 2.16 | JSON serialization |
| jgit 6.8 | Git integration |
| jna 5.16 | Tree-sitter C library bridging |
| guava 33.0 | General utility library |
| slf4j + logback | Logging |
---
## License
MIT License
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
No recommendations available