greplm-mcp 0.1.0

greplm Model Context Protocol (MCP) stdio server.
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! greplm MCP server (stdio transport).
//!
//! Exposes the greplm trigram code index to LLM agents over the Model Context
//! Protocol. All logging goes to stderr; stdout is reserved for the protocol.

use std::collections::BTreeSet;
use std::path::PathBuf;

use rmcp::handler::server::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
    CallToolResult, Content, Implementation, ProtocolVersion, ServerCapabilities, ServerInfo,
};
use rmcp::{tool, tool_handler, tool_router, ErrorData, ServerHandler, ServiceExt};
use schemars::JsonSchema;
use serde::Deserialize;

use greplm_core::search::{SearchQuery, SymbolQuery};
use greplm_core::Greplm;

#[derive(Debug, Deserialize, JsonSchema, Default)]
struct IndexArgs {
    /// Project root to index. Defaults to the server's working directory.
    #[serde(default)]
    root: Option<String>,
    /// Rebuild the whole index from scratch.
    #[serde(default)]
    force: bool,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct SearchArgs {
    /// The query string (literal by default).
    query: String,
    /// Treat the query as a regular expression.
    #[serde(default)]
    regex: bool,
    /// Case-insensitive matching.
    #[serde(default)]
    ignore_case: bool,
    /// Match whole identifiers only (word boundaries).
    #[serde(default)]
    whole_word: bool,
    /// Restrict results to a language id (e.g. "rust", "python", "swift").
    #[serde(default)]
    lang: Option<String>,
    /// Restrict results to paths containing this substring.
    #[serde(default)]
    path: Option<String>,
    /// Maximum number of results (default 50).
    #[serde(default)]
    limit: Option<usize>,
    /// Skip the first N results (pagination).
    #[serde(default)]
    offset: Option<usize>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct RefsArgs {
    /// Identifier to find references for.
    name: String,
    /// Maximum number of results (default 100).
    #[serde(default)]
    limit: Option<usize>,
    /// Skip the first N results (pagination).
    #[serde(default)]
    offset: Option<usize>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct CallArgs {
    /// Symbol name (function/method) to analyze.
    name: String,
    /// Maximum number of results (default 100).
    #[serde(default)]
    limit: Option<usize>,
    /// Skip the first N results (pagination).
    #[serde(default)]
    offset: Option<usize>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct ImpactArgs {
    /// Symbol name to analyze.
    name: String,
    /// Maximum number of caller hops to follow (default 3).
    #[serde(default)]
    depth: Option<u32>,
    /// Maximum number of affected symbols to report (default 200).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct BlameArgs {
    /// File path relative to the project root.
    file: String,
    /// Line number (1-based).
    line: u32,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct HistoryArgs {
    /// Symbol name to show history for.
    name: String,
    /// Maximum number of commits (default 20).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct ChangedArgs {
    /// Git revision to diff against (e.g. main, HEAD~5, a tag).
    rev: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct PackArgs {
    /// The task or question to assemble relevant code context for.
    task: String,
    /// Token budget for the assembled context (default 8000).
    #[serde(default)]
    budget: Option<u64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct AstArgs {
    /// A tree-sitter query S-expression (with @captures and #eq?/#match?
    /// predicates), or a friendly `$NAME` meta-variable pattern like
    /// `fn $NAME() {}`.
    pattern: String,
    /// Language id to search (required; node kinds are language-specific).
    lang: String,
    /// Maximum number of results (default 50).
    #[serde(default)]
    limit: Option<usize>,
    /// Skip the first N results (pagination).
    #[serde(default)]
    offset: Option<usize>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct DefArgs {
    /// File path relative to the project root.
    file: String,
    /// Line of the identifier (1-based).
    line: u32,
    /// Column of the identifier (1-based).
    col: u32,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct SnippetArgs {
    /// File path relative to the project root.
    file: String,
    /// Start line (1-based).
    start: u32,
    /// End line (1-based). Defaults to start.
    #[serde(default)]
    end: Option<u32>,
    /// Context lines around the range (default 3).
    #[serde(default)]
    context: Option<u32>,
}

#[derive(Debug, Deserialize, JsonSchema, Default)]
struct SummaryArgs {}

#[derive(Debug, Deserialize, JsonSchema)]
struct SymbolArgs {
    /// Symbol name or fuzzy fragment.
    name: String,
    /// Restrict to a symbol kind (function, class, struct, ...).
    #[serde(default)]
    kind: Option<String>,
    /// Require an exact name match.
    #[serde(default)]
    exact: bool,
    /// Maximum number of results (default 50).
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct OutlineArgs {
    /// File path relative to the project root.
    file: String,
}

#[derive(Debug, Deserialize, JsonSchema, Default)]
struct StatusArgs {}

#[derive(Clone)]
struct GreplmServer {
    root: PathBuf,
    #[allow(dead_code)]
    tool_router: ToolRouter<GreplmServer>,
}

fn internal(e: impl std::fmt::Display) -> ErrorData {
    ErrorData::internal_error(e.to_string(), None)
}

/// Record token savings for a query that returns location-style hits: the
/// unique result files (grep+read baseline) vs. the compact payload returned.
fn record_savings<T: serde::Serialize>(
    g: &Greplm,
    kind: &str,
    hits: &[T],
    path_of: impl Fn(&T) -> String,
) {
    let files: BTreeSet<String> = hits.iter().map(&path_of).collect();
    let returned = serde_json::to_string(hits).map(|s| s.len()).unwrap_or(0) as u64;
    g.record_savings(kind, &files, returned, hits.len() as u64);
}

fn ok_json<T: serde::Serialize>(value: &T) -> Result<CallToolResult, ErrorData> {
    let text = serde_json::to_string_pretty(value).map_err(internal)?;
    Ok(CallToolResult::success(vec![Content::text(text)]))
}

#[tool_router]
impl GreplmServer {
    fn new(root: PathBuf) -> Self {
        Self {
            root,
            tool_router: Self::tool_router(),
        }
    }

    /// Resolve the project root for an index request. A caller-supplied `root`
    /// is only honored when it stays within the server's configured root, so an
    /// agent can't drive greplm to index arbitrary directories on the host.
    fn resolve(&self, root: &Option<String>) -> Result<PathBuf, ErrorData> {
        let requested = match root {
            None => return Ok(self.root.clone()),
            Some(r) => PathBuf::from(r),
        };
        let base = self
            .root
            .canonicalize()
            .unwrap_or_else(|_| self.root.clone());
        let target = requested
            .canonicalize()
            .unwrap_or_else(|_| requested.clone());
        if target.starts_with(&base) {
            Ok(requested)
        } else {
            Err(ErrorData::invalid_params(
                format!(
                    "root {} is outside the server root {}",
                    requested.display(),
                    self.root.display()
                ),
                None,
            ))
        }
    }

    #[tool(
        description = "Build or refresh the greplm index for a project. Run this once before \
                          searching, or after large changes. Incremental by default."
    )]
    async fn index_project(
        &self,
        Parameters(args): Parameters<IndexArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.resolve(&args.root)?;
        let force = args.force;
        let stats = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::open(&root)?;
            g.index(force)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&serde_json::json!({
            "files_indexed": stats.files_indexed,
            "files_skipped": stats.files_skipped,
            "files_removed": stats.files_removed,
            "symbols": stats.symbols,
            "segments": stats.segments,
        }))
    }

    #[tool(
        description = "Search file contents using the trigram index. Fast exact, substring, \
                          and regex search across the codebase. Returns ranked matches with \
                          path, line, column, and the matching line text."
    )]
    async fn search_code(
        &self,
        Parameters(args): Parameters<SearchArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let query = SearchQuery {
            pattern: args.query,
            regex: args.regex,
            case_insensitive: args.ignore_case,
            whole_word: args.whole_word,
            lang: args.lang,
            path: args.path,
            limit: args.limit.unwrap_or(50),
            offset: args.offset.unwrap_or(0),
            max_per_file: 20,
        };
        let hits = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let hits = g.searcher()?.search(&query)?;
            record_savings(&g, "search", &hits, |h| h.path.clone());
            Ok(hits)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&hits)
    }

    #[tool(
        description = "Find symbol definitions (functions, classes, structs, etc.) by name. \
                          Supports exact, prefix, substring, and fuzzy matching."
    )]
    async fn find_symbol(
        &self,
        Parameters(args): Parameters<SymbolArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let query = SymbolQuery {
            name: args.name,
            kind: args.kind,
            exact: args.exact,
            limit: args.limit.unwrap_or(50),
            offset: 0,
        };
        let hits = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let hits = g.searcher()?.symbols(&query)?;
            record_savings(&g, "symbols", &hits, |h| h.path.clone());
            Ok(hits)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&hits)
    }

    #[tool(
        description = "Get the symbol outline (definitions in order) of a single file, given \
                          its path relative to the project root."
    )]
    async fn get_file_outline(
        &self,
        Parameters(args): Parameters<OutlineArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let file = args.file;
        let hits = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            g.searcher()?.outline(&file)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&hits)
    }

    #[tool(
        description = "Find references to an identifier: whole-word occurrences across the \
                          codebase (definitions rank first). Good for 'who uses X'."
    )]
    async fn find_references(
        &self,
        Parameters(args): Parameters<RefsArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let name = args.name;
        let limit = args.limit.unwrap_or(100);
        let offset = args.offset.unwrap_or(0);
        let hits = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let hits = g.searcher()?.references(&name, limit, offset)?;
            record_savings(&g, "refs", &hits, |h| h.path.clone());
            Ok(hits)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&hits)
    }

    #[tool(
        description = "Resolved references for a symbol from the structural index: its \
                          definitions, call sites, and imports (not text matching). Each result \
                          carries the enclosing symbol. Prefer this over find_references for code \
                          intelligence."
    )]
    async fn resolved_references(
        &self,
        Parameters(args): Parameters<CallArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let name = args.name;
        let limit = args.limit.unwrap_or(100);
        let offset = args.offset.unwrap_or(0);
        let hits = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let hits = g.searcher()?.references_resolved(&name, limit, offset);
            record_savings(&g, "xref", &hits, |h| h.path.clone());
            Ok(hits)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&hits)
    }

    #[tool(
        description = "Find who calls a function/method: every call site that targets the \
                          named symbol, attributed to its enclosing caller symbol. Use to trace \
                          where behavior originates."
    )]
    async fn find_callers(
        &self,
        Parameters(args): Parameters<CallArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let name = args.name;
        let limit = args.limit.unwrap_or(100);
        let offset = args.offset.unwrap_or(0);
        let hits = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let hits = g.searcher()?.callers(&name, limit, offset);
            record_savings(&g, "callers", &hits, |h| h.path.clone());
            Ok(hits)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&hits)
    }

    #[tool(
        description = "Find what a function/method calls: every call site inside the named \
                          symbol's body. Use to understand a function's outgoing dependencies."
    )]
    async fn find_callees(
        &self,
        Parameters(args): Parameters<CallArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let name = args.name;
        let limit = args.limit.unwrap_or(100);
        let offset = args.offset.unwrap_or(0);
        let hits = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let hits = g.searcher()?.callees(&name, limit, offset);
            record_savings(&g, "callees", &hits, |h| h.path.clone());
            Ok(hits)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&hits)
    }

    #[tool(
        description = "Blast radius: the symbols transitively affected if the named symbol \
                          changes, found by walking the reverse call graph up to `depth` hops. \
                          Use before editing to gauge impact. Resolution is by name, so treat \
                          results as a guide."
    )]
    async fn impact_of(
        &self,
        Parameters(args): Parameters<ImpactArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let name = args.name;
        let depth = args.depth.unwrap_or(3);
        let limit = args.limit.unwrap_or(200);
        let nodes = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let nodes = g.searcher()?.blast_radius(&name, depth, limit);
            record_savings(&g, "impact", &nodes, |n| n.path.clone());
            Ok(nodes)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&nodes)
    }

    #[tool(
        description = "Git blame for a single line: the commit, author, and summary that last \
                          changed it. Use to learn why a line exists."
    )]
    async fn git_blame(
        &self,
        Parameters(args): Parameters<BlameArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let (file, line) = (args.file, args.line);
        let b = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            g.searcher()?.blame(&file, line)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&b)
    }

    #[tool(
        description = "Show the commit history of a symbol: resolve it to its definition and \
                          list the commits that touched its line range, newest first."
    )]
    async fn symbol_history(
        &self,
        Parameters(args): Parameters<HistoryArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let name = args.name;
        let limit = args.limit.unwrap_or(20);
        let h = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            g.searcher()?.symbol_history(&name, limit)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&h)
    }

    #[tool(
        description = "List files changed since a git revision (e.g. main, HEAD~5), each \
                          annotated with the symbols it defines. Use to scope a review or \
                          understand what a branch touched."
    )]
    async fn changed_since(
        &self,
        Parameters(args): Parameters<ChangedArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let rev = args.rev;
        let changed = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            g.searcher()?.changed_since(&rev)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&changed)
    }

    #[tool(
        description = "Build a token-budgeted context pack for a task: the most relevant \
                          symbols (with signatures and code snippets) plus their dependency \
                          neighborhood, ranked by lexical relevance and call-graph centrality. \
                          Call this FIRST when starting a task to load exactly the code you need \
                          instead of grepping and reading whole files."
    )]
    async fn build_context(
        &self,
        Parameters(args): Parameters<PackArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let task = args.task;
        let budget = args.budget.unwrap_or(8000);
        let pack = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let pack = g.searcher()?.context_pack(&task, budget);
            let files: std::collections::BTreeSet<String> =
                pack.items.iter().map(|i| i.path.clone()).collect();
            let returned = serde_json::to_string(&pack).map(|s| s.len()).unwrap_or(0) as u64;
            g.record_savings("pack", &files, returned, pack.items.len() as u64);
            Ok(pack)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&pack)
    }

    #[tool(
        description = "Structural (AST) search: match a tree-sitter query S-expression \
                          (with @captures and #eq?/#match? predicates) or a friendly `$NAME` \
                          meta-variable pattern (e.g. `fn $NAME() {}`) across one language. More \
                          precise than regex for code shapes. `lang` is required."
    )]
    async fn structural_search(
        &self,
        Parameters(args): Parameters<AstArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let pattern = args.pattern;
        let lang = args.lang;
        let limit = args.limit.unwrap_or(50);
        let offset = args.offset.unwrap_or(0);
        let hits = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let hits = g
                .searcher()?
                .structural_search(&pattern, &lang, limit, offset)?;
            record_savings(&g, "ast", &hits, |h| h.path.clone());
            Ok(hits)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&hits)
    }

    #[tool(
        description = "Typed go-to-definition: resolve the identifier at file:line:col to its \
                          most likely definition(s), using scope, usage context, and imports. \
                          The unambiguous target is flagged `resolved`; otherwise ranked \
                          candidates are returned. Falls back to text matches when unindexed."
    )]
    async fn goto_definition(
        &self,
        Parameters(args): Parameters<DefArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let (file, line, col) = (args.file, args.line, args.col);
        let hits = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let hits = g.searcher()?.definition(&file, line, col)?;
            record_savings(&g, "def", &hits, |h| h.path.clone());
            Ok(hits)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&hits)
    }

    #[tool(
        description = "Resolved references for the identifier at file:line:col: its definitions, \
                          call sites, and imports across the repo, from the structural reference \
                          index. Use after locating an identifier to see everywhere it is used."
    )]
    async fn references_at(
        &self,
        Parameters(args): Parameters<DefArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let (file, line, col) = (args.file, args.line, args.col);
        let hits = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let hits = g.searcher()?.references_of(&file, line, col)?;
            record_savings(&g, "refs-at", &hits, |h| h.path.clone());
            Ok(hits)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&hits)
    }

    #[tool(
        description = "Read a slice of a file with surrounding context lines. Use the line \
                          numbers returned by search_code/find_symbol to fetch exact code."
    )]
    async fn read_snippet(
        &self,
        Parameters(args): Parameters<SnippetArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let file = args.file;
        let start = args.start;
        let end = args.end.unwrap_or(start);
        let context = args.context.unwrap_or(3);
        let snip = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            let snip = g.searcher()?.read_snippet(&file, start, end, context)?;
            let returned: u64 = snip.lines.iter().map(|l| l.text.len() as u64 + 1).sum();
            let files: BTreeSet<String> = [snip.path.clone()].into_iter().collect();
            g.record_savings("snippet", &files, returned, 1);
            Ok(snip)
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&snip)
    }

    #[tool(
        description = "Summarize the indexed repository: file/symbol counts, language \
                          breakdown, and top-level directories."
    )]
    async fn repo_summary(
        &self,
        Parameters(_args): Parameters<SummaryArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let summary = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            Ok(g.searcher()?.summary())
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&summary)
    }

    #[tool(
        description = "Report greplm index status: whether the project is indexed, segment \
                          count, document and symbol counts, and last index time."
    )]
    async fn index_status(
        &self,
        Parameters(_args): Parameters<StatusArgs>,
    ) -> Result<CallToolResult, ErrorData> {
        let root = self.root.clone();
        let status = tokio::task::spawn_blocking(move || -> greplm_core::Result<_> {
            let g = Greplm::discover(&root)?;
            g.status()
        })
        .await
        .map_err(internal)?
        .map_err(internal)?;
        ok_json(&status)
    }
}

#[tool_handler]
impl ServerHandler for GreplmServer {
    fn get_info(&self) -> ServerInfo {
        let mut info = ServerInfo::default();
        info.protocol_version = ProtocolVersion::default();
        info.capabilities = ServerCapabilities::builder().enable_tools().build();
        info.server_info = Implementation::from_build_env();
        info.instructions = Some(
            "greplm is an extreme-performance code index with code intelligence. Call \
             `index_project` first. To start a task, call `build_context` to load exactly the \
             relevant code on a token budget instead of reading whole files. Use `search_code` \
             for content/regex search, `find_symbol`/`goto_definition` for definitions, \
             `find_callers`/`find_callees`/`impact_of` to navigate the call graph and gauge the \
             blast radius before editing, `structural_search` for AST patterns, and \
             `git_blame`/`symbol_history`/`changed_since` for history. Prefer these over raw grep."
                .to_string(),
        );
        info
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_env("GREPLM_LOG")
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();

    // Optional first positional arg sets the project root; default to cwd.
    let root = std::env::args()
        .nth(1)
        .map(PathBuf::from)
        .unwrap_or(std::env::current_dir()?);

    tracing::info!("greplm-mcp serving root {}", root.display());

    let service = GreplmServer::new(root)
        .serve(rmcp::transport::stdio())
        .await?;
    service.waiting().await?;
    Ok(())
}