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
//! Natural language translation tool execution (P2-18).
//!
//! This module implements the `sqry_ask` MCP tool which translates
//! natural language queries into sqry commands using the sqry-nl crate.
//!
//! The MCP server performs translation only - command execution is
//! the responsibility of the MCP client.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Instant;

use anyhow::Result;
use sqry_nl::{DisambiguationOption, TranslationResponse, Translator, TranslatorConfig};

use crate::engine::{canonicalize_in_workspace, engine_for_workspace};
use crate::execution::utils::duration_to_ms;
use crate::execution::{NlDisambiguationOption, NlTranslationData, ToolExecution};
use crate::tools::SqryAskParams;

/// Check if a command has a `--path` flag as an actual CLI argument.
///
/// This checks for `--path` appearing outside of quoted strings to avoid
/// false positives when the query text itself contains "--path".
fn has_path_flag_outside_quotes(command: &str) -> bool {
    let chars: Vec<char> = command.chars().collect();
    let path_pattern: Vec<char> = "--path".chars().collect();
    let mut state = QuoteScanState::default();

    for i in 0..chars.len() {
        let c = chars[i];

        if state.advance(c) {
            continue;
        }

        // Check for --path at this position (only outside quotes)
        if !state.in_quotes()
            && matches_path_flag_at(&chars, i, &path_pattern)
            && has_path_flag_boundaries(&chars, i, path_pattern.len())
        {
            return true;
        }
    }
    false
}

#[derive(Default)]
struct QuoteScanState {
    in_double_quotes: bool,
    in_single_quotes: bool,
    prev_was_escape: bool,
}

impl QuoteScanState {
    fn advance(&mut self, c: char) -> bool {
        // Handle escape sequences
        if self.prev_was_escape {
            self.prev_was_escape = false;
            return true;
        }
        if c == '\\' {
            self.prev_was_escape = true;
            return true;
        }

        // Track quote state
        if c == '"' && !self.in_single_quotes {
            self.in_double_quotes = !self.in_double_quotes;
            return true;
        }
        if c == '\'' && !self.in_double_quotes {
            self.in_single_quotes = !self.in_single_quotes;
            return true;
        }

        false
    }

    fn in_quotes(&self) -> bool {
        self.in_double_quotes || self.in_single_quotes
    }
}

fn matches_path_flag_at(chars: &[char], offset: usize, pattern: &[char]) -> bool {
    if offset + pattern.len() > chars.len() {
        return false;
    }

    chars[offset..offset + pattern.len()]
        .iter()
        .zip(pattern.iter())
        .all(|(a, b)| a == b)
}

fn has_path_flag_boundaries(chars: &[char], offset: usize, pattern_len: usize) -> bool {
    // Check word boundary before (start of string or whitespace)
    let before_ok = offset == 0 || chars[offset - 1].is_whitespace();
    // Check word boundary after (end of string, whitespace, or '=')
    let after_pos = offset + pattern_len;
    let after_ok =
        after_pos == chars.len() || chars[after_pos].is_whitespace() || chars[after_pos] == '=';

    before_ok && after_ok
}

/// Augment a sqry command with path scope if it differs from workspace root.
///
/// When the user specifies a path that's a subdirectory of the workspace,
/// this appends `--path "<path>"` to the command so execution is scoped
/// to that directory.
fn augment_command_with_path(command: &str, scoped_path: &Path, workspace_root: &Path) -> String {
    // Only augment if path differs from workspace root
    if scoped_path == workspace_root {
        return command.to_string();
    }

    // Get relative path from workspace root for cleaner commands
    let relative_path = scoped_path
        .strip_prefix(workspace_root)
        .unwrap_or(scoped_path);

    // Don't add path flag if a real --path CLI flag is already present
    // (not just --path appearing inside a quoted query string)
    if has_path_flag_outside_quotes(command) {
        return command.to_string();
    }

    // Append --path flag with quoted path (handles spaces in path)
    format!(
        "{} --path \"{}\"",
        command,
        crate::execution::symbol_utils::path_to_forward_slash(relative_path)
    )
}

/// 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))
    }
}

/// Execute the `sqry_ask` natural language translation tool.
///
/// Translates a natural language query into a sqry command using the
/// sqry-nl translation pipeline. Returns structured response data
/// suitable for MCP clients.
///
/// The path parameter is canonicalized relative to the workspace root
/// to ensure translations are scoped correctly.
pub fn execute_sqry_ask(args: &SqryAskParams) -> Result<ToolExecution<NlTranslationData>> {
    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();

    // Canonicalize the path relative to workspace (validates it's within workspace)
    let scoped_path = canonicalize_in_workspace(&args.path, workspace_root)?;

    tracing::debug!(
        query = %args.query,
        path = %args.path,
        scoped_path = %scoped_path.display(),
        workspace = %workspace_root.display(),
        "Executing sqry_ask tool"
    );

    // Create translator with configuration scoped to the requested path
    let mut translator = build_translator(&scoped_path)?;

    // Translate the query
    let response = translator.translate(&args.query);

    // Convert to MCP response, augmenting commands with path scope if needed
    let mut data = build_translation_data(response, &scoped_path, workspace_root);

    // Optionally execute the translated command
    if args.execute
        && let Some(cmd_str) = &data.command
    {
        tracing::debug!(command = %cmd_str, "Executing translated sqry command");

        // Split command into binary and args
        let parts: Vec<&str> = cmd_str.split_whitespace().collect();
        if !parts.is_empty() {
            let bin = parts[0];
            let cmd_args = &parts[1..];

            let output = Command::new(bin)
                .args(cmd_args)
                .current_dir(workspace_root)
                .output();

            match output {
                Ok(out) => {
                    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
                    let stderr = String::from_utf8_lossy(&out.stderr).to_string();

                    if out.status.success() {
                        data.execution_output = Some(stdout);
                    } else {
                        data.execution_output = Some(format!("Error: {stderr}\n{stdout}"));
                    }
                }
                Err(e) => {
                    data.execution_output = Some(format!("Failed to execute command: {e}"));
                }
            }
        }
    }

    tracing::debug!(
        response_type = %data.response_type,
        "sqry_ask tool completed"
    );

    Ok(ToolExecution {
        data,
        used_index: false,
        used_graph: false,
        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),
    })
}

fn build_translator(scoped_path: &Path) -> Result<Translator> {
    let config = TranslatorConfig {
        working_directory: Some(crate::execution::symbol_utils::path_to_forward_slash(
            scoped_path,
        )),
        ..TranslatorConfig::default()
    };
    Ok(Translator::new(config)?)
}

fn build_translation_data(
    response: TranslationResponse,
    scoped_path: &Path,
    workspace_root: &Path,
) -> NlTranslationData {
    match response {
        TranslationResponse::Execute {
            command,
            confidence,
            intent,
            ..
        } => build_execute_data(
            &command,
            confidence,
            intent.as_str(),
            scoped_path,
            workspace_root,
        ),
        TranslationResponse::Confirm {
            command,
            confidence,
            prompt,
        } => build_confirm_data(&command, confidence, &prompt, scoped_path, workspace_root),
        TranslationResponse::Disambiguate { options, prompt } => {
            build_disambiguate_data(options, prompt, scoped_path, workspace_root)
        }
        TranslationResponse::Reject {
            reason,
            suggestions,
        } => build_reject_data(reason, suggestions),
    }
}

fn build_execute_data(
    command: &str,
    confidence: f32,
    intent: &str,
    scoped_path: &Path,
    workspace_root: &Path,
) -> NlTranslationData {
    let scoped_command = augment_command_with_path(command, scoped_path, workspace_root);
    NlTranslationData {
        response_type: "execute".to_string(),
        command: Some(scoped_command),
        confidence: Some(confidence),
        intent: Some(intent.to_string()),
        prompt: None,
        reason: None,
        suggestions: Vec::new(),
        options: Vec::new(),
        execution_output: None,
    }
}

fn build_confirm_data(
    command: &str,
    confidence: f32,
    prompt: &str,
    scoped_path: &Path,
    workspace_root: &Path,
) -> NlTranslationData {
    let scoped_command = augment_command_with_path(command, scoped_path, workspace_root);
    // Update the prompt to include the scoped command
    let scoped_prompt = prompt.replace(command, &scoped_command);
    NlTranslationData {
        response_type: "confirm".to_string(),
        command: Some(scoped_command),
        confidence: Some(confidence),
        intent: None,
        prompt: Some(scoped_prompt),
        reason: None,
        suggestions: Vec::new(),
        options: Vec::new(),
        execution_output: None,
    }
}

fn build_disambiguate_data(
    options: Vec<DisambiguationOption>,
    prompt: String,
    scoped_path: &Path,
    workspace_root: &Path,
) -> NlTranslationData {
    // Low confidence - needs user selection
    let nl_options = build_disambiguation_options(options, scoped_path, workspace_root);
    NlTranslationData {
        response_type: "disambiguate".to_string(),
        command: None,
        confidence: None,
        intent: None,
        prompt: Some(prompt),
        reason: None,
        suggestions: Vec::new(),
        options: nl_options,
        execution_output: None,
    }
}

fn build_disambiguation_options(
    options: Vec<DisambiguationOption>,
    scoped_path: &Path,
    workspace_root: &Path,
) -> Vec<NlDisambiguationOption> {
    options
        .into_iter()
        .map(|opt| {
            let scoped_command =
                augment_command_with_path(&opt.command, scoped_path, workspace_root);
            NlDisambiguationOption {
                command: scoped_command,
                intent: opt.intent.as_str().to_string(),
                description: opt.description,
                confidence: opt.confidence,
            }
        })
        .collect()
}

fn build_reject_data(reason: String, suggestions: Vec<String>) -> NlTranslationData {
    // Cannot translate
    NlTranslationData {
        response_type: "reject".to_string(),
        command: None,
        confidence: None,
        intent: None,
        prompt: None,
        reason: Some(reason),
        suggestions,
        options: Vec::new(),
        execution_output: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    // ===== augment_command_with_path unit tests =====

    #[test]
    fn test_augment_command_same_as_workspace() {
        let workspace = PathBuf::from("/workspace");
        let scoped = PathBuf::from("/workspace");
        let command = "sqry query \"kind:function\"";

        let result = augment_command_with_path(command, &scoped, &workspace);
        assert_eq!(
            result, command,
            "Should not modify command when path == workspace"
        );
    }

    #[test]
    fn test_augment_command_with_subdirectory() {
        let workspace = PathBuf::from("/workspace");
        let scoped = PathBuf::from("/workspace/src/lib");
        let command = "sqry query \"kind:function\"";

        let result = augment_command_with_path(command, &scoped, &workspace);
        assert_eq!(
            result, "sqry query \"kind:function\" --path \"src/lib\"",
            "Should append relative --path"
        );
    }

    #[test]
    fn test_augment_command_already_has_path() {
        let workspace = PathBuf::from("/workspace");
        let scoped = PathBuf::from("/workspace/src");
        let command = "sqry query \"kind:function\" --path \"other\"";

        let result = augment_command_with_path(command, &scoped, &workspace);
        assert_eq!(result, command, "Should not add --path if already present");
    }

    #[test]
    fn test_augment_command_with_spaces_in_path() {
        let workspace = PathBuf::from("/workspace");
        let scoped = PathBuf::from("/workspace/my project/src");
        let command = "sqry query \"kind:function\"";

        let result = augment_command_with_path(command, &scoped, &workspace);
        assert!(
            result.contains("--path \"my project/src\""),
            "Path with spaces should be quoted: {result}"
        );
    }

    #[test]
    fn test_augment_command_path_in_query_text() {
        // Regression test: --path inside quoted query should NOT prevent path augmentation
        let workspace = PathBuf::from("/workspace");
        let scoped = PathBuf::from("/workspace/src/lib");
        // User is searching for code containing "--path"
        let command = "sqry query \"find --path flag usage\"";

        let result = augment_command_with_path(command, &scoped, &workspace);
        assert!(
            result.contains("--path \"src/lib\""),
            "Should append --path when it only appears inside query: {result}"
        );
    }

    #[test]
    fn test_augment_command_path_in_single_quotes() {
        // --path inside single quotes should also NOT prevent augmentation
        let workspace = PathBuf::from("/workspace");
        let scoped = PathBuf::from("/workspace/src");
        let command = "sqry query 'find --path'";

        let result = augment_command_with_path(command, &scoped, &workspace);
        assert!(
            result.contains("--path \"src\""),
            "Should append --path when it only appears inside single quotes: {result}"
        );
    }

    // ===== has_path_flag_outside_quotes unit tests =====

    #[test]
    fn test_has_path_flag_no_path() {
        assert!(!has_path_flag_outside_quotes(
            "sqry query \"kind:function\""
        ));
    }

    #[test]
    fn test_has_path_flag_real_flag() {
        assert!(has_path_flag_outside_quotes(
            "sqry query \"kind:function\" --path \"src\""
        ));
    }

    #[test]
    fn test_has_path_flag_with_equals() {
        assert!(has_path_flag_outside_quotes(
            "sqry query \"kind:function\" --path=\"src\""
        ));
    }

    #[test]
    fn test_has_path_flag_inside_double_quotes() {
        // --path inside double quotes is NOT a real flag
        assert!(!has_path_flag_outside_quotes(
            "sqry query \"find --path usage\""
        ));
    }

    #[test]
    fn test_has_path_flag_inside_single_quotes() {
        // --path inside single quotes is NOT a real flag
        assert!(!has_path_flag_outside_quotes("sqry query 'find --path'"));
    }

    #[test]
    fn test_has_path_flag_escaped_quote() {
        // Escaped quote shouldn't change quote state
        assert!(!has_path_flag_outside_quotes(
            "sqry query \"find \\\"--path\\\" usage\""
        ));
    }

    #[test]
    fn test_has_path_flag_partial_match() {
        // --pathlike should NOT match
        assert!(!has_path_flag_outside_quotes(
            "sqry query \"kind:function\" --pathlike \"src\""
        ));
    }

    // ===== execute_sqry_ask integration tests =====

    #[test]
    #[serial_test::serial(engine_cache)]
    #[serial_test::serial(workspace_env)]
    fn test_execute_sqry_ask_basic() {
        // Initialize engine cache before use
        crate::engine::init_engine_cache(std::num::NonZeroUsize::new(4).unwrap());

        // Skip if no .sqry workspace available (e.g., CI without index)
        if engine_for_workspace(None).is_err() {
            return;
        }

        let args = SqryAskParams {
            query: "find public functions".to_string(),
            path: ".".to_string(),
            execute: false,
        };

        let result = execute_sqry_ask(&args);
        // Translation should not error (may return any response type)
        assert!(result.is_ok());

        let execution = result.unwrap();
        // Verify response type is one of the valid types
        let valid_types = ["execute", "confirm", "disambiguate", "reject"];
        assert!(
            valid_types.contains(&execution.data.response_type.as_str()),
            "Unexpected response type: {}",
            execution.data.response_type
        );
    }

    #[test]
    #[serial_test::serial(engine_cache)]
    #[serial_test::serial(workspace_env)]
    fn test_execute_sqry_ask_response_types() {
        // Initialize engine cache before use
        crate::engine::init_engine_cache(std::num::NonZeroUsize::new(4).unwrap());

        // Skip if no .sqry workspace available (e.g., CI without index)
        if engine_for_workspace(None).is_err() {
            return;
        }

        // Test various query patterns to exercise different response types
        let test_cases = vec![
            ("find all public functions", "execute"),
            ("show me methods", "execute"),
            // These may produce different response types depending on confidence
            ("xyz123", "reject"), // Likely rejected due to no clear intent
        ];

        for (query, _expected_type) in test_cases {
            let args = SqryAskParams {
                query: query.to_string(),
                path: ".".to_string(),
                execute: false,
            };

            let result = execute_sqry_ask(&args);
            // All queries should produce a valid response (even if rejected)
            assert!(
                result.is_ok(),
                "Query '{}' should not error: {:?}",
                query,
                result.err()
            );

            let execution = result.unwrap();
            let valid_types = ["execute", "confirm", "disambiguate", "reject"];
            assert!(
                valid_types.contains(&execution.data.response_type.as_str()),
                "Query '{}' produced invalid response type: {}",
                query,
                execution.data.response_type
            );
        }
    }

    #[test]
    #[serial_test::serial(engine_cache)]
    #[serial_test::serial(workspace_env)]
    fn test_execute_sqry_ask_path_validation() {
        // Initialize engine cache before use
        crate::engine::init_engine_cache(std::num::NonZeroUsize::new(4).unwrap());

        // Skip if no .sqry workspace available (e.g., CI without index)
        if engine_for_workspace(None).is_err() {
            return;
        }

        // Valid path should work
        let args = SqryAskParams {
            query: "find functions".to_string(),
            path: ".".to_string(),
            execute: false,
        };
        assert!(execute_sqry_ask(&args).is_ok());

        // Path outside workspace should fail (path traversal attempt)
        let args_bad = SqryAskParams {
            query: "find functions".to_string(),
            path: "/etc/passwd".to_string(),
            execute: false,
        };
        // This should fail due to path canonicalization
        assert!(execute_sqry_ask(&args_bad).is_err());
    }
}