# How CodeGraph Indexing Works and How to Query Code Relationships: A Technical Guide

> Learn how CodeGraph indexing transforms Git repositories into queryable knowledge graphs. Discover how to query code relationships with MCP tools like code_callers and code_callees.

- Repository: [Tencent Cloud/TencentDB-Agent-Memory](https://github.com/TencentCloud/TencentDB-Agent-Memory)
- Tags: how-to-guide
- Published: 2026-08-26

---

**CodeGraph indexing transforms Git repositories into queryable knowledge graphs through an asynchronous pipeline that clones source code, extracts symbols and edges, and persists the structure, while code relationships are queried via MCP tools such as `code_callers`, `code_callees`, and `code_impact` that expose call hierarchies and dependency chains.**

The TencentDB-Agent-Memory repository implements a robust knowledge management layer that converts raw source repositories into navigable CodeGraph assets. Understanding how CodeGraph indexing works and how to query code relationships enables AI agents and developers to perform impact analysis, trace function dependencies, and explore codebase topology programmatically through structured HTTP endpoints.

## The CodeGraph Indexing Pipeline

The indexing process follows a three-stage lifecycle managed by the `CodeGraphService` class, ensuring durable storage and reliable asynchronous processing.

### Asset Creation and Storage

Indexing begins when a client invokes **`CodeGraphService.create`** in [[`MemoryKnowledge/src/store/code-graph-service.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/src/store/code-graph-service.ts)](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/feat/server_team/MemoryKnowledge/src/store/code-graph-service.ts). This method implements idempotent creation logic: it checks for existing rows matching the composite key (`service_id`, `team_id`, `repo_url`, `branch`) and returns the existing `CodeGraphRow` if found, or inserts a new row into the `IKnowledgeStore` with initial status `pending`.

```typescript
// Conceptual flow based on CodeGraphService.create()
const row = await codeGraphService.create({
  service_id: "svc_123",
  team_id: "team_456", 
  repo_url: "https://github.com/example/repo",
  branch: "main"
});
// Returns: { code_graph_id: "cg_abc", status: "pending", ... }

```

### Asynchronous Build Execution

Once persisted, the service triggers **`enqueueBuild`**, which pushes a task into the **`BuildQueue`** ([[`MemoryKnowledge/src/store/build-queue.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/src/store/build-queue.ts)](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/feat/server_team/MemoryKnowledge/src/store/build-queue.ts)). This serial queue guarantees that only one indexing job runs per graph at a time. An injected **CodeGraph Worker** consumes the task and performs three operations:

1. **Clone**: Clones the repository into `{dataRoot}/{service_id}/{team_id}/{code_graph_id}`
2. **Parse**: Extracts nodes (symbols) and edges (relationships) from the source
3. **Store**: Persists the graph structure and updates statistics (file count, node count, edge count)

During execution, the worker updates internal status via `setInternalStatus`, transitioning through `cloning` → `indexing` → `ready` (or `failed`).

### Monitoring Indexing Status

Clients poll the **`code_status`** MCP tool or the `/v3/code-graph/status` endpoint to track progress. The endpoint returns the current state stored in the `CodeGraphRow`, including the optional `service_url` where the completed graph is queryable once status equals `"ready"`.

```json
{
  "code_graph_id": "cg_abc",
  "status": "ready",
  "stats": {
    "files": 150,
    "nodes": 1200,
    "edges": 3400
  }
}

```

## Querying Code Relationships via MCP Tools

The system exposes eight specialized MCP (Memory-Core-Proxy) tools defined in [[`MemoryKnowledge/src/mcp/tools.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/src/mcp/tools.ts)](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/feat/server_team/MemoryKnowledge/src/mcp/tools.ts) and routed through [[`MemoryKnowledge/src/routes/code-graph.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/src/routes/code-graph.ts)](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/feat/server_team/MemoryKnowledge/src/routes/code-graph.ts). These tools map to the underlying `CodeGraphService` query methods.

### Core Query Tool Reference

| Tool | Function | Payload Structure |
|------|----------|-------------------|
| `code_search` | Symbol name lookup | `{ "code_graph_id": "cg_abc", "query": "parseConfig", "kind": "function", "limit": 10 }` |
| `code_explore` | File discovery | `{ "code_graph_id": "cg_abc", "query": "utils/", "maxFiles": 20 }` |
| `code_callers` | Find functions invoking symbol | `{ "code_graph_id": "cg_abc", "symbol": "parseConfig", "limit": 50 }` |
| `code_callees` | Find functions called by symbol | `{ "code_graph_id": "cg_abc", "symbol": "parseConfig", "limit": 50 }` |
| `code_impact` | Dependency chain analysis | `{ "code_graph_id": "cg_abc", "symbol": "parseConfig", "depth": 3 }` |
| `code_node` | Detailed symbol metadata | `{ "code_graph_id": "cg_abc", "symbol": "parseConfig", "includeCode": true }` |
| `code_status` | Indexing state check | `{ "code_graph_id": "cg_abc" }` |
| `code_files` | Repository file tree | `{ "code_graph_id": "cg_abc", "path": "src/", "format": "tree", "maxDepth": 3 }` |

### Traversing Call Hierarchies

To trace execution flow, invoke **`code_callers`** to identify functions that invoke your target symbol, or **`code_callees`** to see what functions the target invokes. Both return arrays of location objects containing `symbol`, `file`, and `line` properties that can be passed to `code_node` for source retrieval.

```bash

# Example: Finding what calls the authenticate function

curl -X POST /v3/code-graph/callers \
  -d '{"code_graph_id": "cg_abc", "symbol": "authenticate", "limit": 20}'

```

### Performing Impact Analysis

The **`code_impact`** tool performs a depth-limited traversal of the dependency graph to evaluate the blast radius of a proposed change. This is essential for refactoring safety and understanding downstream effects of modifications to critical functions.

```json
{
  "code_graph_id": "cg_abc",
  "symbol": "database.connect",
  "depth": 2
}

```

## Implementation Architecture

The query layer relies on type-safe definitions in [[`MemoryKnowledge/src/store/types.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/src/store/types.ts)](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/feat/server_team/MemoryKnowledge/src/store/types.ts), which declares `CodeGraphRow` interfaces and request/response structures. The `CodeGraphService` abstracts storage operations, providing methods like `get`, `list`, and `count` that the route handlers consume to serve the MCP tool endpoints.

## Summary

- **Creation**: `CodeGraphService.create` idempotently initializes graph assets and persists metadata to the knowledge store.
- **Indexing**: The `BuildQueue` schedules asynchronous worker tasks that clone repositories, parse symbols, and update status through discrete lifecycle stages.
- **Querying**: Eight MCP tools (`code_callers`, `code_callees`, `code_impact`, etc.) expose relationship traversal via HTTP endpoints defined in the code-graph router.
- **Status Tracking**: Poll `code_status` to determine when the graph transitions from `indexing` to `ready` and becomes queryable.

## Frequently Asked Questions

### How do I check if a CodeGraph has finished indexing?

Use the **`code_status`** MCP tool with the `code_graph_id` obtained during creation. The tool queries the underlying `CodeGraphRow` and returns the current status field, which will be `"ready"` when indexing completes successfully or `"failed"` if the build encountered errors.

### What is the difference between `code_callers` and `code_callees`?

**`code_callers`** returns the set of functions or methods that invoke the specified symbol (incoming edges), while **`code_callees`** returns the functions that the specified symbol invokes (outgoing edges). Use callers to find dependencies on a function; use callees to understand what a function depends upon.

### Can I query the graph while it is being indexed?

No. While the `BuildQueue` worker is processing the repository, the graph status remains `cloning` or `indexing`, and relationship queries will either return empty results or error responses. Wait for the `code_status` endpoint to report `"ready"` before executing `code_callers`, `code_impact`, or other relationship queries.

### How does the system prevent concurrent indexing of the same repository?

The **`BuildQueue`** class implements serial execution guarantees, ensuring that only one build task per `code_graph_id` runs at any time. Subsequent creation requests for the same repository and branch return the existing row immediately, while the queue ensures the asynchronous worker processes builds sequentially to prevent resource contention and data corruption.