sqry-mcp 7.2.0

MCP server for sqry semantic code search
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
//! Navigation tool execution.
//!
//! This module implements the code navigation tools for finding definitions,
//! references, hover info, document symbols, and workspace symbol search.

use std::path::PathBuf;
use std::time::Instant;

use anyhow::{Result, anyhow};
use sqry_core::graph::unified::{FileScope, ResolutionMode, SymbolCandidateOutcome, SymbolQuery};

use crate::engine::engine_for_workspace;
use crate::execution::symbol_utils::{
    get_classpath_provenance_for_node, get_macro_metadata_for_node,
};
use crate::execution::types::{
    DefinitionData, DocumentSymbolData, GetDefinitionData, GetDocumentSymbolsData,
    GetReferencesData, GetWorkspaceSymbolsData, HoverInfoData, ReferenceLocationData,
    ToolExecution, WorkspaceSymbolData,
};
use crate::execution::utils::duration_to_ms;
use crate::tools::{
    GetDefinitionArgs, GetDocumentSymbolsArgs, GetHoverInfoArgs, GetReferencesArgs,
    GetWorkspaceSymbolsArgs,
};

/// Execute the `get_definition` tool to find where a symbol is defined.
/// Resolve workspace path from args.path parameter.
///
/// If path is "." (default), returns None to trigger discovery.
/// Otherwise returns Some(path) for explicit workspace resolution.
fn resolve_workspace_path(path: &str) -> Option<PathBuf> {
    if path == "." {
        None
    } else {
        Some(PathBuf::from(path))
    }
}

fn candidate_nodes_for_symbol(
    snapshot: &sqry_core::graph::unified::concurrent::GraphSnapshot,
    symbol: &str,
) -> Vec<sqry_core::graph::unified::NodeId> {
    match snapshot.find_symbol_candidates(&SymbolQuery {
        symbol,
        file_scope: FileScope::Any,
        mode: ResolutionMode::AllowSuffixCandidates,
    }) {
        SymbolCandidateOutcome::Candidates(candidates) => candidates,
        SymbolCandidateOutcome::NotFound | SymbolCandidateOutcome::FileNotIndexed => Vec::new(),
    }
}

fn resolve_hover_node(
    snapshot: &sqry_core::graph::unified::concurrent::GraphSnapshot,
    symbol: &str,
) -> Result<sqry_core::graph::unified::NodeId> {
    match candidate_nodes_for_symbol(snapshot, symbol).as_slice() {
        [] => Err(anyhow!("Symbol '{symbol}' not found")),
        [node_id] => Ok(*node_id),
        candidates => Err(anyhow!(
            "Symbol '{symbol}' is ambiguous ({} candidates). Use a canonical qualified name.",
            candidates.len()
        )),
    }
}
pub fn execute_get_definition(
    args: &GetDefinitionArgs,
) -> Result<ToolExecution<GetDefinitionData>> {
    let start = Instant::now();
    let workspace_path = resolve_workspace_path(&args.path);
    let engine = engine_for_workspace(workspace_path.as_ref())?;
    let workspace_root = engine.workspace_root().to_path_buf();

    tracing::debug!(symbol = %args.symbol, "Executing get_definition tool");

    let graph = engine.ensure_graph()?;
    let snapshot = graph.snapshot();

    let files = snapshot.files();
    let strings = snapshot.strings();

    // Find nodes matching the symbol name
    let mut definitions: Vec<DefinitionData> = Vec::new();

    for node_id in candidate_nodes_for_symbol(&snapshot, &args.symbol) {
        let Some(entry) = snapshot.get_node(node_id) else {
            continue;
        };
        let name = strings
            .resolve(entry.name)
            .map(|s| s.to_string())
            .unwrap_or_default();
        let qualified_name = crate::execution::symbol_utils::display_entry_qualified_name(
            entry, strings, files, &name,
        );

        let file_path = files
            .resolve(entry.file)
            .map(|p| {
                crate::execution::symbol_utils::relative_path_forward_slash(
                    p.as_ref(),
                    &workspace_root,
                )
            })
            .unwrap_or_default();

        let language = files
            .language_for_file(entry.file)
            .map_or_else(|| "unknown".to_string(), |l| l.to_string());

        let macro_metadata = get_macro_metadata_for_node(&snapshot, node_id);
        let provenance = get_classpath_provenance_for_node(&snapshot, node_id);

        definitions.push(DefinitionData {
            name,
            qualified_name,
            kind: format!("{:?}", entry.kind),
            file_path,
            line: entry.start_line,
            column: entry.start_column,
            language,
            preview: None, // Would need file content to provide preview
            macro_metadata,
            provenance,
        });
    }

    let total = definitions.len() as u64;
    let data = GetDefinitionData { definitions, total };

    tracing::debug!(total = total, "get_definition completed");

    Ok(ToolExecution {
        data,
        used_index: false,
        used_graph: true,
        graph_metadata: None,
        execution_ms: duration_to_ms(start.elapsed()),
        next_page_token: None,
        total: Some(total),
        truncated: Some(false),
        candidates_scanned: None,
        workspace_path: crate::execution::symbol_utils::path_to_forward_slash(workspace_root),
    })
}

/// Find all nodes that match the given symbol name or qualified name.
fn find_target_nodes(
    snapshot: &sqry_core::graph::unified::concurrent::GraphSnapshot,
    symbol: &str,
) -> Vec<sqry_core::graph::unified::NodeId> {
    candidate_nodes_for_symbol(snapshot, symbol)
}

/// Collect declaration references for target nodes.
fn collect_declaration_refs(
    graph: &sqry_core::graph::unified::concurrent::CodeGraph,
    target_nodes: &[sqry_core::graph::unified::NodeId],
    workspace_root: &std::path::Path,
    seen: &mut std::collections::HashSet<(String, u32, u32)>,
) -> Vec<ReferenceLocationData> {
    let files = graph.files();
    let mut references = Vec::new();

    for node_id in target_nodes {
        if let Some(entry) = graph.nodes().get(*node_id) {
            let file_path = files
                .resolve(entry.file)
                .map(|p| {
                    crate::execution::symbol_utils::relative_path_forward_slash(
                        p.as_ref(),
                        workspace_root,
                    )
                })
                .unwrap_or_default();

            // Build provenance if this declaration is in an external (classpath) file
            let provenance = if files.is_external(entry.file) {
                use sqry_core::graph::unified::storage::NodeMetadata;
                graph
                    .macro_metadata()
                    .get_metadata(*node_id)
                    .and_then(|m| match m {
                        NodeMetadata::Classpath(cp) => {
                            Some(crate::execution::types::ProvenanceData {
                                source: "classpath",
                                coordinates: cp.coordinates.clone(),
                                is_direct: cp.is_direct_dependency,
                                jar_path: Some(cp.jar_path.clone()),
                            })
                        }
                        NodeMetadata::Macro(_) => None,
                    })
            } else {
                None
            };

            let loc_key = (file_path.clone(), entry.start_line, entry.start_column);
            if !seen.contains(&loc_key) {
                seen.insert(loc_key);
                references.push(ReferenceLocationData {
                    file_path,
                    line: entry.start_line,
                    column: entry.start_column,
                    preview: None,
                    is_declaration: true,
                    provenance,
                });
            }
        }
    }

    references
}

/// Collect caller references (incoming edges) for target nodes.
fn collect_caller_refs(
    graph: &sqry_core::graph::unified::concurrent::CodeGraph,
    target_nodes: &[sqry_core::graph::unified::NodeId],
    max_results: usize,
    workspace_root: &std::path::Path,
    seen: &mut std::collections::HashSet<(String, u32, u32)>,
    existing_count: usize,
) -> Vec<ReferenceLocationData> {
    let files = graph.files();
    let mut references = Vec::new();

    for target_id in target_nodes {
        // Use the public edges_to API which handles reverse-store remapping
        // (source = original caller, target = query target).
        let incoming = graph.edges().edges_to(*target_id);
        for edge_ref in &incoming {
            if existing_count + references.len() >= max_results {
                break;
            }

            // Prefer edge spans (call-site locations) over source node location.
            // Edge spans contain the exact call-site position recorded by the graph
            // builder via `span_from_node(node)`, giving accurate line numbers even
            // when the source node's span is imprecise or missing.
            // Build provenance for the source node if it's from a classpath file
            let provenance = {
                use sqry_core::graph::unified::storage::NodeMetadata;
                if files.is_external(edge_ref.file) {
                    graph
                        .macro_metadata()
                        .get_metadata(edge_ref.source)
                        .and_then(|m| match m {
                            NodeMetadata::Classpath(cp) => {
                                Some(crate::execution::types::ProvenanceData {
                                    source: "classpath",
                                    coordinates: cp.coordinates.clone(),
                                    is_direct: cp.is_direct_dependency,
                                    jar_path: Some(cp.jar_path.clone()),
                                })
                            }
                            NodeMetadata::Macro(_) => None,
                        })
                } else {
                    None
                }
            };

            if edge_ref.spans.is_empty() {
                // Fallback: no edge spans — use source node location (existing behavior).
                if let Some(entry) = graph.nodes().get(edge_ref.source) {
                    let file_path = files
                        .resolve(entry.file)
                        .map(|p| {
                            crate::execution::symbol_utils::relative_path_forward_slash(
                                p.as_ref(),
                                workspace_root,
                            )
                        })
                        .unwrap_or_default();

                    let loc_key = (file_path.clone(), entry.start_line, entry.start_column);
                    if !seen.contains(&loc_key) {
                        seen.insert(loc_key);
                        references.push(ReferenceLocationData {
                            file_path,
                            line: entry.start_line,
                            column: entry.start_column,
                            preview: None,
                            is_declaration: false,
                            provenance: provenance.clone(),
                        });
                    }
                }
            } else {
                // Resolve file path from the edge's FileId (preferred), falling back
                // to the source node's file if edge file resolution fails.
                let edge_file_path = files.resolve(edge_ref.file).map(|p| {
                    crate::execution::symbol_utils::relative_path_forward_slash(
                        p.as_ref(),
                        workspace_root,
                    )
                });
                let file_path = edge_file_path.unwrap_or_else(|| {
                    graph
                        .nodes()
                        .get(edge_ref.source)
                        .and_then(|entry| {
                            files.resolve(entry.file).map(|p| {
                                crate::execution::symbol_utils::relative_path_forward_slash(
                                    p.as_ref(),
                                    workspace_root,
                                )
                            })
                        })
                        .unwrap_or_default()
                });

                for span in &edge_ref.spans {
                    if existing_count + references.len() >= max_results {
                        break;
                    }
                    // Edge spans are raw tree-sitter coordinates (0-indexed lines,
                    // 0-indexed columns). Normalize lines to 1-indexed to match
                    // the convention in apply_span_to_entry (staging.rs:257).
                    // Columns are passed through as-is (0-indexed), matching how
                    // NodeEntry.start_column is already stored.
                    let line = u32::try_from(span.start.line.saturating_add(1)).unwrap_or(u32::MAX);
                    let column = u32::try_from(span.start.column).unwrap_or(u32::MAX);

                    let loc_key = (file_path.clone(), line, column);
                    if !seen.contains(&loc_key) {
                        seen.insert(loc_key);
                        references.push(ReferenceLocationData {
                            file_path: file_path.clone(),
                            line,
                            column,
                            preview: None,
                            is_declaration: false,
                            provenance: provenance.clone(),
                        });
                    }
                }
            }
        }
    }

    references
}

/// Execute the `get_references` tool to find all references to a symbol.
pub fn execute_get_references(
    args: &GetReferencesArgs,
) -> Result<ToolExecution<GetReferencesData>> {
    let start = Instant::now();
    let workspace_path = resolve_workspace_path(&args.path);
    let engine = engine_for_workspace(workspace_path.as_ref())?;
    let workspace_root = engine.workspace_root().to_path_buf();

    tracing::debug!(symbol = %args.symbol, "Executing get_references tool");

    let graph = engine.ensure_graph()?;
    let snapshot = graph.snapshot();

    // Find definition nodes for the symbol
    let target_node_ids = find_target_nodes(&snapshot, &args.symbol);

    // Collect references
    let mut references: Vec<ReferenceLocationData> = Vec::new();
    let mut seen_locations = std::collections::HashSet::new();

    // Include declarations if requested
    if args.include_declaration {
        references.extend(collect_declaration_refs(
            &graph,
            &target_node_ids,
            &workspace_root,
            &mut seen_locations,
        ));
    }

    // Find callers (incoming edges)
    references.extend(collect_caller_refs(
        &graph,
        &target_node_ids,
        args.max_results,
        &workspace_root,
        &mut seen_locations,
        references.len(),
    ));

    // Get macro metadata from the first target node (the definition)
    let macro_metadata = target_node_ids
        .first()
        .and_then(|&nid| get_macro_metadata_for_node(&snapshot, nid));

    let total = references.len() as u64;
    let data = GetReferencesData {
        symbol: args.symbol.clone(),
        references,
        total,
        macro_metadata,
    };

    tracing::debug!(total = total, "get_references completed");

    Ok(ToolExecution {
        data,
        used_index: false,
        used_graph: true,
        graph_metadata: None,
        execution_ms: duration_to_ms(start.elapsed()),
        next_page_token: None,
        total: Some(total),
        truncated: Some(false),
        candidates_scanned: None,
        workspace_path: crate::execution::symbol_utils::path_to_forward_slash(workspace_root),
    })
}

/// Execute the `get_hover_info` tool to get symbol information.
pub fn execute_get_hover_info(args: &GetHoverInfoArgs) -> Result<ToolExecution<HoverInfoData>> {
    let start = Instant::now();
    let workspace_path = resolve_workspace_path(&args.path);
    let engine = engine_for_workspace(workspace_path.as_ref())?;
    let workspace_root = engine.workspace_root().to_path_buf();

    tracing::debug!(symbol = %args.symbol, "Executing get_hover_info tool");

    let graph = engine.ensure_graph()?;
    let snapshot = graph.snapshot();
    let node_id = resolve_hover_node(&snapshot, &args.symbol)?;

    let files = snapshot.files();
    let strings = snapshot.strings();
    let entry = snapshot
        .get_node(node_id)
        .ok_or_else(|| anyhow!("Resolved symbol '{}' missing from graph", args.symbol))?;

    let name = strings
        .resolve(entry.name)
        .map(|s| s.to_string())
        .unwrap_or_default();
    let qualified_name =
        crate::execution::symbol_utils::display_entry_qualified_name(entry, strings, files, &name);
    let file_path = files
        .resolve(entry.file)
        .map(|p| {
            crate::execution::symbol_utils::relative_path_forward_slash(p.as_ref(), &workspace_root)
        })
        .unwrap_or_default();
    let language = files
        .language_for_file(entry.file)
        .map_or_else(|| "unknown".to_string(), |l| l.to_string());
    let signature = entry
        .signature
        .and_then(|id| strings.resolve(id))
        .map(|s| s.to_string());
    let documentation = entry
        .doc
        .and_then(|id| strings.resolve(id))
        .map(|s| s.to_string());

    let provenance = get_classpath_provenance_for_node(&snapshot, node_id);

    let data = HoverInfoData {
        name,
        qualified_name,
        kind: format!("{:?}", entry.kind),
        file_path,
        line: entry.start_line,
        language,
        signature,
        documentation,
        provenance,
    };

    Ok(ToolExecution {
        data,
        used_index: false,
        used_graph: true,
        graph_metadata: None,
        execution_ms: duration_to_ms(start.elapsed()),
        next_page_token: None,
        total: Some(1),
        truncated: Some(false),
        candidates_scanned: None,
        workspace_path: crate::execution::symbol_utils::path_to_forward_slash(workspace_root),
    })
}

/// Execute the `get_document_symbols` tool to list symbols in a file.
pub fn execute_get_document_symbols(
    args: &GetDocumentSymbolsArgs,
) -> Result<ToolExecution<GetDocumentSymbolsData>> {
    let start = Instant::now();
    let workspace_path = resolve_workspace_path(&args.path);
    let engine = engine_for_workspace(workspace_path.as_ref())?;
    let workspace_root = engine.workspace_root().to_path_buf();

    tracing::debug!(file_path = %args.file_path, "Executing get_document_symbols tool");

    let graph = engine.ensure_graph()?;

    let files = graph.files();
    let strings = graph.strings();

    // Find the file ID for the given path
    let target_path = std::path::Path::new(&args.file_path);
    let file_id = files.get(target_path).or_else(|| {
        // Try with workspace prefix
        let full_path = workspace_root.join(&args.file_path);
        files.get(&full_path)
    });

    let file_id =
        file_id.ok_or_else(|| anyhow::anyhow!("File '{}' not found in graph", args.file_path))?;

    // Collect symbols in this file
    let mut symbols: Vec<DocumentSymbolData> = Vec::new();

    let macro_meta_store = graph.macro_metadata();

    for (node_id, entry) in graph.nodes().iter() {
        if entry.file == file_id {
            let fallback_name = strings
                .resolve(entry.name)
                .map(|s| s.to_string())
                .unwrap_or_default();
            let name = crate::execution::symbol_utils::display_entry_qualified_name(
                entry,
                strings,
                files,
                &fallback_name,
            );

            let macro_metadata = macro_meta_store
                .get(node_id)
                .and_then(crate::execution::symbol_utils::macro_metadata_to_response);

            symbols.push(DocumentSymbolData {
                name,
                kind: format!("{:?}", entry.kind),
                line: entry.start_line,
                end_line: Some(entry.end_line),
                children: vec![], // Flat list for now, could build hierarchy later
                macro_metadata,
            });
        }
    }

    // Sort by line number
    symbols.sort_by_key(|s| s.line);

    let total = symbols.len() as u64;
    let data = GetDocumentSymbolsData {
        file_path: args.file_path.replace('\\', "/"),
        symbols,
        total,
    };

    tracing::debug!(total = total, "get_document_symbols completed");

    Ok(ToolExecution {
        data,
        used_index: false,
        used_graph: true,
        graph_metadata: None,
        execution_ms: duration_to_ms(start.elapsed()),
        next_page_token: None,
        total: Some(total),
        truncated: Some(false),
        candidates_scanned: None,
        workspace_path: crate::execution::symbol_utils::path_to_forward_slash(workspace_root),
    })
}

/// Execute the `get_workspace_symbols` tool to search for symbols.
pub fn execute_get_workspace_symbols(
    args: &GetWorkspaceSymbolsArgs,
) -> Result<ToolExecution<GetWorkspaceSymbolsData>> {
    let start = Instant::now();
    let workspace_path = resolve_workspace_path(&args.path);
    let engine = engine_for_workspace(workspace_path.as_ref())?;
    let workspace_root = engine.workspace_root().to_path_buf();

    tracing::debug!(query = %args.query, "Executing get_workspace_symbols tool");

    let graph = engine.ensure_graph()?;

    let files = graph.files();
    let strings = graph.strings();

    let query_lower = args.query.to_lowercase();

    // Search for matching symbols
    let mut symbols: Vec<WorkspaceSymbolData> = Vec::new();

    for (_node_id, entry) in graph.nodes().iter() {
        if symbols.len() >= args.max_results {
            break;
        }

        let fallback_name = strings
            .resolve(entry.name)
            .map(|s| s.to_string())
            .unwrap_or_default();
        let display_name = crate::execution::symbol_utils::display_entry_qualified_name(
            entry,
            strings,
            files,
            &fallback_name,
        );
        let qualified_name = display_name.clone();

        // Fuzzy match on name or qualified name
        let name_lower = display_name.to_lowercase();
        let qname_lower = qualified_name.to_lowercase();

        if name_lower.contains(&query_lower) || qname_lower.contains(&query_lower) {
            let file_path = files
                .resolve(entry.file)
                .map(|p| {
                    crate::execution::symbol_utils::relative_path_forward_slash(
                        p.as_ref(),
                        &workspace_root,
                    )
                })
                .unwrap_or_default();

            let language = files
                .language_for_file(entry.file)
                .map_or_else(|| "unknown".to_string(), |l| l.to_string());

            // Calculate a simple relevance score
            let score = if name_lower == query_lower {
                1.0
            } else if name_lower.starts_with(&query_lower) {
                0.9
            } else if name_lower.contains(&query_lower) {
                0.7
            } else {
                0.5
            };

            symbols.push(WorkspaceSymbolData {
                name: display_name,
                qualified_name,
                kind: format!("{:?}", entry.kind),
                file_path,
                line: entry.start_line,
                language,
                score,
            });
        }
    }

    // Sort by score (highest first)
    symbols.sort_by(|a, b| {
        b.score
            .partial_cmp(&a.score)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    let total = symbols.len() as u64;
    let data = GetWorkspaceSymbolsData {
        query: args.query.clone(),
        symbols,
        total,
    };

    tracing::debug!(total = total, "get_workspace_symbols completed");

    Ok(ToolExecution {
        data,
        used_index: false,
        used_graph: true,
        graph_metadata: None,
        execution_ms: duration_to_ms(start.elapsed()),
        next_page_token: None,
        total: Some(total),
        truncated: Some(false),
        candidates_scanned: None,
        workspace_path: crate::execution::symbol_utils::path_to_forward_slash(workspace_root),
    })
}