codesearch 0.1.12

A fast, intelligent CLI tool with multiple search modes (regex, fuzzy, semantic), code analysis, and dead code detection for popular programming languages
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
415
416
417
418
419
420
//! Enhanced MCP tools for symbol-based search and analysis
//!
//! These tools provide AI agents with rich code understanding capabilities
//! without using LLM for search.

use crate::symbols::{
    indexer::SymbolIndexStore,
    relationships::RelationshipGraph,
    context::{create_search_result, SymbolContext},
    Symbol, SymbolKind, SymbolSearchResult, SymbolRelationType,
};
use rmcp::handler::server::wrapper::{Json, Parameters};
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Global symbol index store
static SYMBOL_STORE: once_cell::sync::Lazy<Arc<SymbolIndexStore>> =
    once_cell::sync::Lazy::new(|| {
        let store_path = std::env::current_dir()
            .unwrap()
            .join(".codesearch")
            .join("symbol_index");

        Arc::new(SymbolIndexStore::new(store_path))
    });

/// Global relationship graph
static RELATIONSHIP_GRAPH: once_cell::sync::Lazy<Arc<RelationshipGraph>> =
    once_cell::sync::Lazy::new(|| Arc::new(RelationshipGraph::new()));

/// Symbol search with rich context and relationships
pub async fn search_symbols_tool(
    params: Parameters<SearchSymbolsParams>,
) -> Json<Vec<SymbolSearchResult>> {
    let params = params.0;
    let path_buf = PathBuf::from(params.path.as_deref().unwrap_or("."));

    // Ensure index is up to date
    let _ = SYMBOL_STORE.index_directory(
        &path_buf,
        params.extensions.as_deref(),
        params.exclude.as_deref(),
    );

    // Build relationship graph if needed
    let symbols = SYMBOL_STORE.index().search_symbols(
        params.pattern.as_deref(),
        params.kind.as_ref(),
        params.file_path.as_deref(),
        None,
    );

    let mut results = Vec::new();

    for symbol in symbols {
        // Calculate relevance score
        let score = calculate_symbol_score(&symbol, &params);

        // Apply filters
        if let Some(ref kind) = params.kind {
            if symbol.kind != *kind {
                continue;
            }
        }

        if let Some(ref file_path) = params.file_path {
            if symbol.file_path != *file_path {
                continue;
            }
        }

        // Create result with context
        let mut result = create_search_result(&symbol, score, params.context_lines.unwrap_or(3));

        // Add related symbols if requested
        if params.include_related.unwrap_or(false) {
            result.related_symbols = find_related_symbols(&symbol);
        }

        results.push(result);
    }

    // Sort by score
    results.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));

    // Limit results
    if let Some(limit) = params.limit {
        results.truncate(limit);
    }

    Json(results)
}

/// Get detailed information about a specific symbol
pub async fn get_symbol_details_tool(
    params: Parameters<GetSymbolDetailsParams>,
) -> Json<serde_json::Value> {
    let params = params.0;

    // Try to find by ID first
    let symbol = if let Some(ref id) = params.id {
        SYMBOL_STORE.index().get_symbol(id)
    } else if let Some(ref name) = params.name {
        // Find by name
        let matches = SYMBOL_STORE.index().find_by_name(name);
        if let Some(ref file_path) = params.file_path {
            matches.into_iter().find(|s| &s.file_path == file_path)
        } else {
            matches.first().cloned()
        }
    } else {
        None
    };

    if let Some(symbol) = symbol {
        let file_path = Path::new(&symbol.file_path);
        let context = SymbolContext::extract(file_path, symbol.line, 5);

        let relationships = RELATIONSHIP_GRAPH.get_relationships(&symbol.id);

        Json(serde_json::json!({
            "symbol": symbol,
            "context": context.ok(),
            "relationships": relationships,
        }))
    } else {
        Json(serde_json::json!({
            "error": "Symbol not found"
        }))
    }
}

/// Find relationships between symbols
pub async fn find_symbol_relationships_tool(
    params: Parameters<FindSymbolRelationshipsParams>,
) -> Json<serde_json::Value> {
    let params = params.0;

    // Find the symbol
    let symbol = if let Some(ref id) = params.symbol_id {
        RELATIONSHIP_GRAPH.get_symbol(id)
    } else if let Some(ref name) = params.symbol_name {
        SYMBOL_STORE.index().find_by_name(name).first().cloned()
    } else {
        None
    };

    if let Some(symbol) = symbol {
        let mut related = Vec::new();

        // Get relationships by type if specified
        if let Some(ref relation_types) = params.relation_types {
            for rel_type in relation_types {
                let rel_type: SymbolRelationType = rel_type.clone();
                let relations = RELATIONSHIP_GRAPH.get_relationships_by_type(
                    &symbol.id,
                    rel_type,
                );
                for relation in relations {
                    if let Some(related_symbol) = RELATIONSHIP_GRAPH.get_symbol(&relation.symbol_id) {
                        related.push(serde_json::json!({
                            "symbol": related_symbol,
                            "relation_type": relation.relation_type,
                            "confidence": relation.confidence,
                        }));
                    }
                }
            }
        } else {
            // Get all relationships
            let relations = RELATIONSHIP_GRAPH.get_relationships(&symbol.id);
            for relation in relations {
                if let Some(related_symbol) = RELATIONSHIP_GRAPH.get_symbol(&relation.symbol_id) {
                    related.push(serde_json::json!({
                        "symbol": related_symbol,
                        "relation_type": relation.relation_type,
                        "confidence": relation.confidence,
                    }));
                }
            }
        }

        Json(serde_json::json!({
            "symbol": symbol,
            "related_symbols": related,
        }))
    } else {
        Json(serde_json::json!({
            "error": "Symbol not found"
        }))
    }
}

/// Build or update the symbol index
pub async fn build_symbol_index_tool(
    params: Parameters<BuildSymbolIndexParams>,
) -> Json<serde_json::Value> {
    let params = params.0;
    let path_buf = PathBuf::from(params.path.as_deref().unwrap_or("."));

    let start = std::time::Instant::now();
    let count = SYMBOL_STORE.index_directory(
        &path_buf,
        params.extensions.as_deref(),
        params.exclude.as_deref(),
    ).unwrap_or(0);

    let duration = start.elapsed();

    let stats = SYMBOL_STORE.index().get_stats();

    Json(serde_json::json!({
        "success": true,
        "indexed_symbols": count,
        "duration_ms": duration.as_millis(),
        "total_symbols": stats.total_symbols,
        "total_files": stats.total_files,
        "symbols_by_kind": stats.symbols_by_kind,
        "symbols_by_language": stats.symbols_by_language,
    }))
}

/// Get index statistics
pub async fn get_index_stats_tool(
    params: Parameters<GetIndexStatsParams>,
) -> Json<serde_json::Value> {
    let _params = params.0;

    let stats = SYMBOL_STORE.index().get_stats();

    Json(serde_json::json!({
        "total_symbols": stats.total_symbols,
        "total_files": stats.total_files,
        "symbols_by_kind": stats.symbols_by_kind,
        "symbols_by_language": stats.symbols_by_language,
        "index_size_bytes": stats.index_size_bytes,
        "last_updated": stats.last_updated,
    }))
}

/// Find hierarchy (inheritance/implementation)
pub async fn find_symbol_hierarchy_tool(
    params: Parameters<FindSymbolHierarchyParams>,
) -> Json<serde_json::Value> {
    let params = params.0;

    let symbol = if let Some(ref id) = params.symbol_id {
        RELATIONSHIP_GRAPH.get_symbol(id)
    } else if let Some(ref name) = params.symbol_name {
        SYMBOL_STORE.index().find_by_name(name).first().cloned()
    } else {
        None
    };

    if let Some(symbol) = symbol {
        let hierarchy = RELATIONSHIP_GRAPH.find_hierarchy(&symbol.id);

        Json(serde_json::json!({
            "root_symbol": symbol,
            "hierarchy": hierarchy,
        }))
    } else {
        Json(serde_json::json!({
            "error": "Symbol not found"
        }))
    }
}

/// Calculate relevance score for a symbol
fn calculate_symbol_score(symbol: &Symbol, params: &SearchSymbolsParams) -> f64 {
    let mut score: f64 = 50.0; // Base score

    // Boost for exact name match
    if let Some(ref pattern) = params.pattern {
        if symbol.name == *pattern {
            score += 30.0;
        } else if symbol.name.contains(pattern) {
            score += 15.0;
        }
    }

    // Boost for public symbols
    if symbol.is_public() {
        score += 10.0;
    }

    // Boost for functions/classes (most interesting)
    if symbol.is_function() || symbol.is_type() {
        score += 10.0;
    }

    // Apply visibility filter
    if let Some(ref visibility) = params.visibility {
        if symbol.visibility != *visibility {
            score -= 50.0; // Penalize non-matching visibility
        }
    }

    score.min(100.0).max(0.0)
}

/// Find related symbols
fn find_related_symbols(symbol: &Symbol) -> Vec<crate::symbols::SymbolRelation> {
    let relations = RELATIONSHIP_GRAPH.get_relationships(&symbol.id);

    relations
        .into_iter()
        .map(|r| crate::symbols::SymbolRelation {
            symbol_id: r.symbol_id,
            relation_type: r.relation_type,
            confidence: r.confidence,
        })
        .collect()
}

// ===== New Parameter Structures =====

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct SearchSymbolsParams {
    /// Search pattern (can be name or regex)
    #[serde(default)]
    pub pattern: Option<String>,

    /// Directory to search (default: current directory)
    #[serde(default)]
    pub path: Option<String>,

    /// File extensions to include
    #[serde(default)]
    pub extensions: Option<Vec<String>>,

    /// Exclude directories
    #[serde(default)]
    pub exclude: Option<Vec<String>>,

    /// Filter by symbol kind
    #[serde(default)]
    pub kind: Option<SymbolKind>,

    /// Filter by file path
    #[serde(default)]
    pub file_path: Option<String>,

    /// Filter by visibility
    #[serde(default)]
    pub visibility: Option<crate::symbols::SymbolVisibility>,

    /// Number of context lines to include
    #[serde(default)]
    pub context_lines: Option<usize>,

    /// Include related symbols in results
    #[serde(default)]
    pub include_related: Option<bool>,

    /// Maximum number of results
    #[serde(default)]
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct GetSymbolDetailsParams {
    /// Symbol ID
    #[serde(default)]
    pub id: Option<String>,

    /// Symbol name (if ID not provided)
    #[serde(default)]
    pub name: Option<String>,

    /// File path to disambiguate
    #[serde(default)]
    pub file_path: Option<String>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct FindSymbolRelationshipsParams {
    /// Symbol ID
    #[serde(default)]
    pub symbol_id: Option<String>,

    /// Symbol name (if ID not provided)
    #[serde(default)]
    pub symbol_name: Option<String>,

    /// Filter by relationship types
    #[serde(default)]
    pub relation_types: Option<Vec<SymbolRelationType>>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct BuildSymbolIndexParams {
    /// Directory to index (default: current directory)
    #[serde(default)]
    pub path: Option<String>,

    /// File extensions to include
    #[serde(default)]
    pub extensions: Option<Vec<String>>,

    /// Exclude directories
    #[serde(default)]
    pub exclude: Option<Vec<String>>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct GetIndexStatsParams {
    // No parameters needed
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct FindSymbolHierarchyParams {
    /// Symbol ID
    #[serde(default)]
    pub symbol_id: Option<String>,

    /// Symbol name (if ID not provided)
    #[serde(default)]
    pub symbol_name: Option<String>,
}