kjarni-cli 0.4.4

Kjarni from the shell: classification, embeddings, reranking, search, chat, summarization, translation and speech-to-text as commands, and an MCP server for AI agents. Same output as PyTorch.
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
//! `kjarni mcp`: Kjarni's capabilities as tools for AI agents, over the Model
//! Context Protocol on stdio.
//!
//! An agent (Claude Code, Cursor, Claude Desktop, any MCP client) starts this
//! as a subprocess and calls tools: semantic search over a folder of documents
//! or of photos, speech to text, classification, reranking and similarity, all
//! on the user's machine.
//!
//! The protocol is newline-delimited JSON-RPC 2.0. Only the part of MCP a tool
//! server needs is implemented: initialize, ping, tools/list and tools/call.
//! Models load on first use and stay loaded for the session, so only the first
//! call of each kind pays for it.

use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;

use anyhow::{Context, Result, anyhow, bail};
use kjarni::classifier::Classifier;
use kjarni::common::{DownloadPolicy, ensure_model_downloaded};
use kjarni::embedder::Embedder;
use kjarni::reranker::Reranker;
use kjarni::searcher::{SearchOptions, Searcher};
use kjarni::transcriber::Transcriber;
use kjarni::{ImageIndex, Indexer, ModelType, SearchMode};
use serde_json::{Value, json};
use tokio::io::AsyncBufReadExt;

/// Protocol versions this server speaks, newest first. A client asking for
/// one of these gets it back; anything else gets the newest.
const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];

/// The embedding model behind `search_folder`. Small and fast, which matters
/// more than the last few points of quality when an agent is waiting.
const SEARCH_MODEL: &str = "minilm-l6-v2";
const RERANK_MODEL: &str = "minilm-l6-v2-cross-encoder";
const TRANSCRIBE_MODEL: &str = "whisper-small";
const CLASSIFY_MODEL: &str = "distilbert-sentiment";
/// CLIP, which puts photos and descriptions in one space for `search_images`.
const IMAGE_MODEL: ModelType = ModelType::ClipVitBase32;

/// Never indexed by `search_folder`: build output, dependencies and virtual
/// environments, which in a code repository outnumber the sources many times
/// over. Hidden folders such as .git are skipped as well.
pub(crate) const EXCLUDED: &[&str] = &[
    "target",
    "node_modules",
    "dist",
    "build",
    "out",
    "bin",
    "obj",
    "vendor",
    "venv",
    "__pycache__",
    "*.min.js",
];

const INSTRUCTIONS: &str = "Kjarni runs AI models locally on the user's machine; nothing leaves it. \
Use search_folder to find passages in a folder of documents or code by meaning, not just by \
exact words; the first search of a folder builds an index, later ones reuse it until files \
change. Use search_images to find photos in a folder by describing what is in them. Use transcribe for audio or video files, classify for sentiment, emotion or toxicity, \
rerank to order candidate passages by relevance to a query, and similarity to compare two \
texts. Models download once on first use.";

pub async fn run() -> Result<()> {
    let mut out = protocol_stdout();
    let mut server = Server::default();
    let mut lines = tokio::io::BufReader::new(tokio::io::stdin()).lines();

    while let Some(line) = lines.next_line().await? {
        if line.trim().is_empty() {
            continue;
        }
        let response = match serde_json::from_str::<Value>(&line) {
            Ok(message) => server.handle(&message).await,
            Err(e) => Some(error_response(
                Value::Null,
                -32700,
                &format!("parse error: {e}"),
            )),
        };
        if let Some(response) = response {
            writeln!(out, "{response}")?;
            out.flush()?;
        }
    }
    Ok(())
}

/// Where protocol messages go. Anything else the process prints, a library's
/// progress line or a download notice, would corrupt the stream, so stdout
/// itself is pointed at stderr and the protocol keeps a private copy of the
/// original.
#[cfg(unix)]
fn protocol_stdout() -> Box<dyn Write + Send> {
    use std::os::fd::FromRawFd;
    // SAFETY: plain descriptor duplication on 0..2, which this process owns.
    unsafe {
        let saved = libc::dup(1);
        if saved >= 0 && libc::dup2(2, 1) >= 0 {
            return Box::new(std::fs::File::from_raw_fd(saved));
        }
    }
    Box::new(std::io::stdout())
}

/// On Windows the library's output is kept quiet instead: every model is
/// built with `quiet`, and downloads are the one remaining source of output.
#[cfg(not(unix))]
fn protocol_stdout() -> Box<dyn Write + Send> {
    Box::new(std::io::stdout())
}

#[derive(Default)]
struct Server {
    searcher: Option<Searcher>,
    rerank_searcher: Option<Searcher>,
    indexer: Option<Indexer>,
    embedder: Option<Embedder>,
    reranker: Option<Reranker>,
    transcriber: Option<Transcriber>,
    images: Option<ImageIndex>,
    classifiers: HashMap<String, Classifier>,
}

impl Server {
    /// Answers one message. Notifications get no response.
    async fn handle(&mut self, message: &Value) -> Option<Value> {
        let id = message.get("id").cloned()?;
        let method = message
            .get("method")
            .and_then(Value::as_str)
            .unwrap_or_default();
        let params = message.get("params").cloned().unwrap_or(Value::Null);

        let result = match method {
            "initialize" => Ok(initialize(&params)),
            "ping" => Ok(json!({})),
            "tools/list" => Ok(json!({ "tools": tools() })),
            "tools/call" => Ok(self.call(&params).await),
            _ => Err((-32601, format!("method not found: {method}"))),
        };
        Some(match result {
            Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
            Err((code, message)) => error_response(id, code, &message),
        })
    }

    /// Runs a tool. Failures are results with `isError`, as MCP asks, so the
    /// agent sees what went wrong and can correct its call.
    async fn call(&mut self, params: &Value) -> Value {
        let name = params
            .get("name")
            .and_then(Value::as_str)
            .unwrap_or_default();
        let args = params
            .get("arguments")
            .cloned()
            .unwrap_or_else(|| json!({}));
        let outcome = match name {
            "search_folder" => self.search_folder(&args).await,
            "search_images" => self.search_images(&args).await,
            "transcribe" => self.transcribe(&args).await,
            "classify" => self.classify(&args).await,
            "rerank" => self.rerank(&args).await,
            "similarity" => self.similarity(&args).await,
            _ => Err(anyhow!("unknown tool: {name}")),
        };
        match outcome {
            Ok(text) => json!({ "content": [{ "type": "text", "text": text }] }),
            Err(e) => {
                json!({ "content": [{ "type": "text", "text": format!("{e:#}") }], "isError": true })
            }
        }
    }

    async fn search_folder(&mut self, args: &Value) -> Result<String> {
        let folder = PathBuf::from(string(args, "path")?);
        let folder = folder
            .canonicalize()
            .with_context(|| format!("cannot open {}", folder.display()))?;
        if !folder.is_dir() {
            bail!("{} is not a folder", folder.display());
        }
        let query = string(args, "query")?;
        let mode: SearchMode = optional_string(args, "mode")
            .unwrap_or("hybrid")
            .parse()
            .map_err(|e: String| anyhow!(e))?;
        let top_k = args
            .get("top_k")
            .and_then(Value::as_u64)
            .unwrap_or(5)
            .clamp(1, 50) as usize;
        let rerank = args.get("rerank").and_then(Value::as_bool).unwrap_or(false);

        let (index, note) = self.index_for(&folder).await?;
        let index = index.to_string_lossy().into_owned();
        let options = SearchOptions::new().mode(mode).top_k(top_k).rerank(rerank);
        let searcher = if rerank {
            if self.rerank_searcher.is_none() {
                let s = Searcher::builder(SEARCH_MODEL)
                    .reranker(RERANK_MODEL)
                    .quiet(true)
                    .build()
                    .await?;
                self.rerank_searcher = Some(s);
            }
            self.rerank_searcher.as_ref().expect("built above")
        } else {
            if self.searcher.is_none() {
                self.searcher = Some(Searcher::builder(SEARCH_MODEL).quiet(true).build().await?);
            }
            self.searcher.as_ref().expect("built above")
        };
        let results = searcher
            .search_with_options(&index, query, &options)
            .await?;

        let mut text = String::new();
        if let Some(note) = note {
            text.push_str(&format!("({note} for this search.)\n\n"));
        }
        if results.is_empty() {
            text.push_str("No matching passages.");
        }
        for (i, r) in results.iter().enumerate() {
            let source = r.metadata.get("source").map(String::as_str).unwrap_or("?");
            text.push_str(&format!(
                "{}. {source}  (score {:.3})\n{}\n\n",
                i + 1,
                r.score,
                clip(r.text.trim(), 800)
            ));
        }
        Ok(text.trim_end().to_string())
    }

    /// The index for a folder, and a note on what was updated if anything was.
    /// Built on first use, then kept in step with the folder: only new and
    /// changed files are embedded. Indexes live in Kjarni's cache, never in the
    /// folder.
    async fn index_for(&mut self, folder: &Path) -> Result<(PathBuf, Option<String>)> {
        let root = kjarni::registry::cache_dir().join("mcp-indexes");
        let index = root.join(format!(
            "{:016x}",
            fnv1a(folder.as_os_str().as_encoded_bytes())
        ));
        let stamp_file = index.with_extension("stamp");
        let stamp = fingerprint(folder, SEARCH_MODEL);

        let current = std::fs::read_to_string(&stamp_file).ok();
        if index.exists() && current.as_deref() == Some(stamp.as_str()) {
            return Ok((index, None));
        }
        if self.indexer.is_none() {
            let mut builder = Indexer::builder(SEARCH_MODEL).quiet(true);
            for pattern in EXCLUDED {
                builder = builder.exclude(pattern);
            }
            self.indexer = Some(builder.build().await?);
        }
        let indexer = self.indexer.as_ref().expect("built above");
        std::fs::create_dir_all(&root)?;
        let index_str = index.to_string_lossy().into_owned();
        let folder_str = folder.to_string_lossy().into_owned();
        let existed = index.exists();
        let stats = match indexer.sync(&index_str, &[folder_str.as_str()]).await {
            Ok(stats) => stats,
            // An index this version cannot update, such as one from another
            // model, is rebuilt.
            Err(_) if existed => {
                std::fs::remove_dir_all(&index).context("removing the outdated index")?;
                indexer.sync(&index_str, &[folder_str.as_str()]).await?
            }
            Err(e) => return Err(e.into()),
        };
        std::fs::write(&stamp_file, stamp)?;

        let note = if !existed {
            format!("Indexed {} ({} files)", folder.display(), stats.files_added)
        } else {
            let changed = stats.files_added + stats.files_updated + stats.files_removed;
            if changed == 0 {
                return Ok((index, None));
            }
            format!(
                "Updated the index of {}: {} new, {} changed, {} removed",
                folder.display(),
                stats.files_added,
                stats.files_updated,
                stats.files_removed
            )
        };
        Ok((index, Some(note)))
    }

    async fn search_images(&mut self, args: &Value) -> Result<String> {
        let folder = PathBuf::from(string(args, "path")?);
        let folder = folder
            .canonicalize()
            .with_context(|| format!("cannot open {}", folder.display()))?;
        if !folder.is_dir() {
            bail!("{} is not a folder", folder.display());
        }
        let query = string(args, "query")?;
        let top_k = args
            .get("top_k")
            .and_then(Value::as_u64)
            .unwrap_or(5)
            .clamp(1, 50) as usize;

        if self.images.is_none() {
            let dir = ensure_model_downloaded(IMAGE_MODEL, None, DownloadPolicy::IfMissing, true)
                .await
                .context("downloading CLIP")?;
            self.images = Some(ImageIndex::load(&dir).context("loading CLIP")?);
        }
        let images = self.images.as_mut().expect("loaded above");

        // Vectors are cached per folder like search_folder's indexes, and
        // recomputed when the folder's files change.
        let root = kjarni::registry::cache_dir().join("mcp-image-indexes");
        let saved = root.join(format!(
            "{:016x}.json",
            fnv1a(folder.as_os_str().as_encoded_bytes())
        ));
        let stamp_file = saved.with_extension("stamp");
        let stamp = fingerprint(&folder, IMAGE_MODEL.cli_name());
        let current = std::fs::read_to_string(&stamp_file).ok();

        let mut text = String::new();
        if saved.exists() && current.as_deref() == Some(stamp.as_str()) {
            images.load_entries(&saved)?;
        } else {
            images.clear();
            // Seconds per hundred photos on the CPU: keep it off the runtime's
            // other threads, as transcribe does.
            let report = tokio::task::block_in_place(|| images.add_directory(&folder))?;
            std::fs::create_dir_all(&root)?;
            images.save(&saved)?;
            std::fs::write(&stamp_file, stamp)?;
            text.push_str(&format!(
                "(Indexed {} photos in {} for this search.",
                report.added,
                folder.display()
            ));
            if report.skipped > 0 {
                text.push_str(&format!(" {} could not be read.", report.skipped));
            }
            let unsupported: usize = report.unsupported.values().sum();
            if unsupported > 0 {
                let kinds: Vec<String> = report
                    .unsupported
                    .iter()
                    .map(|(ext, n)| format!("{n} .{ext}"))
                    .collect();
                text.push_str(&format!(
                    " Skipped, format not supported: {}.",
                    kinds.join(", ")
                ));
            }
            text.push_str(")\n\n");
        }

        let hits = images.search(query, top_k)?;
        if hits.is_empty() {
            text.push_str("No JPEG or PNG photos in this folder.");
        }
        for (i, hit) in hits.iter().enumerate() {
            text.push_str(&format!(
                "{}. {}  (score {:.3})\n",
                i + 1,
                hit.path.display(),
                hit.score
            ));
        }
        Ok(text.trim_end().to_string())
    }

    async fn transcribe(&mut self, args: &Value) -> Result<String> {
        let path = PathBuf::from(string(args, "path")?);
        if !path.is_file() {
            bail!("{} is not a file", path.display());
        }
        if self.transcriber.is_none() {
            self.transcriber = Some(
                Transcriber::builder(TRANSCRIBE_MODEL)
                    .quiet()
                    .build()
                    .await?,
            );
        }
        let transcriber = self.transcriber.as_ref().expect("built above");
        // Minutes of work on the CPU: run it where it will not stall the
        // runtime's other threads.
        let result = tokio::task::block_in_place(|| transcriber.transcribe_file(&path))?;

        let mut text = format!(
            "Language: {}. Duration: {:.0} s.\n\n",
            result.language, result.duration_secs
        );
        for s in &result.segments {
            text.push_str(&format!("[{}] {}\n", timestamp(s.start), s.text.trim()));
        }
        if result.segments.is_empty() {
            text.push_str(result.text.trim());
        }
        Ok(text.trim_end().to_string())
    }

    async fn classify(&mut self, args: &Value) -> Result<String> {
        let text = string(args, "text")?;
        let model = optional_string(args, "model")
            .unwrap_or(CLASSIFY_MODEL)
            .to_string();
        if !self.classifiers.contains_key(&model) {
            let classifier = Classifier::builder(model.clone())
                .quiet(true)
                .build()
                .await?;
            self.classifiers.insert(model.clone(), classifier);
        }
        let result = self.classifiers[&model].classify(text).await?;
        let scores: Vec<String> = result
            .all_scores
            .iter()
            .map(|(label, score)| format!("{label}: {:.3}", score))
            .collect();
        Ok(format!(
            "{} ({:.3})\nAll: {}",
            result.label,
            result.score,
            scores.join(", ")
        ))
    }

    async fn rerank(&mut self, args: &Value) -> Result<String> {
        let query = string(args, "query")?;
        let documents: Vec<String> = args
            .get("documents")
            .and_then(Value::as_array)
            .ok_or_else(|| anyhow!("documents must be an array of strings"))?
            .iter()
            .map(|d| {
                d.as_str()
                    .map(str::to_string)
                    .ok_or_else(|| anyhow!("documents must be strings"))
            })
            .collect::<Result<_>>()?;
        if documents.is_empty() {
            bail!("documents is empty");
        }
        if self.reranker.is_none() {
            self.reranker = Some(Reranker::builder(RERANK_MODEL).quiet(true).build().await?);
        }
        let refs: Vec<&str> = documents.iter().map(String::as_str).collect();
        let ranked = self
            .reranker
            .as_ref()
            .expect("built above")
            .rerank(query, &refs)
            .await?;
        let lines: Vec<String> = ranked
            .iter()
            .enumerate()
            .map(|(rank, r)| {
                format!(
                    "{}. [{}] relevance {:.3}: {}",
                    rank + 1,
                    r.index,
                    r.probability(),
                    clip(&documents[r.index], 200)
                )
            })
            .collect();
        Ok(lines.join("\n"))
    }

    async fn similarity(&mut self, args: &Value) -> Result<String> {
        let a = string(args, "a")?;
        let b = string(args, "b")?;
        if self.embedder.is_none() {
            self.embedder = Some(Embedder::builder(SEARCH_MODEL).quiet(true).build().await?);
        }
        let score = self
            .embedder
            .as_ref()
            .expect("built above")
            .similarity(a, b)
            .await?;
        Ok(format!("{score:.4}"))
    }
}

fn initialize(params: &Value) -> Value {
    let requested = params
        .get("protocolVersion")
        .and_then(Value::as_str)
        .unwrap_or_default();
    let version = PROTOCOL_VERSIONS
        .iter()
        .find(|v| **v == requested)
        .unwrap_or(&PROTOCOL_VERSIONS[0]);
    json!({
        "protocolVersion": version,
        "capabilities": { "tools": { "listChanged": false } },
        "serverInfo": { "name": "kjarni", "title": "Kjarni", "version": env!("CARGO_PKG_VERSION") },
        "instructions": INSTRUCTIONS,
    })
}

fn tools() -> Value {
    json!([
        {
            "name": "search_folder",
            "title": "Search a folder by meaning",
            "description": "Find the passages in a folder of documents or code (txt, md, source code, json, yaml, html, ...) that best match a query, by meaning as well as by keyword. Runs locally. The first search of a folder indexes it, which takes seconds to minutes depending on its size; later searches reuse the index until files change. Build output, dependencies and hidden folders are skipped.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "path": { "type": "string", "description": "Absolute path of the folder to search, subfolders included." },
                    "query": { "type": "string", "description": "What to find, in natural language or keywords." },
                    "mode": { "type": "string", "enum": ["hybrid", "semantic", "keyword"], "description": "hybrid (default) combines meaning and keywords; semantic is meaning only; keyword is BM25 only." },
                    "top_k": { "type": "integer", "minimum": 1, "maximum": 50, "description": "How many passages to return. Default 5." },
                    "rerank": { "type": "boolean", "description": "Reorder results with a cross-encoder for better precision. Slower. Default false." }
                },
                "required": ["path", "query"]
            },
            "annotations": { "readOnlyHint": true, "openWorldHint": false }
        },
        {
            "name": "search_images",
            "title": "Find photos by description",
            "description": "Find the photos in a folder that best match a description, such as \"a dog on a beach\" or \"receipt from a restaurant\", with CLIP, locally. Photos are never uploaded. JPEG and PNG, subfolders included; iPhone HEIC photos are not read. The first search of a folder embeds every photo, about 20 ms each on a desktop CPU; later searches reuse that until files change. Scores are only meaningful as a ranking.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "path": { "type": "string", "description": "Absolute path of the folder of photos." },
                    "query": { "type": "string", "description": "What the photo shows, in natural language." },
                    "top_k": { "type": "integer", "minimum": 1, "maximum": 50, "description": "How many photos to return. Default 5." }
                },
                "required": ["path", "query"]
            },
            "annotations": { "readOnlyHint": true, "openWorldHint": false }
        },
        {
            "name": "transcribe",
            "title": "Transcribe audio or video",
            "description": "Speech to text with Whisper, locally. Detects the language. Returns timestamped segments. Takes roughly a tenth of the recording's length on a desktop CPU.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "path": { "type": "string", "description": "Absolute path of a wav, mp3, flac or ogg file." }
                },
                "required": ["path"]
            },
            "annotations": { "readOnlyHint": true, "openWorldHint": false }
        },
        {
            "name": "classify",
            "title": "Classify text",
            "description": "Sentiment, emotion or toxicity of a text, locally.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "text": { "type": "string" },
                    "model": { "type": "string", "enum": ["distilbert-sentiment", "roberta-sentiment", "roberta-emotions", "distilroberta-emotion", "toxic-bert", "bert-sentiment-multilingual"], "description": "Default distilbert-sentiment (positive/negative)." }
                },
                "required": ["text"]
            },
            "annotations": { "readOnlyHint": true, "openWorldHint": false }
        },
        {
            "name": "rerank",
            "title": "Rank passages by relevance",
            "description": "Order candidate passages by how well each answers a query, with a cross-encoder. Returns each passage's original index and a relevance from 0 to 1.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "query": { "type": "string" },
                    "documents": { "type": "array", "items": { "type": "string" }, "minItems": 1 }
                },
                "required": ["query", "documents"]
            },
            "annotations": { "readOnlyHint": true, "openWorldHint": false }
        },
        {
            "name": "similarity",
            "title": "Compare two texts",
            "description": "Semantic similarity of two texts as a cosine between -1 and 1; above about 0.6 usually means the same topic.",
            "inputSchema": {
                "type": "object",
                "properties": { "a": { "type": "string" }, "b": { "type": "string" } },
                "required": ["a", "b"]
            },
            "annotations": { "readOnlyHint": true, "openWorldHint": false }
        }
    ])
}

fn error_response(id: Value, code: i64, message: &str) -> Value {
    json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
}

fn string<'a>(args: &'a Value, key: &str) -> Result<&'a str> {
    optional_string(args, key).ok_or_else(|| anyhow!("missing argument: {key}"))
}

fn optional_string<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
    args.get(key)
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
}

/// What says a folder has changed since it was indexed: how many files it
/// has outside the excluded and hidden folders, their total size, and the
/// newest modification time.
fn fingerprint(folder: &Path, model: &str) -> String {
    let (mut files, mut bytes, mut newest) = (0u64, 0u64, 0u128);
    let walker = walkdir::WalkDir::new(folder).into_iter().filter_entry(|e| {
        e.depth() == 0 || {
            let name = e.file_name().to_string_lossy();
            !name.starts_with('.') && !EXCLUDED.iter().any(|p| wildcard(p, &name))
        }
    });
    for entry in walker.filter_map(|e| e.ok()) {
        if let Ok(meta) = entry.metadata()
            && meta.is_file()
        {
            files += 1;
            bytes += meta.len();
            let mtime = meta
                .modified()
                .ok()
                .and_then(|t| t.duration_since(UNIX_EPOCH).ok());
            newest = newest.max(mtime.map_or(0, |d| d.as_nanos()));
        }
    }
    format!("{model} {files} {bytes} {newest}")
}

/// `*` matches any run of characters, as in the indexer's own exclusions.
fn wildcard(pattern: &str, name: &str) -> bool {
    match pattern.split_once('*') {
        None => pattern == name,
        Some((head, tail)) => {
            name.len() >= head.len() + tail.len() && name.starts_with(head) && name.ends_with(tail)
        }
    }
}

/// A stable hash, so the same folder maps to the same index across runs.
fn fnv1a(bytes: &[u8]) -> u64 {
    bytes.iter().fold(0xcbf29ce484222325, |h, &b| {
        (h ^ b as u64).wrapping_mul(0x100000001b3)
    })
}

fn timestamp(secs: f32) -> String {
    let s = secs.max(0.0) as u64;
    format!("{:02}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
}

fn clip(text: &str, max_chars: usize) -> String {
    if text.chars().count() <= max_chars {
        return text.to_string();
    }
    let cut: String = text.chars().take(max_chars).collect();
    format!("{}…", cut.trim_end())
}

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

    async fn ask(server: &mut Server, message: Value) -> Value {
        server
            .handle(&message)
            .await
            .expect("a request gets a response")
    }

    #[tokio::test]
    async fn speaks_the_protocol_handshake() {
        let mut server = Server::default();
        let init = ask(
            &mut server,
            json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"t","version":"1"}}}),
        )
        .await;
        assert_eq!(init["result"]["protocolVersion"], "2025-03-26");
        assert_eq!(init["result"]["serverInfo"]["name"], "kjarni");
        assert!(init["result"]["capabilities"]["tools"].is_object());

        // An unknown version gets the newest one this server speaks.
        let init = ask(&mut server, json!({"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"1999-01-01"}})).await;
        assert_eq!(init["result"]["protocolVersion"], PROTOCOL_VERSIONS[0]);

        // Notifications get no answer; ping gets an empty one.
        assert!(
            server
                .handle(&json!({"jsonrpc":"2.0","method":"notifications/initialized"}))
                .await
                .is_none()
        );
        assert_eq!(
            ask(
                &mut server,
                json!({"jsonrpc":"2.0","id":"p","method":"ping"})
            )
            .await["result"],
            json!({})
        );

        let unknown = ask(
            &mut server,
            json!({"jsonrpc":"2.0","id":3,"method":"resources/list"}),
        )
        .await;
        assert_eq!(unknown["error"]["code"], -32601);
    }

    #[tokio::test]
    async fn lists_tools_with_schemas() {
        let mut server = Server::default();
        let list = ask(
            &mut server,
            json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}),
        )
        .await;
        let tools = list["result"]["tools"].as_array().unwrap();
        let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
        assert_eq!(
            names,
            [
                "search_folder",
                "search_images",
                "transcribe",
                "classify",
                "rerank",
                "similarity"
            ]
        );
        for tool in tools {
            assert_eq!(tool["inputSchema"]["type"], "object", "{}", tool["name"]);
            assert!(tool["description"].as_str().unwrap().len() > 20);
        }
    }

    /// Bad arguments are the agent's to fix, so they come back as a tool
    /// result it can read, not as a protocol error.
    #[tokio::test]
    async fn tool_errors_are_results_the_agent_can_read() {
        let mut server = Server::default();
        let r = ask(&mut server, json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_folder","arguments":{"query":"x"}}})).await;
        assert_eq!(r["result"]["isError"], true);
        assert!(
            r["result"]["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("missing argument: path")
        );

        let r = ask(
            &mut server,
            json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"nope"}}),
        )
        .await;
        assert_eq!(r["result"]["isError"], true);
    }

    /// A second search after files change updates the index rather than
    /// rebuilding it, and finds what was written since.
    #[tokio::test(flavor = "multi_thread")]
    async fn search_folder_follows_edits_to_the_folder() {
        let dir = tempfile::tempdir().unwrap();
        let notes = dir.path().canonicalize().unwrap();
        std::fs::write(
            notes.join("boat.md"),
            "The ferry leaves the harbour at nine.",
        )
        .unwrap();
        std::fs::write(notes.join("bread.md"), "Knead the dough and let it rise.").unwrap();
        let mut server = Server::default();
        let search = |q: &str| json!({ "path": notes, "query": q, "top_k": 1 });

        let first = server
            .search_folder(&search("when does the ferry go"))
            .await
            .unwrap();
        assert!(first.starts_with("(Indexed "), "{first}");
        assert!(first.contains("boat.md"), "{first}");

        let unchanged = server.search_folder(&search("baking")).await.unwrap();
        assert!(unchanged.starts_with("1. "), "{unchanged}");

        std::fs::write(
            notes.join("bread.md"),
            "Rye bread needs a sourdough starter.",
        )
        .unwrap();
        std::fs::write(notes.join("bike.md"), "Pump the bicycle tyres every week.").unwrap();
        let updated = server
            .search_folder(&search("sourdough starter"))
            .await
            .unwrap();
        assert!(updated.contains("1 new, 1 changed, 0 removed"), "{updated}");
        assert!(
            updated.contains("bread.md") && updated.contains("Rye bread"),
            "{updated}"
        );

        std::fs::remove_file(notes.join("boat.md")).unwrap();
        let removed = server
            .search_folder(&search("ferry harbour"))
            .await
            .unwrap();
        assert!(removed.contains("0 new, 0 changed, 1 removed"), "{removed}");
        assert!(!removed.contains("boat.md"), "{removed}");
    }

    /// Four test photos, one subject each. Each description must put its own
    /// photo first, and a second search reuses the saved vectors.
    #[tokio::test(flavor = "multi_thread")]
    async fn search_images_finds_photos_by_description() {
        let photos = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/clip/photos");
        let photos = photos.canonicalize().unwrap();
        let mut server = Server::default();
        for (query, expected) in [
            ("a red car", "red_car.png"),
            ("snow on a mountain", "snowy_mountain.png"),
            ("a sunny beach", "beach_holiday.png"),
            ("trees in a forest", "deep_forest.png"),
        ] {
            let text = server
                .search_images(&json!({ "path": photos, "query": query, "top_k": 1 }))
                .await
                .unwrap();
            let first = text.lines().last().unwrap();
            assert!(
                first.starts_with("1. ") && first.contains(expected),
                "{query}: {text}"
            );
        }
        let again = server
            .search_images(&json!({ "path": photos, "query": "a red car" }))
            .await
            .unwrap();
        assert!(!again.contains("Indexed"), "{again}");
        assert_eq!(again.lines().count(), 4, "{again}");
    }

    #[test]
    fn fingerprint_follows_the_files_that_would_be_indexed() {
        let dir = tempfile::tempdir().unwrap();
        let d = dir.path();
        std::fs::write(d.join("a.md"), "one").unwrap();
        let before = fingerprint(d, SEARCH_MODEL);
        // Excluded and hidden folders do not count.
        std::fs::create_dir_all(d.join("target/debug")).unwrap();
        std::fs::write(d.join("target/debug/x.rs"), "generated").unwrap();
        std::fs::create_dir_all(d.join(".git")).unwrap();
        std::fs::write(d.join(".git/HEAD"), "ref").unwrap();
        assert_eq!(fingerprint(d, SEARCH_MODEL), before);
        // A new real file does.
        std::fs::write(d.join("b.md"), "two").unwrap();
        assert_ne!(fingerprint(d, SEARCH_MODEL), before);
    }

    #[test]
    fn helpers() {
        assert!(wildcard("*.min.js", "app.min.js") && !wildcard("*.min.js", "app.js"));
        assert!(wildcard("target", "target") && !wildcard("target", "targets"));
        assert_eq!(timestamp(3725.5), "01:02:05");
        assert_eq!(clip("abcdef", 3), "abc…");
        assert_eq!(fnv1a(b"same"), fnv1a(b"same"));
    }
}