rust-fs-mcp 0.2.3

Rust stdio MCP server compatible with fs-mcp public tool contracts.
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! search_tools.rs
//! tools::search_tools
//!
//! Content regex search tool: fs-search.
//! In-process engine built on ripgrep's own libraries (grep-searcher + ignore parallel
//! walk): removes the ~16ms per-search rg spawn and the PATH dependency while keeping
//! the rg-compatible contract (default excludes, filePattern globs, context lines,
//! maxResults early stop, timeout, literal fallback, "path / N:line" output shape).
//!

use crate::core::args_ref::read_text_slice;
use crate::core::batch::{SEARCH_PLAN, available_parallelism, create_batch_response, run_batch_parallel};
use crate::core::config::ensure_path_allowed;
use crate::core::response::RawResult;
use grep_matcher::{Match, Matcher, NoCaptures, NoError};
use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkContext, SinkMatch};
use ignore::WalkState;
use ignore::overrides::OverrideBuilder;
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

const SEARCH_BACKEND: &str = "native-grep";
// 기본 타임아웃은 Codex 계열 tools/call 30초 상한 안쪽이면서 대형 트리를 감당하는 25초.
const SEARCH_TIMEOUT_MS: u64 = 25_000;

#[derive(Clone, Debug)]
struct SearchSession {
    lines: Vec<String>,
    backend: String,
}

// 1. Search tool --------------------------------------------------------------
pub fn handle_fs_search(args: &Value) -> RawResult {
    let Some(items) = args.get("items").and_then(Value::as_array) else {
        return RawResult::error(
            "items must be an array; wrap a single operation as items:[{...}]",
        );
    };

    let results = run_batch_parallel(items, SEARCH_PLAN, regex_item);
    create_batch_response("fs-search", results, true)
}

fn regex_item(item: &Value) -> RawResult {
    let search = match run_regex_search(item) {
        Ok(search) => search,
        Err(error) => return RawResult::error(error),
    };
    // The match lines ship in the text body once; structured carries metadata only instead of
    // re-sending the same lines as a JSON array.
    let text = search.lines.join("\n");
    let backend = search.backend;
    let total = search.lines.len();
    let mut result = RawResult::structured(
        text,
        json!({
            "backend": &backend,
            "totalCount": total
        }),
    );
    result.meta.insert("backend".to_string(), json!(backend));
    result
}

// 2. In-process search runner ----------------------------------------------------
struct SearchSpec {
    root: PathBuf,
    include_hidden: bool,
    file_globs: Vec<String>,
    default_excludes: bool,
    context: usize,
    max_results: usize,
    timeout_ms: u64,
    multiline: bool,
}

fn run_regex_search(item: &Value) -> Result<SearchSession, String> {
    let Some(path) = item.get("path").and_then(Value::as_str) else {
        return Err("path must be a string".to_string());
    };
    let root = ensure_path_allowed(path)?;
    let pattern = read_pattern(item)?;
    let opts = PatternOpts {
        ignore_case: bool_field(item, "ignoreCase", true),
        literal: bool_field(item, "literal", false),
        multiline: bool_field(item, "multiline", false),
        word_match: bool_field(item, "wordMatch", false),
    };
    let include_hidden = bool_field(item, "includeHidden", false);
    let max_results = item
        .get("maxResults")
        .and_then(Value::as_u64)
        .map(|value| value as usize)
        .unwrap_or(usize::MAX);
    if max_results == 0 {
        return Ok(SearchSession {
            lines: Vec::new(),
            backend: SEARCH_BACKEND.to_string(),
        });
    }
    let spec = SearchSpec {
        include_hidden,
        file_globs: split_patterns(item.get("filePattern").and_then(Value::as_str)),
        // 기본 제외: 대형 산출물 디렉터리(node_modules/target, hidden 시 .git)가 시간 예산
        // 소진의 주범. 검색 루트가 그 내부이거나 noDefaultExcludes:true면 적용하지 않는다.
        default_excludes: !bool_field(item, "noDefaultExcludes", false) && !path_in_heavy_dir(&root),
        context: item
            .get("contextLines")
            .and_then(Value::as_u64)
            .map(|value| value as usize)
            .unwrap_or(2),
        max_results,
        timeout_ms: item
            .get("timeout_ms")
            .and_then(Value::as_u64)
            .unwrap_or(SEARCH_TIMEOUT_MS),
        multiline: opts.multiline,
        root,
    };
    let (matcher, backend) = if opts.literal {
        // 명시 literal은 rg -F 계약: 메타문자 이스케이프 없이 고정 문자열을 찾는다.
        let matcher = build_matcher(&pattern, &opts, true)
            .map_err(|error| format!("Invalid literal pattern: {error}"))?;
        (matcher, format!("{SEARCH_BACKEND} (literal)"))
    }
    else {
        match build_matcher(&pattern, &opts, false) {
            Ok(matcher) => (matcher, SEARCH_BACKEND.to_string()),
            Err(error) => {
                // 유효하지만 linear engine 미지원인 구문(lookaround/backref)은 리터럴 폴백이
                // 패턴 텍스트를 찾는 전혀 다른 검색이 되므로 재작성 힌트와 함께 거절한다.
                if let Some(hint) = reject_unsupported(&error) {
                    return Err(hint);
                }
                // 순수 문법 오류만 리터럴 검색으로 1회 폴백하고 라벨에 파스 오류 요지를 남긴다.
                let matcher = build_matcher(&pattern, &opts, true)
                    .map_err(|inner| format!("Invalid search pattern: {inner}"))?;
                (
                    matcher,
                    format!("{SEARCH_BACKEND} (literal fallback: {})", parse_error_gist(&error)),
                )
            }
        }
    };
    let outcome = run_native_search(&spec, &matcher)?;
    // maxResults 조기 종료는 정상 부분 성공(go의 cancel-and-return과 동일); 순수 타임아웃만 오류.
    if outcome.timed_out {
        return Err(format!(
            "{SEARCH_BACKEND} timed out after {}ms; narrow the search path, add filePattern, or raise timeout_ms",
            spec.timeout_ms
        ));
    }
    // 읽지 못한 파일(잠김 등)이 있어도 수집된 매치는 부분 결과로 살린다.
    let backend = if outcome.partial {
        format!("{backend} (partial: some files were unreadable)")
    }
    else {
        backend
    };
    Ok(SearchSession {
        lines: outcome.lines,
        backend,
    })
}

// 2a. regex(bytes) -> grep Matcher adapter -----------------------------------------
// rg와 동일하게 라인 지향 ^/$ 매칭을 위해 (?m)을 상시 켠다. 기본에서는 `.`이 개행을
// 매치하지 않아 매치가 한 줄 안에 갇히고, multiline 옵션이 (?s)로 줄 경계를 연다.
#[derive(Clone, Debug)]
pub(crate) struct RegexAdapter {
    pub(crate) regex: regex::bytes::Regex,
}
impl Matcher for RegexAdapter {
    type Captures = NoCaptures;
    type Error = NoError;
    fn find_at(&self, haystack: &[u8], at: usize) -> Result<Option<Match>, NoError> {
        Ok(self
            .regex
            .find_at(haystack, at)
            .map(|found| Match::new(found.start(), found.end())))
    }
    fn new_captures(&self) -> Result<NoCaptures, NoError> {
        Ok(NoCaptures::new())
    }
}
// 패턴 컴파일 옵션: literal=rg -F, word_match=rg -w, multiline=rg -U(+dot-all) 대응.
struct PatternOpts {
    ignore_case: bool,
    literal: bool,
    multiline: bool,
    word_match: bool,
}
fn build_matcher(pattern: &str, opts: &PatternOpts, force_literal: bool) -> Result<RegexAdapter, regex::Error> {
    let mut source = if opts.literal || force_literal {
        regex::escape(pattern)
    }
    else {
        pattern.to_string()
    };
    if opts.word_match {
        // rg -w 계약: 패턴 앞뒤에 \b. Rust regex의 \b는 Unicode-aware라 한글 경계도 성립.
        source = format!(r"\b(?:{source})\b");
    }
    let regex = regex::bytes::RegexBuilder::new(&source)
        .case_insensitive(opts.ignore_case)
        .multi_line(true)
        .dot_matches_new_line(opts.multiline)
        .build()?;
    Ok(RegexAdapter { regex })
}
// linear engine(Rust regex)이 문법으로는 인지하지만 지원하지 않는 구문 판별. 이때의
// 리터럴 폴백은 패턴 텍스트 자체를 찾는 오검색이므로 대안 힌트로 거절한다.
fn reject_unsupported(error: &regex::Error) -> Option<String> {
    if let regex::Error::CompiledTooBig(limit) = error {
        return Some(format!(
            "pattern compiles past the {limit}-byte engine limit; shrink bounded repetitions or split the search"
        ));
    }
    let text = error.to_string();
    if text.contains("look-around") {
        return Some(
            "pattern uses look-around, which this linear engine (Rust regex syntax) does not support; \
             match the surrounding text with plain groups and filter afterwards, or set literal:true for exact text"
                .to_string(),
        );
    }
    if text.contains("backreference") {
        return Some(
            "pattern uses backreferences, which this linear engine (Rust regex syntax) does not support; \
             repeat the subpattern explicitly or run a second confirming search"
                .to_string(),
        );
    }
    None
}
// regex 파스 오류는 캐럿 포함 다중 줄이라 마지막 "error: ..." 요지만 라벨에 싣는다.
fn parse_error_gist(error: &regex::Error) -> String {
    let text = error.to_string();
    text.lines()
        .rev()
        .find_map(|line| line.strip_prefix("error: "))
        .unwrap_or("regex parse error")
        .to_string()
}

// 2b. Parallel walk + per-file sink ---------------------------------------------
struct NativeOutcome {
    lines: Vec<String>,
    timed_out: bool,
    partial: bool,
}
struct Collected {
    lines: Vec<String>,
    hits: usize,
}
fn run_native_search(spec: &SearchSpec, matcher: &RegexAdapter) -> Result<NativeOutcome, String> {
    let deadline = Instant::now() + Duration::from_millis(spec.timeout_ms);
    let collected = Mutex::new(Collected {
        lines: Vec::new(),
        hits: 0,
    });
    let timed_out = AtomicBool::new(false);
    let partial = AtomicBool::new(false);
    let done = AtomicBool::new(false);

    // filePattern / 기본 제외는 rg --glob과 동일한 overrides 시맨틱으로 적용한다.
    let mut overrides = OverrideBuilder::new(&spec.root);
    for glob in &spec.file_globs {
        overrides
            .add(glob)
            .map_err(|error| format!("Invalid filePattern glob '{glob}': {error}"))?;
    }
    if spec.default_excludes {
        for glob in ["!**/node_modules/**", "!**/target/**"] {
            overrides.add(glob).map_err(|error| error.to_string())?;
        }
        if spec.include_hidden {
            overrides.add("!**/.git/**").map_err(|error| error.to_string())?;
        }
    }
    let overrides = overrides.build().map_err(|error| error.to_string())?;

    // rg CLI와 동일 기본: hidden 스킵(includeHidden으로 해제), --no-ignore, 심링크 미추적.
    let mut builder = ignore::WalkBuilder::new(&spec.root);
    builder
        .hidden(!spec.include_hidden)
        .ignore(false)
        .git_ignore(false)
        .git_global(false)
        .git_exclude(false)
        .parents(false)
        .follow_links(false)
        .overrides(overrides)
        .threads(available_parallelism().clamp(2, 12));
    builder.build_parallel().run(|| {
        let mut searcher = SearcherBuilder::new()
            .line_number(true)
            .before_context(spec.context)
            .after_context(spec.context)
            .multi_line(spec.multiline)
            .binary_detection(BinaryDetection::quit(0))
            .build();
        let matcher = matcher.clone();
        let collected = &collected;
        let timed_out = &timed_out;
        let partial = &partial;
        let done = &done;
        Box::new(move |entry| {
            if done.load(Ordering::Relaxed) || timed_out.load(Ordering::Relaxed) {
                return WalkState::Quit;
            }
            if Instant::now() >= deadline {
                timed_out.store(true, Ordering::Relaxed);
                return WalkState::Quit;
            }
            let Ok(entry) = entry else {
                // 순회 오류(권한 등)는 해당 항목만 건너뛴다.
                partial.store(true, Ordering::Relaxed);
                return WalkState::Continue;
            };
            if !entry.file_type().map(|kind| kind.is_file()).unwrap_or(false) {
                return WalkState::Continue;
            }
            // 남은 전역 예산 스냅샷: 파일 안에서는 이 한도까지만 수집하고 병합 시 재절단한다.
            let budget = {
                let collected = collected.lock().unwrap();
                if collected.hits >= spec.max_results {
                    done.store(true, Ordering::Relaxed);
                    return WalkState::Quit;
                }
                spec.max_results - collected.hits
            };
            let mut sink = FileSink {
                lines: Vec::new(),
                hits: 0,
                budget,
                deadline,
                timed_out,
                tick: 0,
            };
            if searcher.search_path(&matcher, entry.path(), &mut sink).is_err() {
                // 읽기 실패(잠긴 파일 등)는 부분 결과로 계속한다(rg 종료코드 2 대응).
                partial.store(true, Ordering::Relaxed);
                return WalkState::Continue;
            }
            if timed_out.load(Ordering::Relaxed) {
                return WalkState::Quit;
            }
            if sink.lines.is_empty() {
                return WalkState::Continue;
            }
            let mut collected = collected.lock().unwrap();
            let remaining = spec.max_results.saturating_sub(collected.hits);
            if remaining == 0 {
                done.store(true, Ordering::Relaxed);
                return WalkState::Quit;
            }
            // Emit the file path once per file run (rg --heading style).
            collected.lines.push(entry.path().display().to_string());
            let take = sink.lines.len().min(remaining);
            collected.lines.extend(sink.lines.drain(..take));
            collected.hits += take;
            if collected.hits >= spec.max_results {
                done.store(true, Ordering::Relaxed);
                return WalkState::Quit;
            }
            WalkState::Continue
        })
    });

    let collected = collected
        .into_inner()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    let hit_cap = done.into_inner();
    Ok(NativeOutcome {
        lines: collected.lines,
        timed_out: timed_out.into_inner() && !hit_cap,
        partial: partial.into_inner(),
    })
}
// 파일 1개 분량의 매치/컨텍스트를 "N:text" / "N-text"로 수집하는 sink.
struct FileSink<'a> {
    lines: Vec<String>,
    hits: usize,
    budget: usize,
    deadline: Instant,
    timed_out: &'a AtomicBool,
    tick: u32,
}
impl FileSink<'_> {
    fn push_line(&mut self, number: Option<u64>, sep: char, bytes: &[u8]) -> Result<bool, std::io::Error> {
        // 시계 호출은 64회에 1회만: 핫루프에서 Instant::now()가 줄당 비용을 지배하지 않게.
        self.tick = self.tick.wrapping_add(1);
        if self.tick & 63 == 0 && Instant::now() >= self.deadline {
            self.timed_out.store(true, Ordering::Relaxed);
            return Ok(false);
        }
        let text = String::from_utf8_lossy(bytes);
        let text = text.trim_end_matches(['\r', '\n']);
        // multiline 매치는 한 SinkMatch에 여러 줄이 실려 온다: 줄별로 실제 줄번호를 잇는다.
        for (number, line) in (number.unwrap_or(0)..).zip(text.split('\n')) {
            let line = line.trim_end_matches('\r');
            self.lines.push(format!("{number}{sep}{line}"));
            self.hits += 1;
            if self.hits >= self.budget {
                return Ok(false);
            }
        }
        Ok(true)
    }
}
impl Sink for FileSink<'_> {
    type Error = std::io::Error;
    fn matched(&mut self, _searcher: &Searcher, mat: &SinkMatch<'_>) -> Result<bool, std::io::Error> {
        self.push_line(mat.line_number(), ':', mat.bytes())
    }
    fn context(&mut self, _searcher: &Searcher, ctx: &SinkContext<'_>) -> Result<bool, std::io::Error> {
        self.push_line(ctx.line_number(), '-', ctx.bytes())
    }
}

// 3. Shared helpers -------------------------------------------------------------
// 검색 루트가 기본 제외 대상 디렉터리 내부인지 판별(명시 탐색 의도는 존중). fs-inspect도 공유.
pub(crate) fn path_in_heavy_dir(path: &std::path::Path) -> bool {
    path.components().any(|component| {
        let text = component.as_os_str().to_string_lossy().to_ascii_lowercase();
        text == "node_modules" || text == "target" || text == ".git"
    })
}

fn split_patterns(pattern: Option<&str>) -> Vec<String> {
    pattern
        .into_iter()
        .flat_map(|value| value.split('|'))
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
        .collect()
}

fn read_pattern(item: &Value) -> Result<String, String> {
    if let Some(path) = item.get("pattern_path").and_then(Value::as_str) {
        let path = ensure_path_allowed(path)?;
        let offset = item
            .get("pattern_offset")
            .and_then(Value::as_u64)
            .unwrap_or(0) as usize;
        let length = item
            .get("pattern_length")
            .and_then(Value::as_u64)
            .map(|value| value as usize);
        return read_text_slice(path, offset, length);
    }

    // 다른 도구 인자를 들고 온 혼동 호출은 교정 힌트로 안내.
    if item.get("start_line").is_some() || item.get("line_count").is_some() {
        return Err(
            "pattern is required; fs-search matches regex content — for start_line/line_count reads use file-read-line-range"
                .to_string(),
        );
    }
    item.get("pattern")
        .and_then(Value::as_str)
        .map(str::to_string)
        .ok_or_else(|| "pattern or pattern_path is required".to_string())
}

fn bool_field(value: &Value, key: &str, default: bool) -> bool {
    value.get(key).and_then(Value::as_bool).unwrap_or(default)
}

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

    fn temp_dir(prefix: &str) -> std::path::PathBuf {
        // target/ 아래를 피해야 default_excludes(=heavy dir 판정) 경로가 유지된다.
        let dir = std::env::temp_dir().join(format!(
            "{prefix}-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }
    fn first_backend(result: &RawResult) -> String {
        result.structured.clone().unwrap()["results"][0]["data"]["backend"]
            .as_str()
            .unwrap_or_default()
            .to_string()
    }

    #[test]
    fn missing_pattern_is_error() {
        let result = handle_fs_search(&json!({ "items": [{ "path": "." }] }));
        assert!(result.is_error);
    }

    #[test]
    fn line_range_args_get_targeted_hint() {
        let result = handle_fs_search(
            &json!({ "items": [{ "path": ".", "start_line": 3, "line_count": 2 }] }),
        );
        assert!(result.is_error);
        let text = result.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("file-read-line-range"), "{text}");
    }

    #[test]
    fn invalid_regex_falls_back_to_literal() {
        // "sendCancel(" 는 regex 파스 오류 → 리터럴 폴백 매치.
        let dir = temp_dir("rust-fs-mcp-litfb");
        std::fs::write(dir.join("sample.txt"), "call sendCancel( now\n").unwrap();

        let result = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": "sendCancel(" }]
        }));
        assert!(!result.is_error, "{result:?}");
        let text = result.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("sendCancel("), "{text}");
        // 라벨에 파스 오류 요지가 실려 패턴 교정이 가능해야 한다.
        let backend = first_backend(&result);
        assert!(backend.contains("literal fallback"), "{result:?}");
        assert!(backend.contains("unclosed group"), "{backend}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn groups_lines_under_file_headings_with_context() {
        let dir = temp_dir("rust-fs-mcp-heading");
        std::fs::write(dir.join("a.txt"), "ctx before\nneedle hit\nctx after\n").unwrap();

        let result = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": "needle", "contextLines": 1 }]
        }));
        assert!(!result.is_error, "{result:?}");
        let text = result.content[0]["text"].as_str().unwrap_or_default();
        // rg --heading 형태: 파일 경로 1줄 + "1-ctx", "2:hit", "3-ctx".
        assert!(text.contains("a.txt"), "{text}");
        assert!(text.contains("1-ctx before"), "{text}");
        assert!(text.contains("2:needle hit"), "{text}");
        assert!(text.contains("3-ctx after"), "{text}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn default_excludes_skip_heavy_dirs() {
        let dir = temp_dir("rust-fs-mcp-heavy");
        std::fs::create_dir_all(dir.join("node_modules").join("pkg")).unwrap();
        std::fs::create_dir_all(dir.join("target")).unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("node_modules").join("pkg").join("dep.js"), "needle\n").unwrap();
        std::fs::write(dir.join("target").join("out.txt"), "needle\n").unwrap();
        std::fs::write(dir.join("src").join("app.js"), "needle\n").unwrap();

        let result = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": "needle" }]
        }));
        assert!(!result.is_error, "{result:?}");
        let text = result.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("app.js"), "{text}");
        assert!(!text.contains("dep.js"), "{text}");
        assert!(!text.contains("out.txt"), "{text}");

        // noDefaultExcludes:true 면 산출물 디렉터리도 검색된다.
        let all = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": "needle", "noDefaultExcludes": true }]
        }));
        let text = all.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("dep.js"), "{text}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn max_results_caps_match_and_context_lines() {
        let dir = temp_dir("rust-fs-mcp-maxres");
        let body: String = (1..=50).map(|index| format!("needle line {index}\n")).collect();
        std::fs::write(dir.join("many.txt"), body).unwrap();

        let result = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": "needle", "maxResults": 5, "contextLines": 0 }]
        }));
        assert!(!result.is_error, "{result:?}");
        let structured = result.structured.clone().unwrap();
        // totalCount = 헤딩 1 + 콘텐츠 줄 5.
        assert_eq!(structured["results"][0]["data"]["totalCount"], 6, "{structured}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn single_file_root_searches_that_file() {
        let dir = temp_dir("rust-fs-mcp-singlefile");
        let file = dir.join("only.rs");
        std::fs::write(&file, "fn needle_here() {}\n").unwrap();

        let result = handle_fs_search(&json!({
            "items": [{ "path": file.display().to_string(), "pattern": "needle_here" }]
        }));
        assert!(!result.is_error, "{result:?}");
        let text = result.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("1:fn needle_here() {}"), "{text}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn file_pattern_narrows_targets() {
        let dir = temp_dir("rust-fs-mcp-filepat");
        std::fs::write(dir.join("a.rs"), "needle\n").unwrap();
        std::fs::write(dir.join("b.js"), "needle\n").unwrap();

        let result = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": "needle", "filePattern": "*.rs" }]
        }));
        assert!(!result.is_error, "{result:?}");
        let text = result.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("a.rs"), "{text}");
        assert!(!text.contains("b.js"), "{text}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn unsupported_constructs_are_rejected_with_hints() {
        let dir = temp_dir("rust-fs-mcp-unsupported");
        std::fs::write(dir.join("a.txt"), "foo bar\n").unwrap();

        // lookaround는 리터럴 폴백(조용한 0건) 대신 재작성 힌트로 거절된다.
        let look = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": "(?<=foo )bar" }]
        }));
        assert!(look.is_error, "{look:?}");
        let text = look.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("look-around"), "{text}");
        assert!(text.contains("literal:true"), "{text}");

        let backref = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": r"(\w+) \1" }]
        }));
        assert!(backref.is_error, "{backref:?}");
        let text = backref.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("backreference"), "{text}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn explicit_literal_matches_fixed_string_only() {
        let dir = temp_dir("rust-fs-mcp-literal");
        // "foo.bar"는 유효한 regex이기도 해서 자동 폴백이 없다: literal:true만이 정확한 계약.
        std::fs::write(dir.join("a.txt"), "foo.bar\nfooXbar\n").unwrap();

        let result = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": "foo.bar", "literal": true, "contextLines": 0 }]
        }));
        assert!(!result.is_error, "{result:?}");
        let text = result.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("1:foo.bar"), "{text}");
        assert!(!text.contains("fooXbar"), "{text}");
        assert!(first_backend(&result).contains("(literal)"), "{result:?}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn word_match_bounds_ascii_and_hangul_words() {
        let dir = temp_dir("rust-fs-mcp-word");
        std::fs::write(dir.join("a.txt"), "cat\nconcatenate\n가나 이후\n가나다 이후\n").unwrap();

        let ascii = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": "cat", "wordMatch": true, "contextLines": 0 }]
        }));
        assert!(!ascii.is_error, "{ascii:?}");
        let text = ascii.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("1:cat"), "{text}");
        assert!(!text.contains("concatenate"), "{text}");

        // Rust regex의 \b는 Unicode-aware: 완성형 음절 경계도 단어 경계로 성립한다.
        let hangul = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": "가나", "wordMatch": true, "contextLines": 0 }]
        }));
        assert!(!hangul.is_error, "{hangul:?}");
        let text = hangul.content[0]["text"].as_str().unwrap_or_default();
        assert!(text.contains("3:가나 이후"), "{text}");
        assert!(!text.contains("가나다"), "{text}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn multiline_lets_patterns_span_lines() {
        let dir = temp_dir("rust-fs-mcp-multiline");
        std::fs::write(dir.join("a.rs"), "alpha\nfn demo(\n  arg: u32,\n) -> bool {\nomega\n").unwrap();

        // 기본(라인 지향)에서는 `.`이 개행을 매치하지 않아 줄 경계를 넘는 매치가 없다.
        let single = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": r"fn demo\(.*?\) -> bool", "contextLines": 0 }]
        }));
        assert!(!single.is_error, "{single:?}");
        let text = single.content[0]["text"].as_str().unwrap_or_default();
        assert!(!text.contains("fn demo"), "{text}");

        let multi = handle_fs_search(&json!({
            "items": [{ "path": dir.display().to_string(), "pattern": r"fn demo\(.*?\) -> bool", "multiline": true, "contextLines": 0 }]
        }));
        assert!(!multi.is_error, "{multi:?}");
        let text = multi.content[0]["text"].as_str().unwrap_or_default();
        // 매치가 걸친 줄들이 실제 줄번호로 분해되어 나온다.
        assert!(text.contains("2:fn demo("), "{text}");
        assert!(text.contains("3:  arg: u32,"), "{text}");
        assert!(text.contains("4:) -> bool {"), "{text}");

        std::fs::remove_dir_all(&dir).unwrap();
    }
}