semlith 0.14.0

A fast local vector store for AI agents — index files once, keep it current as you save, and answer questions across all of it in milliseconds without leaving the machine.
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
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
//! A stdio MCP server, so an agent can query and maintain the store as tool
//! calls.
//!
//! Deliberately hand-rolled: MCP over stdio is newline-delimited JSON-RPC 2.0,
//! and what a tools-only server needs fits in one file with no extra dependency.
//!
//! The server speaks two eras of the protocol at once. Every client shipping
//! today opens with an `initialize` handshake and then sends bare requests;
//! revision `2026-07-28` deleted that handshake, made `server/discover`
//! mandatory, and moved the protocol version onto every individual request.
//! Rather than choose an era per connection, each message says which era it
//! belongs to: a request carrying `_meta.io.modelcontextprotocol/protocolVersion`
//! is modern, anything else is legacy. A legacy answer is byte for byte what
//! this server has always sent.
//!
//! Everything written to stdout is protocol. Diagnostics go to stderr.

use crate::filter::Filter;
use crate::fleet::Fleet;
use anyhow::Result;
use serde_json::{Value, json};
use std::io::{BufRead, Write};
use std::path::PathBuf;
use std::time::Duration;

/// The MCP revisions this server implements, newest first.
///
/// Every entry is a promise, so every entry has a session in `tests/mcp.rs`
/// proving it. `2025-03-26` is deliberately absent: it is the one revision that
/// required JSON-RPC batching, and this loop reads one message per line.
pub const SUPPORTED: [&str; 4] = ["2026-07-28", "2025-11-25", "2025-06-18", "2024-11-05"];

/// The revision that carries its version per request instead of shaking hands.
const MODERN: &str = "2026-07-28";

/// The newest revision that still has an `initialize` handshake, and so the
/// right answer when a client asks for one we do not implement.
const LEGACY_NEWEST: &str = "2025-11-25";

/// What a client that names no version at all gets. The field is required, so
/// a client omitting it is old rather than new, and the oldest revision is the
/// one every client can read.
const LEGACY_OLDEST: &str = "2024-11-05";

const META_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
const META_SERVER_INFO: &str = "io.modelcontextprotocol/serverInfo";

/// `UnsupportedProtocolVersionError`, from the error range 2026-07-28 reserved
/// for the specification itself.
const UNSUPPORTED_VERSION: i64 = -32022;

/// Freshness hint for the cacheable lists. Neither the tool list nor the
/// server's identity changes while the process lives.
const TTL_MS: u64 = 3_600_000;

/// How many paths `semlith_files` returns before it starts counting instead.
const FILE_LIMIT: usize = 200;

/// How long `semlith_index` works before handing back what it has.
///
/// Clients cut a tool call off at a timeout — Codex documents 60 seconds — and
/// a call killed by the client is indistinguishable from a hung server. This
/// sits under the shortest of those, and the tool says what it did not reach.
const INDEX_BUDGET: Duration = Duration::from_secs(45);

/// `(code, message, data)`. `data` carries the version list on the one error
/// the protocol defines a shape for.
type Fail = (i64, String, Option<Value>);

/// Where a write goes when this process is not the one holding the lock.
///
/// `semlith mcp` in 0.8.0 wrote through its own `Fleet`, which is why an agent
/// and a watcher could not both be pointed at one store. When a daemon is
/// running it is the writer, and the two write tools are handed to it instead;
/// everything else still reads through the `Fleet`, because a reader is allowed
/// to exist alongside the writer and always was.
pub trait Writer: Send + Sync {
    /// `semlith_index`, returning the text the tool reports.
    fn index(&self, store: Option<&str>, paths: &[PathBuf]) -> Result<String, String>;
    /// `semlith_forget`, returning the text the tool reports.
    fn forget(&self, store: Option<&str>, path: &str) -> Result<String, String>;
    /// `semlith_add`, returning the text the tool reports.
    fn add(&self, store: Option<&str>, url: &str) -> Result<String, String>;
}

/// Answer one JSON-RPC request. `None` for a notification, which must not be
/// answered at all.
///
/// The whole protocol lives behind this one function, so a request that arrives
/// over stdio and the same request forwarded over loopback are answered by the
/// same code — which is what makes "every supported revision works through the
/// proxy" true by construction rather than by a second implementation agreeing.
pub fn answer(stores: &mut Fleet, writer: Option<&dyn Writer>, request: &Value) -> Option<Value> {
    let id = request.get("id").cloned()?;
    let method = request.get("method").and_then(Value::as_str).unwrap_or("");
    let params = request.get("params").cloned().unwrap_or(json!({}));
    Some(reply(&id, dispatch(stores, writer, method, &params)))
}

/// Read requests from `input` until EOF, answering on `output`.
pub fn serve(stores: &mut Fleet, input: impl BufRead, mut output: impl Write) -> Result<()> {
    stores.quiet = true;

    for line in input.lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }

        let req: Value = match serde_json::from_str(&line) {
            Ok(v) => v,
            Err(e) => {
                respond(
                    &mut output,
                    &json!(null),
                    Err((-32700, e.to_string(), None)),
                )?;
                continue;
            }
        };

        // Notifications carry no id and must not be answered.
        let Some(id) = req.get("id").cloned() else {
            continue;
        };
        let method = req.get("method").and_then(Value::as_str).unwrap_or("");
        let params = req.get("params").cloned().unwrap_or(json!({}));

        let result = dispatch(stores, None, method, &params);
        respond(&mut output, &id, result)?;
    }
    Ok(())
}

/// The revision a modern request declares, if it is one.
fn declared_version(params: &Value) -> Option<&str> {
    params.get("_meta")?.get(META_VERSION)?.as_str()
}

fn server_info() -> Value {
    json!({ "name": "semlith", "version": env!("CARGO_PKG_VERSION") })
}

/// Add what every modern result carries. Legacy results are left exactly as
/// they were, because an agent already connected must see no change.
fn modernize(mut result: Value, cacheable: Option<&str>) -> Value {
    result["resultType"] = json!("complete");
    result["_meta"] = json!({ META_SERVER_INFO: server_info() });
    if let Some(scope) = cacheable {
        result["ttlMs"] = json!(TTL_MS);
        result["cacheScope"] = json!(scope);
    }
    result
}

fn dispatch(
    stores: &mut Fleet,
    writer: Option<&dyn Writer>,
    method: &str,
    params: &Value,
) -> Result<Value, Fail> {
    let declared = declared_version(params);

    // Checked before the method runs, so a client on a revision we do not
    // implement is told once, plainly, rather than served something that only
    // resembles what it asked for.
    if let Some(version) = declared
        && !SUPPORTED.contains(&version)
    {
        return Err((
            UNSUPPORTED_VERSION,
            "Unsupported protocol version".into(),
            Some(json!({ "supported": SUPPORTED, "requested": version })),
        ));
    }
    let modern = declared == Some(MODERN);

    match method {
        // Mandatory in the modern era, and the probe a dual-era client opens
        // with on stdio: there is no HTTP status code here to fall back on, so
        // this answer is how a client tells a 2026-07-28 server from a 2025 one.
        "server/discover" => Ok(modernize(
            json!({
                "supportedVersions": SUPPORTED,
                "capabilities": { "tools": {} },
                "instructions":
                    "Search and maintain the local semlith stores this server was opened on. \
                     Call semlith_stats first to learn the store names the other tools accept.",
            }),
            Some("public"),
        )),

        "initialize" => {
            let asked = params.get("protocolVersion").and_then(Value::as_str);
            let version = negotiate(asked);
            // "The agent sees no tools" is otherwise undiagnosable from the
            // client's side, and stderr is the one channel a stdio client
            // captures for exactly this.
            match asked {
                Some(a) if a != version => {
                    eprintln!("semlith: client asked for MCP {a}; answering {version}")
                }
                _ => eprintln!("semlith: MCP {version}"),
            }
            Ok(json!({
                "protocolVersion": version,
                "capabilities": { "tools": {} },
                "serverInfo": server_info(),
            }))
        }

        // Removed by 2026-07-28, still sent by legacy clients. Answering it
        // costs one line; refusing it costs somebody a connection.
        "ping" => Ok(json!({})),

        "tools/list" => {
            let listed = json!({ "tools": tools(stores) });
            // Private, not public: the descriptions name the stores this
            // process was opened on, so the answer is this server's, not one
            // an intermediary may hand to another client.
            Ok(if modern {
                modernize(listed, Some("private"))
            } else {
                listed
            })
        }

        "tools/call" => {
            let called = call_tool(stores, writer, params)?;
            Ok(if modern {
                modernize(called, None)
            } else {
                called
            })
        }

        other => Err((-32601, format!("unknown method: {other}"), None)),
    }
}

/// The revision to answer a handshake with.
///
/// A server that echoes what it was asked claims every revision that exists,
/// including the ones that deleted the handshake it is answering. What the
/// protocol asks for instead is the truth: the same version when we implement
/// it, and otherwise the newest one we do.
fn negotiate(requested: Option<&str>) -> &'static str {
    match requested {
        Some(v) => SUPPORTED
            .iter()
            .find(|s| **s == v && **s != MODERN)
            .copied()
            .unwrap_or(LEGACY_NEWEST),
        None => LEGACY_OLDEST,
    }
}

fn tools(stores: &Fleet) -> Value {
    // An agent cannot narrow to a store whose name it has never seen, so the
    // open stores are part of the tool description rather than something to
    // discover by trial.
    tool_defs(&stores.labels().join(", "))
}

/// Every tool name this server serves.
///
/// The portal's Agents page reads this rather than repeating the list. Two
/// hand-written copies of a tool surface in two files is precisely how a tool
/// ends up served by the server and invisible in the portal, which the parity
/// rule exists to prevent — so there is only one copy.
pub fn tool_names() -> Vec<String> {
    tool_list().into_iter().map(|(name, _)| name).collect()
}

/// Every tool, with the one-line purpose its definition advertises.
///
/// The Agents page lists these. Reading the description out of the definition
/// rather than writing a second one beside it is what stops a tool being
/// served with one description and documented with another — the title an
/// annotation carries is the sentence a client shows a user, so it is the one
/// the portal shows too.
pub fn tool_list() -> Vec<(String, String)> {
    tool_defs("")
        .as_array()
        .map(|defs| {
            defs.iter()
                .filter_map(|tool| {
                    let name = tool["name"].as_str()?.to_string();
                    let about = tool["annotations"]["title"]
                        .as_str()
                        .or_else(|| tool["description"].as_str())
                        .unwrap_or_default()
                        .to_string();
                    Some((name, about))
                })
                .collect()
        })
        .unwrap_or_default()
}

fn tool_defs(open: &str) -> Value {
    let store_arg = format!(
        "Restrict the search to these stores by name. Open stores: {open}. \
         Omit to search all of them, which is usually right — narrow only when \
         you already know which corpus holds the answer."
    );
    let write_store_arg = format!(
        "Which store to write to, by name. Open stores: {open}. \
         Required when more than one is open, since a store takes one writer."
    );

    json!([
        {
            "name": "semlith_search",
            "description":
                "Semantic search over the local semlith store: docs, PDFs, code, and notes \
                 that have been indexed on this machine. Returns the most relevant excerpts \
                 with their file path and line range. Use this instead of reading whole files \
                 when you need to find where something is discussed or implemented. \
                 Optionally narrow the search to one part of the corpus with path, ext or lang.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "What you are looking for. A question in plain English, or an exact identifier — both are searched."
                    },
                    "k": {
                        "type": "integer",
                        "description": "How many excerpts to return (default 8).",
                        "minimum": 1,
                        "maximum": 50
                    },
                    "path": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description":
                            "Restrict the search to files matching these globs, e.g. \"src/**\". \
                             A pattern that does not start with / matches anywhere in the tree. \
                             `*` crosses directory separators, so `src/*` reaches the whole \
                             subtree. Only filter when you already know which part of the \
                             corpus holds the answer — a wrong guess hides it entirely."
                    },
                    "ext": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Restrict the search to these file extensions, e.g. [\"rs\", \"toml\"]."
                    },
                    "lang": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description":
                            "Restrict the search to these languages, e.g. [\"rust\"]. Accepts: \
                             c, cpp, csharp, css, go, haskell, html, java, javascript, json, \
                             kotlin, lua, markdown, ocaml, php, python, ruby, rust, scala, \
                             shell, sql, swift, toml, typescript, yaml."
                    },
                    "store": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": store_arg
                    }
                },
                "required": ["query"]
            },
            "annotations": { "title": "Search the semlith store", "readOnlyHint": true }
        },
        {
            "name": "semlith_stats",
            "description":
                "Report what the local semlith stores currently contain: file count, chunk \
                 count, indexed bytes, and the embedding model, one line per store. Use this \
                 to check whether a corpus is indexed before searching it, and to learn the \
                 store names the other tools accept.",
            "inputSchema": { "type": "object", "properties": {} },
            "annotations": { "title": "Describe the semlith stores", "readOnlyHint": true }
        },
        {
            "name": "semlith_files",
            "description":
                "List the files currently indexed, narrowed the same way as a search. Use it \
                 to tell \"this file is not indexed\" apart from \"the corpus does not discuss \
                 this\", which a search returning nothing cannot say.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Only list files matching these globs, e.g. \"src/**\"."
                    },
                    "ext": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Only list files with these extensions, e.g. [\"rs\"]."
                    },
                    "lang": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Only list files of these languages, e.g. [\"rust\"]."
                    },
                    "store": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": store_arg
                    },
                    "limit": {
                        "type": "integer",
                        "description": "How many paths to return before counting the rest (default 200).",
                        "minimum": 1
                    }
                }
            },
            "annotations": { "title": "List indexed files", "readOnlyHint": true }
        },
        {
            "name": "semlith_index",
            "description":
                "Index files and directories into a store that is already open, so their \
                 contents become searchable in this session. Only what has changed is \
                 re-embedded. Large corpora take longer than one tool call allows: the call \
                 returns what it managed and how much is left, and calling it again continues \
                 from there.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Files or directories to index. Directories are walked, honouring .gitignore."
                    },
                    "store": { "type": "string", "description": write_store_arg }
                },
                "required": ["path"]
            },
            "annotations": { "title": "Index files into the store", "readOnlyHint": false }
        },
        {
            "name": "semlith_add",
            "description":
                "Fetch one URL into the store and index it, so its contents become \
                 searchable in this session: a web page, a PDF such as an arXiv paper, or a \
                 file on GitHub (a /blob/ link is rewritten to the raw file). Exactly one \
                 request is made, for exactly this URL — nothing is crawled, no link is \
                 followed, and no credential is ever sent. The file is written inside the \
                 store's own downloads directory, never into the user's working tree. \
                 Refused when semlith is running with --airgap.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "url": {
                        "type": "string",
                        "description": "The https URL to fetch. Plain http is refused."
                    },
                    "store": { "type": "string", "description": write_store_arg }
                },
                "required": ["url"]
            },
            "annotations": {
                "title": "Add a URL to the store",
                "readOnlyHint": false,
                "openWorldHint": true
            }
        },
        {
            "name": "semlith_forget",
            "description":
                "Remove one file from a store, so it stops appearing in searches. The file on \
                 disk is untouched; only what was indexed about it goes.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "path": { "type": "string", "description": "The file to remove from the index." },
                    "store": { "type": "string", "description": write_store_arg }
                },
                "required": ["path"]
            },
            "annotations": {
                "title": "Forget a file",
                "readOnlyHint": false,
                "destructiveHint": true
            }
        },
        {
            "name": "semlith_symbol",
            "description":
                "Find where a symbol is defined, by exact name, across every indexed store. \
                 Returns the file and line range of each definition. Use this instead of \
                 grepping for `fn name` or `def name`: it reads the definition out of the \
                 parsed syntax tree, so it does not match the name in a comment, a string, \
                 or a call. Six languages carry symbols — Rust, TypeScript, Python, Go, Java \
                 and C.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "name": { "type": "string", "description": "The symbol's name, matched exactly." },
                    "k": { "type": "integer", "description": "Most definitions to return. Default 20." },
                    "store": { "type": "string", "description": store_arg }
                },
                "required": ["name"]
            },
            "annotations": { "title": "Find a symbol's definition", "readOnlyHint": true }
        },
        {
            "name": "semlith_neighbors",
            "description":
                "List what calls a symbol and what it calls, one hop in each direction, from \
                 the extracted code graph. Use this to answer \"who uses this\" and \"what \
                 does this depend on\" in one call rather than a chain of greps. Each edge \
                 says whether it was resolved through an import (extracted) or matched by \
                 name (inferred) — do not treat an inferred edge as certain.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "name": { "type": "string", "description": "The symbol's name, matched exactly." },
                    "kind": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description":
                            "Only follow edges of these kinds: defines, calls, imports, \
                             references, contains. Omit for all of them."
                    },
                    "store": { "type": "string", "description": store_arg }
                },
                "required": ["name"]
            },
            "annotations": { "title": "List a symbol's callers and callees", "readOnlyHint": true }
        },
        {
            "name": "semlith_path",
            "description":
                "Show the shortest chain of edges from one symbol to another, naming every \
                 edge in it. Use it to find out how two parts of a codebase are connected, \
                 or to confirm that they are not. Follows calls, imports and references; \
                 returns nothing when the two are unconnected within the depth searched, \
                 which is an answer rather than a failure.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "from": { "type": "string", "description": "The symbol the chain starts at." },
                    "to": { "type": "string", "description": "The symbol the chain ends at." },
                    "depth": { "type": "integer", "description": "Most hops to search. Default 6." },
                    "store": { "type": "string", "description": store_arg }
                },
                "required": ["from", "to"]
            },
            "annotations": { "title": "Find the path between two symbols", "readOnlyHint": true }
        }
    ])
}

fn call_tool(
    stores: &mut Fleet,
    writer: Option<&dyn Writer>,
    params: &Value,
) -> Result<Value, Fail> {
    let name = params.get("name").and_then(Value::as_str).unwrap_or("");
    let args = params.get("arguments").cloned().unwrap_or(json!({}));

    let body = match name {
        "semlith_search" => {
            let Some(query) = args.get("query").and_then(Value::as_str) else {
                return Err((-32602, "missing required argument: query".into(), None));
            };
            let k = args.get("k").and_then(Value::as_u64).unwrap_or(8) as usize;

            let filter = match filter_of(&args) {
                Ok(f) => f,
                // An unknown language is the agent's mistake to correct, so it
                // goes back in-band with the list rather than as a protocol error.
                Err(e) => return Ok(tool_error(&e)),
            };

            // A store name the agent guessed is the agent's mistake to correct,
            // so it comes back in-band with the names that exist.
            let only = strings(&args, "store");

            // Told apart because an agent that scoped to the wrong subsystem
            // should widen the filter, not conclude the corpus is empty. A
            // failure here is a broken store, not an empty selection, and must
            // not be reported as one.
            let selected = if filter.is_empty() {
                1
            } else {
                match stores.matching_files(&filter) {
                    Ok(n) => n,
                    Err(e) => return Ok(tool_error(&format!("search failed: {e}"))),
                }
            };

            if selected == 0 {
                "No indexed file matches that path/ext/lang filter. Try again without it."
                    .to_string()
            } else {
                match stores.search_in(Some(&only), query, k.clamp(1, 50), &filter) {
                    Ok(hits) if hits.is_empty() => "No matches in the semlith store.".to_string(),
                    Ok(hits) => render(&hits),
                    // Tool failures are reported in-band so the agent can react,
                    // rather than as a protocol-level error.
                    Err(e) => return Ok(tool_error(&e.to_string())),
                }
            }
        }
        "semlith_stats" => {
            let many = stores.len() > 1;
            let mut lines = Vec::new();
            for (label, store) in stores.each() {
                let (files, chunks, bytes) = match store.stats() {
                    Ok(s) => s,
                    Err(e) => return Ok(tool_error(&format!("stats failed: {e}"))),
                };
                let body = format!(
                    "{files} files, {chunks} chunks, {} indexed, model {} ({} dim)",
                    crate::human_bytes(bytes),
                    store.model(),
                    store.dim(),
                );
                // One store answers exactly as it did before stores could be
                // combined; a name in front of it would only cost tokens.
                lines.push(if many {
                    format!("{label}: {body}")
                } else {
                    body
                });
            }
            lines.join("\n")
        }
        "semlith_files" => {
            let filter = match filter_of(&args) {
                Ok(f) => f,
                Err(e) => return Ok(tool_error(&e)),
            };
            let only = strings(&args, "store");
            let limit = args
                .get("limit")
                .and_then(Value::as_u64)
                .map(|n| n as usize)
                .unwrap_or(FILE_LIMIT)
                .max(1);

            match stores.paths_in(Some(&only), &filter, limit) {
                Ok((paths, _)) if paths.is_empty() => {
                    "No file in the semlith store matches that.".to_string()
                }
                Ok((paths, left_out)) => {
                    let mut out = paths.join("\n");
                    // A truncated list that does not say so is how an agent
                    // decides a file it cannot see was never indexed.
                    if left_out > 0 {
                        out.push_str(&format!(
                            "\n… and {left_out} more. Narrow with path/ext/lang, or raise limit."
                        ));
                    }
                    out
                }
                Err(e) => return Ok(tool_error(&e.to_string())),
            }
        }
        "semlith_index" => {
            let roots: Vec<PathBuf> = strings(&args, "path").iter().map(PathBuf::from).collect();
            if roots.is_empty() {
                return Err((-32602, "missing required argument: path".into(), None));
            }
            if let Some(writer) = writer {
                let named = strings(&args, "store");
                return Ok(
                    match writer.index(named.first().map(String::as_str), &roots) {
                        Ok(text) => json!({ "content": [{ "type": "text", "text": text }] }),
                        Err(e) => tool_error(&e),
                    },
                );
            }

            let store = match stores.writable(&strings(&args, "store")) {
                Ok(s) => s,
                Err(e) => return Ok(tool_error(&e.to_string())),
            };

            // The key that opens this tool lives in a config file on disk, so
            // what it can reach is what a copied config file can reach. An
            // agent may index this store's own roots and the home directory,
            // and never a credential by name. `semlith index` on the command
            // line is not held to the boundary — the person typing it is the
            // owner of the machine.
            store.boundary = crate::Boundary::within(crate::home::index_roots(store.dir()));

            match store.index_paths_within(&roots, index_budget(), |_, _| {}) {
                // A store another process is writing is a conflict to report,
                // not an error to fail the call with: the agent can wait, or
                // write somewhere else.
                Err(e) => return Ok(tool_error(&e.to_string())),
                Ok(report) => {
                    let mut out = format!(
                        "{} indexed, {} unchanged, {} skipped, {} removed ({} chunks)",
                        report.indexed,
                        report.unchanged,
                        report.skipped,
                        report.removed,
                        report.chunks,
                    );
                    if report.remaining > 0 {
                        out.push_str(&format!(
                            "\nStopped at the time limit with {} paths remaining. \
                             Call semlith_index again with the same arguments to continue; \
                             nothing already indexed is redone.",
                            report.remaining
                        ));
                    }
                    // Named, one per line, with the rule that refused each. A
                    // refusal reported as a count is one an agent retries.
                    for (path, why) in &report.refused {
                        out.push_str(&format!("\nrefused: {path} — {why}"));
                    }
                    out
                }
            }
        }
        "semlith_add" => {
            // A bare string is what the schema asks for; an agent sends a
            // one-element array often enough that refusing it teaches nothing.
            let urls = strings(&args, "url");
            let url = match urls.as_slice() {
                [one] => one.clone(),
                [] => return Err((-32602, "missing required argument: url".into(), None)),
                many => {
                    return Ok(tool_error(&format!(
                        "semlith_add fetches one URL, not {}: {}",
                        many.len(),
                        many.join(", ")
                    )));
                }
            };
            let named = strings(&args, "store");

            if let Some(writer) = writer {
                return Ok(match writer.add(named.first().map(String::as_str), &url) {
                    Ok(text) => json!({ "content": [{ "type": "text", "text": text }] }),
                    Err(e) => tool_error(&e),
                });
            }

            let store = match stores.writable(&named) {
                Ok(s) => s,
                Err(e) => return Ok(tool_error(&e.to_string())),
            };

            // A refused fetch is the agent's answer, not a protocol failure:
            // the URL was http, or too large, or a type with no reader, and the
            // agent can act on any of those.
            let fetched = match crate::add::fetch(&url, store.dir()) {
                Ok(fetched) => fetched,
                Err(e) => return Ok(tool_error(&format!("{e:#}"))),
            };
            match store.index_paths_within(
                std::slice::from_ref(&fetched.path),
                index_budget(),
                |_, _| {},
            ) {
                Err(e) => return Ok(tool_error(&e.to_string())),
                Ok(report) => format!(
                    "Fetched {} into {} and indexed {} chunks.",
                    fetched.url,
                    fetched.path.display(),
                    report.chunks
                ),
            }
        }
        "semlith_forget" => {
            // A bare string is what the schema asks for, but an agent sends a
            // one-element array often enough that refusing it teaches nothing.
            let paths = strings(&args, "path");
            let path = match paths.as_slice() {
                [one] => one.clone(),
                [] => return Err((-32602, "missing required argument: path".into(), None)),
                many => {
                    return Ok(tool_error(&format!(
                        "semlith_forget removes one file, not {}: {}",
                        many.len(),
                        many.join(", ")
                    )));
                }
            };
            if let Some(writer) = writer {
                let named = strings(&args, "store");
                return Ok(
                    match writer.forget(named.first().map(String::as_str), &path) {
                        Ok(text) => json!({ "content": [{ "type": "text", "text": text }] }),
                        Err(e) => tool_error(&e),
                    },
                );
            }

            let store = match stores.writable(&strings(&args, "store")) {
                Ok(s) => s,
                Err(e) => return Ok(tool_error(&e.to_string())),
            };
            match store.forget(std::path::Path::new(&path)) {
                Ok((0, 0)) => format!("{path} was not indexed; nothing removed."),
                Ok((0, images)) => format!("Removed {images} image vector(s) for {path}."),
                Ok((chunks, 0)) => format!("Removed {chunks} chunks for {path}."),
                Ok((chunks, images)) => {
                    format!("Removed {chunks} chunks and {images} image vector(s) for {path}.")
                }
                Err(e) => return Ok(tool_error(&e.to_string())),
            }
        }
        "semlith_symbol" => {
            let Some(name) = args.get("name").and_then(Value::as_str) else {
                return Err((-32602, "missing required argument: name".into(), None));
            };
            let k = args.get("k").and_then(Value::as_u64).unwrap_or(20) as usize;
            let only = strings(&args, "store");
            match stores.symbols_in(Some(&only), name, k.clamp(1, 200)) {
                Ok(found) if found.is_empty() => empty_graph(stores, name),
                Ok(found) => found
                    .iter()
                    .map(|s| {
                        format!(
                            "{} ({}) {}{}:{}-{}",
                            s.name,
                            s.kind,
                            label_of(&s.store),
                            s.path,
                            s.start_line,
                            s.end_line
                        )
                    })
                    .collect::<Vec<_>>()
                    .join("\n"),
                Err(e) => return Ok(tool_error(&e.to_string())),
            }
        }
        "semlith_neighbors" => {
            let Some(name) = args.get("name").and_then(Value::as_str) else {
                return Err((-32602, "missing required argument: name".into(), None));
            };
            let kinds = strings(&args, "kind");
            if let Some(bad) = kinds
                .iter()
                .find(|k| !crate::graph::KINDS.contains(&k.as_str()))
            {
                return Ok(tool_error(&format!(
                    "unknown edge kind {bad:?}; the kinds are {}",
                    crate::graph::KINDS.join(", ")
                )));
            }
            let only = strings(&args, "store");
            match stores.neighbours_in(Some(&only), name, &kinds) {
                Ok(n) if n.callers.is_empty() && n.callees.is_empty() => empty_graph(stores, name),
                Ok(n) => format!(
                    "callers of {name} ({}):\n{}\n\ncallees of {name} ({}):\n{}",
                    n.callers.len(),
                    render_ends(&n.callers),
                    n.callees.len(),
                    render_ends(&n.callees),
                ),
                Err(e) => return Ok(tool_error(&e.to_string())),
            }
        }
        "semlith_path" => {
            let (Some(from), Some(to)) = (
                args.get("from").and_then(Value::as_str),
                args.get("to").and_then(Value::as_str),
            ) else {
                return Err((-32602, "missing required arguments: from, to".into(), None));
            };
            let depth = args.get("depth").and_then(Value::as_u64).unwrap_or(6) as u32;
            let only = strings(&args, "store");
            match stores.path_in(Some(&only), from, to, depth.clamp(1, 20)) {
                Ok(Some(steps)) if steps.is_empty() => format!("{from} is {to}."),
                Ok(Some(steps)) => {
                    let chain = steps
                        .iter()
                        .map(|s| format!("{} --{}({})--> {}", s.from, s.kind, s.confidence, s.to))
                        .collect::<Vec<_>>()
                        .join("\n");
                    format!("{} hops:\n{chain}", steps.len())
                }
                Ok(None) => format!(
                    "No chain from {from} to {to} within {depth} hops. They may be \
                     unconnected, or connected only further than that."
                ),
                Err(e) => return Ok(tool_error(&e.to_string())),
            }
        }
        other => return Err((-32602, format!("unknown tool: {other}"), None)),
    };

    Ok(json!({ "content": [{ "type": "text", "text": body }] }))
}

/// What to say when the graph has nothing for a name.
///
/// An empty graph and an absent symbol read identically to an agent, and only
/// one of them means "this corpus has not been indexed since the graph
/// existed". Telling them apart is the difference between the agent running
/// `semlith_index` and concluding the symbol is not there.
fn empty_graph(stores: &Fleet, name: &str) -> String {
    let symbols: i64 = stores
        .each()
        .map(|(_, store)| {
            crate::store::graph_stats(store.db())
                .map(|(s, _)| s)
                .unwrap_or(0)
        })
        .sum();
    if symbols == 0 {
        "This store has no symbols yet: its graph is built as files are indexed. Call \
         semlith_index on the corpus, then ask again."
            .to_string()
    } else {
        format!(
            "No symbol named {name} in the graph. Only Rust, TypeScript, Python, Go, Java \
             and C carry symbols; semlith_search still finds text in everything else."
        )
    }
}

fn label_of(store: &Option<String>) -> String {
    match store {
        Some(label) => format!("[{label}] "),
        None => String::new(),
    }
}

fn render_ends(ends: &[crate::store::EdgeEnd]) -> String {
    if ends.is_empty() {
        return "  none".to_string();
    }
    ends.iter()
        .map(|e| {
            format!(
                "  {} via {} ({})  {}{}:{}",
                e.symbol.name,
                e.kind,
                e.confidence,
                label_of(&e.symbol.store),
                e.symbol.path,
                e.symbol.start_line
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// How long an index tool call may work for.
///
/// Overridable because clients disagree about how long a tool call may take,
/// and the person who knows which client this is, is the one who wrote its
/// configuration — not the model on the other end of the tool.
fn index_budget() -> Duration {
    match std::env::var("SEMLITH_MCP_INDEX_BUDGET") {
        Ok(v) => match v.trim().parse::<u64>() {
            Ok(seconds) => Duration::from_secs(seconds),
            Err(_) => INDEX_BUDGET,
        },
        Err(_) => INDEX_BUDGET,
    }
}

/// The path/ext/lang narrowing three tools share.
fn filter_of(args: &Value) -> Result<Filter, String> {
    Filter::new(
        &strings(args, "path"),
        &strings(args, "ext"),
        &strings(args, "lang"),
    )
    .map_err(|e| e.to_string())
}

/// One filter argument as strings. A bare string is accepted alongside an
/// array, because that is what an agent produces about half the time.
fn strings(args: &Value, key: &str) -> Vec<String> {
    match args.get(key) {
        Some(Value::String(s)) => vec![s.clone()],
        Some(Value::Array(items)) => items
            .iter()
            .filter_map(|i| i.as_str().map(str::to_string))
            .collect(),
        _ => Vec::new(),
    }
}

fn tool_error(message: &str) -> Value {
    json!({ "content": [{ "type": "text", "text": message }], "isError": true })
}

/// Compact, agent-readable: a locator line then the excerpt. Cheap to parse,
/// cheap in tokens, and the locator is enough to go read the real file.
fn render(hits: &[crate::Hit]) -> String {
    let mut out = String::new();
    for (i, h) in hits.iter().enumerate() {
        // The store, when there is more than one, goes in front of the path:
        // one short word, and without it an excerpt from the client is
        // indistinguishable from one from the service.
        let from = match &h.store {
            Some(label) => format!("{label} "),
            None => String::new(),
        };
        // Which lists found it. A hit that only the graph reached is a
        // neighbour of a match rather than a match, and an agent that cannot
        // tell the two apart will quote it as though the query found it.
        let via = if h.lists.is_empty() {
            String::new()
        } else {
            format!(" via {}", h.lists.join("+"))
        };
        // An image has no excerpt to quote: it is named, sized, and left for
        // the agent to open. Saying "an image" outright matters more here than
        // anywhere else — an agent handed a path with no text under it would
        // otherwise read the silence as an empty file.
        if let Some(px) = h.image {
            out.push_str(&format!(
                "[{}] {from}{} — image, {}x{} px (score {:.3}{via})\n\n",
                i + 1,
                h.path,
                px.width,
                px.height,
                h.score,
            ));
            continue;
        }
        out.push_str(&format!(
            "[{}] {from}{}:{}-{} (score {:.3}{via})\n{}\n\n",
            i + 1,
            h.path,
            h.start_line,
            h.end_line,
            h.score,
            h.text.trim_end()
        ));
    }
    out.trim_end().to_string()
}

fn respond(out: &mut impl Write, id: &Value, result: Result<Value, Fail>) -> std::io::Result<()> {
    writeln!(out, "{}", reply(id, result))?;
    out.flush()
}

/// One JSON-RPC response object.
fn reply(id: &Value, result: Result<Value, Fail>) -> Value {
    match result {
        Ok(value) => json!({ "jsonrpc": "2.0", "id": id, "result": value }),
        Err((code, message, data)) => {
            let mut error = json!({ "code": code, "message": message });
            if let Some(data) = data {
                error["data"] = data;
            }
            json!({ "jsonrpc": "2.0", "id": id, "error": error })
        }
    }
}

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

    /// The defect this release exists to fix: answering a handshake with
    /// whatever it was sent claims every revision that will ever exist,
    /// including the ones that deleted handshakes.
    #[test]
    fn a_revision_we_do_not_implement_is_never_echoed() {
        assert_eq!(negotiate(Some("1900-01-01")), LEGACY_NEWEST);
        assert_eq!(negotiate(Some("2029-11-05")), LEGACY_NEWEST);
        // The modern revision has no handshake, so a client asking for it over
        // `initialize` is asking for something that does not exist there.
        assert_eq!(negotiate(Some(MODERN)), LEGACY_NEWEST);
    }

    #[test]
    fn a_revision_we_do_implement_is_answered_with_itself() {
        for revision in ["2025-11-25", "2025-06-18", "2024-11-05"] {
            assert_eq!(negotiate(Some(revision)), revision);
        }
        // No version named at all: the field is required, so this client is
        // old rather than new.
        assert_eq!(negotiate(None), LEGACY_OLDEST);
    }

    /// A modern result is told apart from a legacy one by the message, not by
    /// the connection, so the marker has to be on the result itself.
    #[test]
    fn only_modern_requests_declare_a_version() {
        let modern = json!({ "_meta": { META_VERSION: MODERN } });
        assert_eq!(declared_version(&modern), Some(MODERN));
        assert_eq!(declared_version(&json!({ "name": "semlith_stats" })), None);
    }
}