docterm 0.2.0

A TUI-first documentation browser for Dash/Zeal docsets, optimized for the terminal.
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
pub mod token_auth_provider;

use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    sync::Arc,
};

use async_trait::async_trait;
use rust_mcp_sdk::{
    McpServer,
    macros::{JsonSchema, mcp_tool},
    mcp_server::ServerHandler,
    schema::{
        CallToolRequestParams, CallToolResult, ListToolsResult, PaginatedRequestParams, RpcError,
        TextContent, schema_utils::CallToolError,
    },
    tool_box,
};
use serde::{Deserialize, Serialize};

use crate::{search, storage};

// ── Tool: search_docs ─────────────────────────────────────────────────────────

#[mcp_tool(
    name = "search_docs",
    description = "Fuzzy-search documentation entries across all indexed docsets. Returns matching entries with their IDs, types, and file paths. Use the returned `id` with `read_doc` to retrieve the full content.",
    read_only_hint = true,
    idempotent_hint = true,
    destructive_hint = false,
    open_world_hint = false
)]
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct SearchDocsTool {
    /// The fuzzy-search query string.
    pub query: String,
    /// Optional docset filter. Format: `<name>` or `<name>:<version>` (e.g. `"Rust"` or `"Rust:1.75.0"`).
    pub docset: Option<String>,
    /// Maximum number of results to return. Defaults to 20.
    pub limit: Option<u64>,
}

// ── Tool: read_doc ────────────────────────────────────────────────────────────

#[mcp_tool(
    name = "read_doc",
    description = "Return the Markdown content for a documentation entry by its numeric ID (as returned by search_docs).",
    read_only_hint = true,
    idempotent_hint = true,
    destructive_hint = false,
    open_world_hint = false
)]
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ReadDocTool {
    /// The entry ID as returned by search_docs.
    pub entry_id: i64,
}

// ── Tool: list_docsets ────────────────────────────────────────────────────────

#[mcp_tool(
    name = "list_docsets",
    description = "List docsets with their installed versions. Returns a JSON array of objects with `name`, `installed_versions`, and `available_versions` fields. Filter by name (case-insensitive substring) or set `installed_only` to exclude names with no local installation.",
    read_only_hint = true,
    idempotent_hint = true,
    destructive_hint = false,
    open_world_hint = false
)]
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ListDocsetsTool {
    /// Optional case-insensitive substring filter on the docset name.
    pub name: Option<String>,
    /// If true, only return docsets that have at least one installed version.
    pub installed_only: Option<bool>,
}

// ── Tool box ──────────────────────────────────────────────────────────────────

tool_box!(DocdbTools, [SearchDocsTool, ReadDocTool, ListDocsetsTool]);

// ── Handler ───────────────────────────────────────────────────────────────────

pub struct DocdbHandler {
    db_path: PathBuf,
    compression_level: i32,
}

impl DocdbHandler {
    pub fn new(db_path: PathBuf, compression_level: i32) -> Self {
        Self {
            db_path,
            compression_level,
        }
    }
}

#[async_trait]
impl ServerHandler for DocdbHandler {
    async fn handle_list_tools_request(
        &self,
        _params: Option<PaginatedRequestParams>,
        _runtime: Arc<dyn McpServer>,
    ) -> Result<ListToolsResult, RpcError> {
        Ok(ListToolsResult {
            meta: None,
            next_cursor: None,
            tools: DocdbTools::tools(),
        })
    }

    async fn handle_call_tool_request(
        &self,
        params: CallToolRequestParams,
        _runtime: Arc<dyn McpServer>,
    ) -> Result<CallToolResult, CallToolError> {
        let tool: DocdbTools = DocdbTools::try_from(params).map_err(CallToolError::new)?;
        let db_path = self.db_path.clone();
        let compression_level = self.compression_level;

        tokio::task::spawn_blocking(move || -> Result<CallToolResult, String> {
            match tool {
                DocdbTools::SearchDocsTool(t) => t
                    .execute(&db_path, compression_level)
                    .map_err(|e| e.to_string()),
                DocdbTools::ReadDocTool(t) => t
                    .execute(&db_path, compression_level)
                    .map_err(|e| e.to_string()),
                DocdbTools::ListDocsetsTool(t) => t
                    .execute(&db_path, compression_level)
                    .map_err(|e| e.to_string()),
            }
        })
        .await
        .map_err(|e| CallToolError::from_message(e.to_string()))?
        .map_err(CallToolError::from_message)
    }
}

// ── Tool implementations ──────────────────────────────────────────────────────

impl SearchDocsTool {
    fn execute(
        &self,
        db_path: &Path,
        compression_level: i32,
    ) -> Result<CallToolResult, CallToolError> {
        if !db_path.exists() {
            return Err(CallToolError::from_message(
                "No database found. Run `docterm download <name>` to add a docset.".to_string(),
            ));
        }

        let storage = storage::Storage::open(db_path, compression_level)
            .map_err(|e| CallToolError::from_message(e.to_string()))?;

        let (entries, scope) = if let Some(spec) = &self.docset {
            let (name, version) = parse_docset_spec(spec);
            let docset = storage
                .find_docset_by_name(name, version)
                .map_err(|e| CallToolError::from_message(e.to_string()))?
                .ok_or_else(|| {
                    CallToolError::from_message(format!("Docset '{spec}' not found."))
                })?;
            let label = format!(
                "{} {}",
                docset.name,
                docset.version.as_deref().unwrap_or("(latest)")
            );
            let entries = storage
                .list_entries_for_docset(docset.id)
                .map_err(|e| CallToolError::from_message(e.to_string()))?;
            (entries, label)
        } else {
            let entries = storage
                .list_all_entries()
                .map_err(|e| CallToolError::from_message(e.to_string()))?;
            (entries, "all docsets".to_string())
        };

        if entries.is_empty() {
            return Ok(CallToolResult::text_content(vec![TextContent::from(
                "No entries indexed. Run `docterm download <name>` to add a docset.".to_string(),
            )]));
        }

        let limit = self.limit.unwrap_or(20) as usize;
        let mut searcher = search::Searcher::new(entries);
        let results = searcher.search(&self.query, limit);

        if results.is_empty() {
            return Ok(CallToolResult::text_content(vec![TextContent::from(
                format!("No results for '{}' in {}.", self.query, scope),
            )]));
        }

        let docset_names: HashMap<i64, String> = storage
            .list_docsets()
            .map_err(|e| CallToolError::from_message(e.to_string()))?
            .into_iter()
            .map(|d| (d.id, d.name))
            .collect();

        let mut output = format!(
            "Results for '{}' in {} ({} found):\n\n",
            self.query,
            scope,
            results.len()
        );
        for r in &results {
            let docset_name = docset_names
                .get(&r.entry.docset_id)
                .map(String::as_str)
                .unwrap_or("?");
            output.push_str(&format!(
                "- id={} [{}] {} ({}) — {}\n",
                r.entry.id, docset_name, r.entry.name, r.entry.entry_type, r.entry.path
            ));
        }

        Ok(CallToolResult::text_content(vec![TextContent::from(
            output,
        )]))
    }
}

impl ReadDocTool {
    fn execute(
        &self,
        db_path: &Path,
        compression_level: i32,
    ) -> Result<CallToolResult, CallToolError> {
        if !db_path.exists() {
            return Err(CallToolError::from_message(
                "No database found. Run `docterm download <name>` to add a docset.".to_string(),
            ));
        }

        let storage = storage::Storage::open(db_path, compression_level)
            .map_err(|e| CallToolError::from_message(e.to_string()))?;

        let entry = storage.get_entry(self.entry_id).map_err(|e| {
            CallToolError::from_message(format!("Entry {} not found: {e}", self.entry_id))
        })?;

        let dict = storage
            .get_docset_dictionary(entry.docset_id)
            .ok()
            .flatten();

        let page = storage
            .get_page_content_dict(self.entry_id, dict.as_deref())
            .map_err(|e| {
                CallToolError::from_message(format!("Failed to read doc {}: {e}", self.entry_id))
            })?;

        Ok(CallToolResult::text_content(vec![TextContent::from(
            page.markdown,
        )]))
    }
}

impl ListDocsetsTool {
    fn execute(
        &self,
        db_path: &Path,
        compression_level: i32,
    ) -> Result<CallToolResult, CallToolError> {
        if !db_path.exists() {
            return Err(CallToolError::from_message(
                "No database found. Run `docterm download <name>` to add a docset.".to_string(),
            ));
        }

        let storage = storage::Storage::open(db_path, compression_level)
            .map_err(|e| CallToolError::from_message(e.to_string()))?;

        let all_docsets = storage
            .list_docsets()
            .map_err(|e| CallToolError::from_message(e.to_string()))?;

        // Group installed versions by lowercase name, preserving insertion order
        // and the original display name (first occurrence wins).
        let mut seen: Vec<String> = Vec::new();
        let mut display_names: HashMap<String, String> = HashMap::new();
        let mut by_name: HashMap<String, Vec<String>> = HashMap::new();
        for d in all_docsets {
            let key = d.name.to_lowercase();
            if !by_name.contains_key(&key) {
                seen.push(key.clone());
                display_names.insert(key.clone(), d.name.clone());
            }
            if let Some(v) = d.version {
                by_name.entry(key).or_default().push(v);
            } else {
                by_name.entry(key).or_default();
            }
        }

        // Apply filters.
        let name_filter = self.name.as_deref().map(str::to_lowercase);
        let installed_only = self.installed_only.unwrap_or(false);

        let results: Vec<DocsetInfo> = seen
            .into_iter()
            .filter(|key| {
                if let Some(ref f) = name_filter {
                    key.contains(f.as_str())
                } else {
                    true
                }
            })
            .filter_map(|key| {
                let installed_versions = by_name.remove(&key).unwrap_or_default();
                if installed_only && installed_versions.is_empty() {
                    return None;
                }
                let name = display_names.remove(&key).unwrap_or(key);
                Some(DocsetInfo {
                    name,
                    installed_versions,
                    available_versions: vec![],
                })
            })
            .collect();

        let json = serde_json::to_string_pretty(&results)
            .map_err(|e| CallToolError::from_message(e.to_string()))?;

        Ok(CallToolResult::text_content(vec![TextContent::from(json)]))
    }
}

// ── Response shape ────────────────────────────────────────────────────────────

#[derive(Debug, Serialize)]
struct DocsetInfo {
    name: String,
    installed_versions: Vec<String>,
    available_versions: Vec<String>,
}

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Split `"name:version"` into `("name", Some("version"))`, or
/// `"name"` into `("name", None)`.
fn parse_docset_spec(spec: &str) -> (&str, Option<&str>) {
    if let Some((name, version)) = spec.split_once(':') {
        (name, Some(version))
    } else {
        (spec, None)
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    // ── parse_docset_spec ─────────────────────────────────────────────────────

    #[test]
    fn parse_spec_without_version() {
        let (name, version) = parse_docset_spec("Rust");
        assert_eq!(name, "Rust");
        assert!(version.is_none());
    }

    #[test]
    fn parse_spec_with_version() {
        let (name, version) = parse_docset_spec("Rust:1.75.0");
        assert_eq!(name, "Rust");
        assert_eq!(version, Some("1.75.0"));
    }

    // ── SearchDocsTool ────────────────────────────────────────────────────────

    #[test]
    fn search_tool_missing_db_returns_error() {
        let tool = SearchDocsTool {
            query: "Vec".into(),
            docset: None,
            limit: None,
        };
        let result = tool.execute(&PathBuf::from("/nonexistent/library.db"), 3);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("No database found"));
    }

    #[test]
    fn search_tool_empty_db_returns_informative_message() {
        let dir = TempDir::new().unwrap();
        let db_path = dir.path().join("library.db");
        let _storage = storage::Storage::open(&db_path, 3).unwrap();

        let tool = SearchDocsTool {
            query: "Vec".into(),
            docset: None,
            limit: None,
        };
        let result = tool.execute(&db_path, 3).unwrap();
        let text = extract_text(&result);
        assert!(text.contains("No entries indexed"));
    }

    #[test]
    fn search_tool_unknown_docset_returns_error() {
        let dir = TempDir::new().unwrap();
        let db_path = dir.path().join("library.db");
        let _storage = storage::Storage::open(&db_path, 3).unwrap();

        let tool = SearchDocsTool {
            query: "Vec".into(),
            docset: Some("NoSuchDocset".into()),
            limit: None,
        };
        let result = tool.execute(&db_path, 3);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn search_tool_finds_entries() {
        let dir = TempDir::new().unwrap();
        let db_path = dir.path().join("library.db");
        let storage = storage::Storage::open(&db_path, 3).unwrap();
        let docset_id = storage.insert_docset("Rust", Some("1.0"), None).unwrap();
        storage
            .insert_entry(docset_id, "Vec", "Struct", "std/vec/struct.Vec.html")
            .unwrap();
        storage
            .insert_entry(
                docset_id,
                "HashMap",
                "Struct",
                "std/collections/struct.HashMap.html",
            )
            .unwrap();

        let tool = SearchDocsTool {
            query: "Vec".into(),
            docset: None,
            limit: Some(10),
        };
        let result = tool.execute(&db_path, 3).unwrap();
        let text = extract_text(&result);
        assert!(text.contains("Vec"));
        assert!(text.contains("id="));
    }

    // ── ReadDocTool ───────────────────────────────────────────────────────────

    #[test]
    fn read_doc_missing_db_returns_error() {
        let tool = ReadDocTool { entry_id: 1 };
        let result = tool.execute(&PathBuf::from("/nonexistent/library.db"), 3);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("No database found")
        );
    }

    #[test]
    fn read_doc_unknown_entry_returns_error() {
        let dir = TempDir::new().unwrap();
        let db_path = dir.path().join("library.db");
        let _storage = storage::Storage::open(&db_path, 3).unwrap();

        let tool = ReadDocTool { entry_id: 9999 };
        let result = tool.execute(&db_path, 3);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("9999"));
    }

    #[test]
    fn read_doc_returns_markdown_content() {
        let dir = TempDir::new().unwrap();
        let db_path = dir.path().join("library.db");
        let storage = storage::Storage::open(&db_path, 3).unwrap();
        let docset_id = storage.insert_docset("Rust", Some("1.0"), None).unwrap();
        let entry_id = storage
            .insert_entry(docset_id, "Vec", "Struct", "std/vec/struct.Vec.html")
            .unwrap();
        let markdown = "# Vec\n\nA growable array.";
        storage.insert_page_dict(entry_id, markdown, None).unwrap();

        let tool = ReadDocTool { entry_id };
        let result = tool.execute(&db_path, 3).unwrap();
        let text = extract_text(&result);
        assert_eq!(text, markdown);
    }

    // ── ListDocsetsTool ───────────────────────────────────────────────────────

    fn setup_db_with_docsets(dir: &TempDir) -> PathBuf {
        let db_path = dir.path().join("library.db");
        let storage = storage::Storage::open(&db_path, 3).unwrap();
        storage.insert_docset("Rust", Some("1.80.0"), None).unwrap();
        storage.insert_docset("Rust", Some("1.94.0"), None).unwrap();
        storage.insert_docset("Python", Some("3.12"), None).unwrap();
        storage.insert_docset("Go", None, None).unwrap();
        db_path
    }

    #[test]
    fn list_docsets_missing_db_returns_error() {
        let tool = ListDocsetsTool {
            name: None,
            installed_only: None,
        };
        let result = tool.execute(&PathBuf::from("/nonexistent/library.db"), 3);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("No database found")
        );
    }

    #[test]
    fn list_docsets_returns_all_names() {
        let dir = TempDir::new().unwrap();
        let db_path = setup_db_with_docsets(&dir);

        let tool = ListDocsetsTool {
            name: None,
            installed_only: None,
        };
        let result = tool.execute(&db_path, 3).unwrap();
        let text = extract_text(&result);
        let parsed: serde_json::Value = serde_json::from_str(&text).unwrap();
        let arr = parsed.as_array().unwrap();
        let names: Vec<&str> = arr.iter().map(|v| v["name"].as_str().unwrap()).collect();
        assert!(names.contains(&"Rust"));
        assert!(names.contains(&"Python"));
        assert!(names.contains(&"Go"));
    }

    #[test]
    fn list_docsets_version_present_in_installed_versions() {
        // The schema enforces name UNIQUE, so each docset name has exactly one
        // row and therefore at most one installed_version.
        let dir = TempDir::new().unwrap();
        let db_path = setup_db_with_docsets(&dir);

        let tool = ListDocsetsTool {
            name: Some("rust".into()),
            installed_only: None,
        };
        let result = tool.execute(&db_path, 3).unwrap();
        let text = extract_text(&result);
        let parsed: serde_json::Value = serde_json::from_str(&text).unwrap();
        let arr = parsed.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        let versions = arr[0]["installed_versions"].as_array().unwrap();
        // Only the first insert is kept (INSERT OR IGNORE); version is "1.80.0".
        assert_eq!(versions.len(), 1);
        assert_eq!(versions[0].as_str().unwrap(), "1.80.0");
    }

    #[test]
    fn list_docsets_name_filter_case_insensitive() {
        let dir = TempDir::new().unwrap();
        let db_path = setup_db_with_docsets(&dir);

        let tool = ListDocsetsTool {
            name: Some("PY".into()),
            installed_only: None,
        };
        let result = tool.execute(&db_path, 3).unwrap();
        let text = extract_text(&result);
        let parsed: serde_json::Value = serde_json::from_str(&text).unwrap();
        let arr = parsed.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["name"].as_str().unwrap(), "Python");
    }

    #[test]
    fn list_docsets_no_match_returns_empty_array() {
        let dir = TempDir::new().unwrap();
        let db_path = setup_db_with_docsets(&dir);

        let tool = ListDocsetsTool {
            name: Some("Haskell".into()),
            installed_only: None,
        };
        let result = tool.execute(&db_path, 3).unwrap();
        let text = extract_text(&result);
        let parsed: serde_json::Value = serde_json::from_str(&text).unwrap();
        assert_eq!(parsed.as_array().unwrap().len(), 0);
    }

    #[test]
    fn list_docsets_installed_only_excludes_empty() {
        let dir = TempDir::new().unwrap();
        // Insert a docset with no version.
        let db_path = dir.path().join("library.db");
        let storage = storage::Storage::open(&db_path, 3).unwrap();
        storage.insert_docset("Rust", Some("1.94"), None).unwrap();
        // Go has no version string — still "installed" (has a row).
        storage.insert_docset("Go", None, None).unwrap();

        let tool = ListDocsetsTool {
            name: None,
            installed_only: Some(true),
        };
        let result = tool.execute(&db_path, 3).unwrap();
        let text = extract_text(&result);
        let parsed: serde_json::Value = serde_json::from_str(&text).unwrap();
        // Both docsets have rows, but Go has no version string → installed_versions is empty.
        // installed_only=true filters those out.
        let arr = parsed.as_array().unwrap();
        let names: Vec<&str> = arr.iter().map(|v| v["name"].as_str().unwrap()).collect();
        assert!(names.contains(&"Rust"));
        assert!(!names.contains(&"Go"));
    }

    #[test]
    fn list_docsets_available_versions_always_empty() {
        let dir = TempDir::new().unwrap();
        let db_path = setup_db_with_docsets(&dir);

        let tool = ListDocsetsTool {
            name: None,
            installed_only: None,
        };
        let result = tool.execute(&db_path, 3).unwrap();
        let text = extract_text(&result);
        let parsed: serde_json::Value = serde_json::from_str(&text).unwrap();
        for entry in parsed.as_array().unwrap() {
            assert_eq!(entry["available_versions"].as_array().unwrap().len(), 0);
        }
    }

    // ── DocdbTools tool list ──────────────────────────────────────────────────

    #[test]
    fn tool_box_has_three_tools() {
        let tools = DocdbTools::tools();
        assert_eq!(tools.len(), 3);
        let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
        assert!(names.contains(&"search_docs"));
        assert!(names.contains(&"read_doc"));
        assert!(names.contains(&"list_docsets"));
    }

    // ── Helpers ───────────────────────────────────────────────────────────────

    fn extract_text(result: &CallToolResult) -> String {
        result
            .content
            .iter()
            .filter_map(|c| c.as_text_content().ok())
            .map(|t| t.text.as_str())
            .collect::<Vec<_>>()
            .join("")
    }
}