symgraph 2026.5.30

Semantic code intelligence library and MCP server - build knowledge graphs of codebases
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! MCP (Model Context Protocol) server implementation
//!
//! Exposes the code graph functionality as MCP tools:
//! - symgraph-context: Build task-specific code context
//! - symgraph-search: Find symbols by name
//! - symgraph-callers: Find all callers of a symbol
//! - symgraph-callees: Find all callees of a symbol
//! - symgraph-impact: Analyze change impact
//! - symgraph-node: Get detailed symbol information
//! - symgraph-status: Get index statistics
//! - symgraph-definition: Get source code of a symbol
//! - symgraph-file: List all symbols in a file
//! - symgraph-references: Find all references to a symbol
//! - symgraph-reindex: Trigger incremental reindexing
//! - symgraph-hierarchy: Get class/module hierarchy
//! - symgraph-path: Find call paths between symbols
//! - symgraph-unused: Find unused/dead code
//! - symgraph-implementations: Find implementations of interfaces/traits
//! - symgraph-diff-impact: Analyze impact of code changes
//! - symgraph-blame: Git blame a symbol's definition
//! - symgraph-churn: File change frequency (volatility)
//! - symgraph-module-graph: Dependency graph folded to a file/dir/module boundary
//! - symgraph-coupling-score: Rank coupling on strength × distance × volatility
//! - symgraph-god-struct: Rank structs by architectural debt
//! - symgraph-dispatch-sites: Find where an enum is matched (control coupling)

mod constants;
mod format;
mod handlers;
mod types;

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};

use rmcp::{
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::{ServerCapabilities, ServerInfo},
    tool, tool_handler, tool_router, ServerHandler,
};

use crate::db::Database;

pub use types::*;

/// Wrapper around `Database` that opts in to `Sync`.
///
/// `rusqlite::Connection` is `!Sync` because it uses `RefCell` internally.
/// We wrap it in an `RwLock` so that access is serialized at the lock level.
///
/// NOTE: concurrent read-locks are technically unsound with raw `RefCell`,
/// but the underlying SQLite C library is compiled with `SQLITE_THREADSAFE=1`
/// (serialized mode) by default, which serializes all access at the C level.
/// If true concurrent reader parallelism is needed in the future, switch to a
/// connection pool (e.g., `r2d2_sqlite`).
pub struct SyncDatabase(pub Database);

// SAFETY: All `Database` access is mediated by an `RwLock`. The underlying
// SQLite library provides its own thread-safety guarantees in serialized mode.
unsafe impl Sync for SyncDatabase {}

impl std::ops::Deref for SyncDatabase {
    type Target = Database;
    fn deref(&self) -> &Database {
        &self.0
    }
}

impl std::ops::DerefMut for SyncDatabase {
    fn deref_mut(&mut self) -> &mut Database {
        &mut self.0
    }
}

/// MCP server handler for symgraph
#[derive(Clone)]
pub struct SymgraphHandler {
    #[allow(dead_code)]
    tool_router: ToolRouter<Self>,
    db: Arc<RwLock<SyncDatabase>>,
    project_root: String,
    /// Flag indicating whether a background reindex is currently in progress.
    is_reindexing: Arc<AtomicBool>,
}

#[tool_router]
impl SymgraphHandler {
    pub fn new(db: Database, project_root: String) -> Self {
        Self {
            tool_router: Self::tool_router(),
            db: Arc::new(RwLock::new(SyncDatabase(db))),
            project_root,
            is_reindexing: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Create a handler with a pre-wrapped database (for sharing across HTTP sessions)
    pub fn new_shared(db: Arc<RwLock<SyncDatabase>>, project_root: String) -> Self {
        Self {
            tool_router: Self::tool_router(),
            db,
            project_root,
            is_reindexing: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Helper to acquire a read lock on the database and run a closure.
    fn with_db<F>(&self, f: F) -> String
    where
        F: FnOnce(&Database) -> Result<String, String>,
    {
        match self.db.read() {
            Ok(guard) => match f(&guard) {
                Ok(output) => output,
                Err(e) => format!("Error: {}", e),
            },
            Err(e) => format!("Error: {}", e),
        }
    }

    /// Helper to acquire a mutable lock on the database and run a closure.
    #[allow(dead_code)]
    fn with_db_mut<F>(&self, f: F) -> String
    where
        F: FnOnce(&mut Database) -> Result<String, String>,
    {
        match self.db.write() {
            Ok(mut guard) => match f(&mut guard) {
                Ok(output) => output,
                Err(e) => format!("Error: {}", e),
            },
            Err(e) => format!("Error: {}", e),
        }
    }

    /// Build focused context for a specific task
    #[tool(
        name = "symgraph-context",
        description = "Build focused code context for a specific task. Returns entry points, related symbols, and code snippets."
    )]
    fn symgraph_context(&self, Parameters(req): Parameters<ContextRequest>) -> String {
        let project_root = &self.project_root;
        self.with_db(|db| handlers::context::handle_context(db, project_root, &req))
    }

    /// Quick symbol search by name
    #[tool(
        name = "symgraph-search",
        description = "Quick symbol search by name. Returns locations only (no code)."
    )]
    fn symgraph_search(&self, Parameters(req): Parameters<SearchRequest>) -> String {
        self.with_db(|db| handlers::search::handle_search(db, &req))
    }

    /// Find all callers of a symbol
    #[tool(
        name = "symgraph-callers",
        description = "Find all functions/methods that call a specific symbol."
    )]
    fn symgraph_callers(&self, Parameters(req): Parameters<SymbolRequest>) -> String {
        self.with_db(|db| handlers::graph::handle_callers(db, &req))
    }

    /// Find all callees of a symbol
    #[tool(
        name = "symgraph-callees",
        description = "Find all functions/methods that a specific symbol calls."
    )]
    fn symgraph_callees(&self, Parameters(req): Parameters<SymbolRequest>) -> String {
        self.with_db(|db| handlers::graph::handle_callees(db, &req))
    }

    /// Analyze the impact of changing a symbol
    #[tool(
        name = "symgraph-impact",
        description = "Analyze the impact of changing a symbol. Breaks inbound coupling down by edge kind (method-call/contract, field-read/model, field-write/intrusive), counts inbound modules, and (with churn=true) annotates volatility. Supports format='json'."
    )]
    fn symgraph_impact(&self, Parameters(req): Parameters<ImpactRequest>) -> String {
        let project_root = self.project_root.clone();
        self.with_db(|db| handlers::graph::handle_impact(db, &project_root, &req))
    }

    /// Get the full source code definition of a symbol
    #[tool(
        name = "symgraph-definition",
        description = "Get the full source code of a symbol. Returns the complete definition with surrounding context lines."
    )]
    fn symgraph_definition(&self, Parameters(req): Parameters<DefinitionRequest>) -> String {
        let project_root = &self.project_root;
        self.with_db(|db| handlers::symbol::handle_definition(db, project_root, &req))
    }

    /// List all symbols in a specific file
    #[tool(
        name = "symgraph-file",
        description = "List all symbols defined in a specific file. Returns functions, classes, methods, etc."
    )]
    fn symgraph_file(&self, Parameters(req): Parameters<FileRequest>) -> String {
        self.with_db(|db| handlers::file::handle_file(db, &req))
    }

    /// Find all references to a symbol
    #[tool(
        name = "symgraph-references",
        description = "Find all references to a symbol including calls, imports, type usages, and other relationships."
    )]
    fn symgraph_references(&self, Parameters(req): Parameters<SymbolRequest>) -> String {
        self.with_db(|db| handlers::symbol::handle_references(db, &req))
    }

    /// Trigger incremental reindexing (runs in background, returns immediately)
    #[tool(
        name = "symgraph-reindex",
        description = "Trigger incremental reindexing of the codebase. Only changed files are re-parsed. Runs in background and returns immediately."
    )]
    fn symgraph_reindex(&self, Parameters(req): Parameters<ReindexRequest>) -> String {
        // If a reindex is already running, refuse to start another one.
        if self
            .is_reindexing
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_err()
        {
            return "Reindex already in progress. Use symgraph-status to check.".to_string();
        }

        let db = Arc::clone(&self.db);
        let project_root = self.project_root.clone();
        let is_reindexing = Arc::clone(&self.is_reindexing);

        let file_count_hint = req.files.as_ref().map(|f| f.len());

        tokio::task::spawn_blocking(move || {
            let result = match db.write() {
                Ok(mut guard) => {
                    match handlers::reindex::handle_reindex(&mut guard, &project_root, &req) {
                        Ok(output) => output,
                        Err(e) => format!("Error: {}", e),
                    }
                }
                Err(e) => format!("Error acquiring write lock: {}", e),
            };
            is_reindexing.store(false, Ordering::SeqCst);
            tracing::info!("Background reindex finished: {}", result);
        });

        match file_count_hint {
            Some(n) => format!(
                "Reindexing {} file(s) in background. Use symgraph-status to check progress.",
                n
            ),
            None => {
                "Reindexing all changed files in background. Use symgraph-status to check progress."
                    .to_string()
            }
        }
    }

    /// Get detailed information about a symbol
    #[tool(
        name = "symgraph-node",
        description = "Get detailed information about a specific code symbol."
    )]
    fn symgraph_node(&self, Parameters(req): Parameters<SymbolRequest>) -> String {
        self.with_db(|db| handlers::symbol::handle_node(db, &req))
    }

    /// Get index statistics
    #[tool(
        name = "symgraph-status",
        description = "Get the status of the symgraph index. Shows statistics about indexed files, symbols, and relationships."
    )]
    fn symgraph_status(&self) -> String {
        let reindexing = self.is_reindexing.load(Ordering::SeqCst);
        self.with_db(|db| {
            let mut output = handlers::status::handle_status(db)?;
            if reindexing {
                output.push_str("\n**Reindex:** In progress\n");
            }
            Ok(output)
        })
    }

    /// Get class/module hierarchy
    #[tool(
        name = "symgraph-hierarchy",
        description = "Get the hierarchy of a symbol showing parent/child contains relationships (e.g., class contains methods)."
    )]
    fn symgraph_hierarchy(&self, Parameters(req): Parameters<SymbolRequest>) -> String {
        self.with_db(|db| handlers::hierarchy::handle_hierarchy(db, &req))
    }

    /// Find call path between two symbols
    #[tool(
        name = "symgraph-path",
        description = "Find call paths from one symbol to another. Shows how function A reaches function B through intermediate calls."
    )]
    fn symgraph_path(&self, Parameters(req): Parameters<PathRequest>) -> String {
        self.with_db(|db| handlers::path::handle_path(db, &req))
    }

    /// Find unused/dead code
    #[tool(
        name = "symgraph-unused",
        description = "Find unused symbols (functions, methods, classes) with no incoming references. Helps identify dead code."
    )]
    fn symgraph_unused(&self) -> String {
        self.with_db(handlers::unused::handle_unused)
    }

    /// Find implementations of an interface/trait
    #[tool(
        name = "symgraph-implementations",
        description = "Find all classes/structs that implement an interface or extend a trait/class."
    )]
    fn symgraph_implementations(&self, Parameters(req): Parameters<SymbolRequest>) -> String {
        self.with_db(|db| handlers::implementations::handle_implementations(db, &req))
    }

    /// Analyze impact of code changes
    #[tool(
        name = "symgraph-diff-impact",
        description = "Analyze the impact of changing a specific region of code. Shows directly modified symbols and their callers."
    )]
    fn symgraph_diff_impact(&self, Parameters(req): Parameters<DiffImpactRequest>) -> String {
        let project_root = &self.project_root;
        self.with_db(|db| handlers::diff_impact::handle_diff_impact(db, project_root, &req))
    }

    /// Git blame a symbol's definition lines
    #[tool(
        name = "symgraph-blame",
        description = "Run git blame over the lines of a symbol's definition. Shows who last changed each line and when."
    )]
    fn symgraph_blame(&self, Parameters(req): Parameters<BlameRequest>) -> String {
        let project_root = &self.project_root;
        self.with_db(|db| handlers::blame::handle_blame(db, project_root, &req))
    }

    /// Git churn / change-frequency analysis
    #[tool(
        name = "symgraph-churn",
        description = "Show file change frequency (churn) over a recent window. Highlights hotspots most likely to harbor bugs."
    )]
    fn symgraph_churn(&self, Parameters(req): Parameters<ChurnRequest>) -> String {
        let project_root = self.project_root.clone();
        match handlers::churn::handle_churn(&project_root, &req) {
            Ok(s) => s,
            Err(e) => format!("Error: {}", e),
        }
    }

    /// Module dependency graph: fan-in/out and cycles at a chosen boundary
    #[tool(
        name = "symgraph-module-graph",
        description = "Aggregate the resolved graph to a file/dir/module boundary. Returns the dependency adjacency list with edge counts, fan-in/fan-out per node, and detected cycles (SCCs). Supports format='json'. Reindex after edits."
    )]
    fn symgraph_module_graph(&self, Parameters(req): Parameters<ModuleGraphRequest>) -> String {
        let project_root = self.project_root.clone();
        self.with_db(|db| handlers::module_graph::handle_module_graph(db, &project_root, &req))
    }

    /// Coupling score: strength × distance × volatility per module pair
    #[tool(
        name = "symgraph-coupling-score",
        description = "Rank module-pair coupling on strength (contract/model/intrusive) × distance × volatility (churn). Produces the hotspots table directly. Supports format='json'. Reindex after edits."
    )]
    fn symgraph_coupling_score(&self, Parameters(req): Parameters<ModuleGraphRequest>) -> String {
        let project_root = self.project_root.clone();
        self.with_db(|db| handlers::module_graph::handle_coupling_score(db, &project_root, &req))
    }

    /// God-struct / hub report: structs ranked by architectural debt
    #[tool(
        name = "symgraph-god-struct",
        description = "Rank structs/classes by pub-field count × inbound-reference count × churn — the 'where is the architectural debt' entry point. Supports format='json'."
    )]
    fn symgraph_god_struct(&self, Parameters(req): Parameters<GodStructRequest>) -> String {
        let project_root = self.project_root.clone();
        self.with_db(|db| handlers::god_struct::handle_god_struct(db, &project_root, &req))
    }

    /// Dispatch sites: files that match/switch on an enum's members
    #[tool(
        name = "symgraph-dispatch-sites",
        description = "Find every file that dispatches on a member of the given enum (control coupling). Verifies completeness before a trait/strategy refactor. Supports format='json'."
    )]
    fn symgraph_dispatch_sites(&self, Parameters(req): Parameters<DispatchSitesRequest>) -> String {
        self.with_db(|db| handlers::dispatch_sites::handle_dispatch_sites(db, &req))
    }
}

#[tool_handler]
impl ServerHandler for SymgraphHandler {
    fn get_info(&self) -> ServerInfo {
        let mut info = ServerInfo::new(ServerCapabilities::builder().enable_tools().build());
        info.instructions = Some(
            "symgraph provides semantic code intelligence for exploring codebases. \
            Use symgraph-context to build task-focused context, symgraph-search for quick lookups, \
            symgraph-callers/callees/impact for understanding code relationships, \
            symgraph-definition to view source code, symgraph-file to list symbols in a file, \
            symgraph-references for all usages of a symbol, symgraph-hierarchy for class/module structure, \
            symgraph-path to find call paths between functions, symgraph-unused to find dead code, \
            symgraph-implementations to find interface/trait implementations, \
            symgraph-diff-impact to analyze change impact, symgraph-blame and symgraph-churn for \
            git history/volatility, and symgraph-reindex to refresh after edits. \
            For coupling analysis: symgraph-module-graph aggregates dependencies to a file/dir/module \
            boundary with fan-in/out and cycles; symgraph-coupling-score ranks hotspots on \
            strength × distance × volatility; symgraph-god-struct surfaces architectural debt; and \
            symgraph-dispatch-sites finds where an enum is matched. Coupling tools rely on field/import/ \
            dispatch edges, so run symgraph-reindex after code changes."
                .into(),
        );
        info
    }
}