agentroot-mcp 0.1.0

Model Context Protocol server for agentroot - AI assistant integration
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
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
//! MCP tool definitions and handlers

use crate::protocol::*;
use agentroot_core::{Database, SearchOptions};
use anyhow::Result;
use serde_json::Value;

pub fn search_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "search".to_string(),
        description: "BM25 full-text search across your knowledge base".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query (keywords or phrases)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum results (default: 20)",
                    "default": 20
                },
                "minScore": {
                    "type": "number",
                    "description": "Minimum relevance score 0-1 (default: 0)",
                    "default": 0
                },
                "collection": {
                    "type": "string",
                    "description": "Filter by collection name"
                },
                "provider": {
                    "type": "string",
                    "description": "Filter by provider type (file, github, url, etc.)"
                },
                "category": {
                    "type": "string",
                    "description": "Filter by document category (tutorial, reference, code, config, etc.)"
                },
                "difficulty": {
                    "type": "string",
                    "description": "Filter by difficulty level (beginner, intermediate, advanced)"
                },
                "concept": {
                    "type": "string",
                    "description": "Filter by concept/topic"
                }
            },
            "required": ["query"]
        }),
    }
}

pub fn vsearch_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "vsearch".to_string(),
        description: "Vector similarity search using embeddings".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query (natural language)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum results (default: 20)",
                    "default": 20
                },
                "minScore": {
                    "type": "number",
                    "description": "Minimum similarity score 0-1 (default: 0.3)",
                    "default": 0.3
                },
                "collection": {
                    "type": "string",
                    "description": "Filter by collection name"
                },
                "provider": {
                    "type": "string",
                    "description": "Filter by provider type (file, github, url, etc.)"
                },
                "category": {
                    "type": "string",
                    "description": "Filter by document category (tutorial, reference, code, config, etc.)"
                },
                "difficulty": {
                    "type": "string",
                    "description": "Filter by difficulty level (beginner, intermediate, advanced)"
                },
                "concept": {
                    "type": "string",
                    "description": "Filter by concept/topic"
                }
            },
            "required": ["query"]
        }),
    }
}

pub fn query_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "query".to_string(),
        description: "Hybrid search with BM25, vectors, and reranking (best quality)".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum results (default: 20)",
                    "default": 20
                },
                "collection": {
                    "type": "string",
                    "description": "Filter by collection name"
                },
                "provider": {
                    "type": "string",
                    "description": "Filter by provider type (file, github, url, etc.)"
                },
                "category": {
                    "type": "string",
                    "description": "Filter by document category (tutorial, reference, code, config, etc.)"
                },
                "difficulty": {
                    "type": "string",
                    "description": "Filter by difficulty level (beginner, intermediate, advanced)"
                },
                "concept": {
                    "type": "string",
                    "description": "Filter by concept/topic"
                }
            },
            "required": ["query"]
        }),
    }
}

pub fn smart_search_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "smart_search".to_string(),
        description: "Intelligent natural language search with automatic query understanding and filtering. Understands temporal filters like 'last hour', metadata filters like 'by Alice', and automatically falls back to BM25 if models are unavailable.".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Natural language search query (e.g., 'files edited last hour', 'rust tutorials by Alice')"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum results (default: 20)",
                    "default": 20
                },
                "minScore": {
                    "type": "number",
                    "description": "Minimum relevance score 0-1 (default: 0)",
                    "default": 0
                },
                "collection": {
                    "type": "string",
                    "description": "Filter by collection name"
                }
            },
            "required": ["query"]
        }),
    }
}

pub fn get_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "get".to_string(),
        description: "Get a document by path, docid, or virtual path".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "file": {
                    "type": "string",
                    "description": "File path, docid (#abc123), or agentroot:// URI"
                },
                "fromLine": {
                    "type": "integer",
                    "description": "Start from line number"
                },
                "maxLines": {
                    "type": "integer",
                    "description": "Maximum lines to return"
                },
                "lineNumbers": {
                    "type": "boolean",
                    "description": "Include line numbers",
                    "default": false
                }
            },
            "required": ["file"]
        }),
    }
}

pub fn multi_get_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "multi_get".to_string(),
        description: "Get multiple documents by glob pattern or comma-separated list".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Glob pattern or comma-separated list of paths/docids"
                },
                "maxLines": {
                    "type": "integer",
                    "description": "Maximum lines per file"
                },
                "maxBytes": {
                    "type": "integer",
                    "description": "Skip files larger than this (default: 10240)",
                    "default": 10240
                },
                "lineNumbers": {
                    "type": "boolean",
                    "description": "Include line numbers",
                    "default": false
                }
            },
            "required": ["pattern"]
        }),
    }
}

pub fn status_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "status".to_string(),
        description: "Show index status and collection information".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {}
        }),
    }
}

pub fn collection_add_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "collection_add".to_string(),
        description: "Add a new collection to index".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Collection name"
                },
                "path": {
                    "type": "string",
                    "description": "Path to local directory or URL"
                },
                "pattern": {
                    "type": "string",
                    "description": "Glob pattern for files (default: **/*.md)",
                    "default": "**/*.md"
                },
                "provider": {
                    "type": "string",
                    "description": "Provider type: file, github, url (default: file)",
                    "default": "file"
                },
                "config": {
                    "type": "string",
                    "description": "Provider-specific JSON configuration"
                }
            },
            "required": ["name", "path"]
        }),
    }
}

pub fn collection_remove_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "collection_remove".to_string(),
        description: "Remove a collection and its documents".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Collection name to remove"
                }
            },
            "required": ["name"]
        }),
    }
}

pub fn collection_update_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "collection_update".to_string(),
        description: "Reindex a collection (scan for new/changed documents)".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Collection name to update"
                }
            },
            "required": ["name"]
        }),
    }
}

pub async fn handle_search(db: &Database, args: Value) -> Result<ToolResult> {
    let query = args
        .get("query")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing query"))?;

    let options = SearchOptions {
        limit: args.get("limit").and_then(|v| v.as_u64()).unwrap_or(20) as usize,
        min_score: args.get("minScore").and_then(|v| v.as_f64()).unwrap_or(0.0),
        collection: args
            .get("collection")
            .and_then(|v| v.as_str())
            .map(String::from),
        provider: args
            .get("provider")
            .and_then(|v| v.as_str())
            .map(String::from),
        full_content: false,
    };

    let mut results = db.search_fts(query, &options)?;

    // Apply metadata filters
    let category_filter = args.get("category").and_then(|v| v.as_str());
    let difficulty_filter = args.get("difficulty").and_then(|v| v.as_str());
    let concept_filter = args.get("concept").and_then(|v| v.as_str());

    if category_filter.is_some() || difficulty_filter.is_some() || concept_filter.is_some() {
        results.retain(|r| {
            let matches_category = category_filter.map_or(true, |cat| {
                r.llm_category
                    .as_ref()
                    .map_or(false, |c| c.to_lowercase().contains(&cat.to_lowercase()))
            });
            let matches_difficulty = difficulty_filter.map_or(true, |diff| {
                r.llm_difficulty
                    .as_ref()
                    .map_or(false, |d| d.to_lowercase() == diff.to_lowercase())
            });
            let matches_concept = concept_filter.map_or(true, |concept| {
                r.llm_keywords.as_ref().map_or(false, |kws| {
                    kws.iter()
                        .any(|kw| kw.to_lowercase().contains(&concept.to_lowercase()))
                })
            });
            matches_category && matches_difficulty && matches_concept
        });
    }

    let summary = format!("Found {} results for \"{}\"", results.len(), query);
    let structured: Vec<Value> = results
        .iter()
        .map(|r| {
            let mut result_json = serde_json::json!({
                "docid": format!("#{}", r.docid),
                "file": r.display_path,
                "title": r.title,
                "score": (r.score * 100.0).round() / 100.0
            });

            // Include LLM metadata if available
            if let Some(summary) = &r.llm_summary {
                result_json["summary"] = Value::String(summary.clone());
            }
            if let Some(category) = &r.llm_category {
                result_json["category"] = Value::String(category.clone());
            }
            if let Some(difficulty) = &r.llm_difficulty {
                result_json["difficulty"] = Value::String(difficulty.clone());
            }
            if let Some(keywords) = &r.llm_keywords {
                result_json["keywords"] = serde_json::to_value(keywords).unwrap();
            }

            // Include user metadata if available
            if let Some(user_meta) = &r.user_metadata {
                if let Ok(json_str) = user_meta.to_json() {
                    if let Ok(parsed) = serde_json::from_str::<Value>(&json_str) {
                        result_json["userMetadata"] = parsed;
                    }
                }
            }

            result_json
        })
        .collect();

    Ok(ToolResult {
        content: vec![Content::Text { text: summary }],
        structured_content: Some(serde_json::json!({ "results": structured })),
        is_error: None,
    })
}

pub async fn handle_vsearch(db: &Database, args: Value) -> Result<ToolResult> {
    if !db.has_vector_index() {
        return Ok(ToolResult {
            content: vec![Content::Text {
                text: "Vector index not found. Run 'agentroot embed' first.".to_string(),
            }],
            structured_content: None,
            is_error: Some(true),
        });
    }

    let query = args
        .get("query")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing query"))?;

    let options = SearchOptions {
        limit: args.get("limit").and_then(|v| v.as_u64()).unwrap_or(20) as usize,
        min_score: args.get("minScore").and_then(|v| v.as_f64()).unwrap_or(0.3),
        collection: args
            .get("collection")
            .and_then(|v| v.as_str())
            .map(String::from),
        provider: args
            .get("provider")
            .and_then(|v| v.as_str())
            .map(String::from),
        full_content: false,
    };

    // Try HTTP embedder first, fallback to local
    let embedder: Box<dyn agentroot_core::Embedder> = if let Ok(http) =
        agentroot_core::HttpEmbedder::from_env()
    {
        Box::new(http)
    } else if let Ok(local) = agentroot_core::LlamaEmbedder::from_default() {
        Box::new(local)
    } else {
        return Ok(ToolResult {
                content: vec![Content::Text {
                    text: "Could not load embedding model. Configure HTTP service via AGENTROOT_EMBEDDING_URL \
                          or download a local model. See: https://github.com/epappas/agentroot#embedding-models"
                        .to_string(),
                }],
                structured_content: None,
                is_error: Some(true),
            });
    };

    let mut results = db.search_vec(query, embedder.as_ref(), &options).await?;

    // Apply metadata filters
    let category_filter = args.get("category").and_then(|v| v.as_str());
    let difficulty_filter = args.get("difficulty").and_then(|v| v.as_str());
    let concept_filter = args.get("concept").and_then(|v| v.as_str());

    if category_filter.is_some() || difficulty_filter.is_some() || concept_filter.is_some() {
        results.retain(|r| {
            let matches_category = category_filter.map_or(true, |cat| {
                r.llm_category
                    .as_ref()
                    .map_or(false, |c| c.to_lowercase().contains(&cat.to_lowercase()))
            });
            let matches_difficulty = difficulty_filter.map_or(true, |diff| {
                r.llm_difficulty
                    .as_ref()
                    .map_or(false, |d| d.to_lowercase() == diff.to_lowercase())
            });
            let matches_concept = concept_filter.map_or(true, |concept| {
                r.llm_keywords.as_ref().map_or(false, |kws| {
                    kws.iter()
                        .any(|kw| kw.to_lowercase().contains(&concept.to_lowercase()))
                })
            });
            matches_category && matches_difficulty && matches_concept
        });
    }

    let summary = format!("Found {} results for \"{}\"", results.len(), query);
    let structured: Vec<Value> = results
        .iter()
        .map(|r| {
            let mut result_json = serde_json::json!({
                "docid": format!("#{}", r.docid),
                "file": r.display_path,
                "title": r.title,
                "score": (r.score * 100.0).round() / 100.0
            });

            // Include LLM metadata if available
            if let Some(summary) = &r.llm_summary {
                result_json["summary"] = Value::String(summary.clone());
            }
            if let Some(category) = &r.llm_category {
                result_json["category"] = Value::String(category.clone());
            }
            if let Some(difficulty) = &r.llm_difficulty {
                result_json["difficulty"] = Value::String(difficulty.clone());
            }
            if let Some(keywords) = &r.llm_keywords {
                result_json["keywords"] = serde_json::to_value(keywords).unwrap();
            }

            // Include user metadata if available
            if let Some(user_meta) = &r.user_metadata {
                if let Ok(json_str) = user_meta.to_json() {
                    if let Ok(parsed) = serde_json::from_str::<Value>(&json_str) {
                        result_json["userMetadata"] = parsed;
                    }
                }
            }

            result_json
        })
        .collect();

    Ok(ToolResult {
        content: vec![Content::Text { text: summary }],
        structured_content: Some(serde_json::json!({ "results": structured })),
        is_error: None,
    })
}

pub async fn handle_query(db: &Database, args: Value) -> Result<ToolResult> {
    if !db.has_vector_index() {
        return handle_search(db, args).await;
    }

    let query = args
        .get("query")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing query"))?;

    let options = SearchOptions {
        limit: args.get("limit").and_then(|v| v.as_u64()).unwrap_or(20) as usize,
        min_score: 0.0,
        collection: args
            .get("collection")
            .and_then(|v| v.as_str())
            .map(String::from),
        provider: args
            .get("provider")
            .and_then(|v| v.as_str())
            .map(String::from),
        full_content: false,
    };

    // Try HTTP embedder first, fallback to local, then BM25-only
    let embedder: Box<dyn agentroot_core::Embedder> =
        if let Ok(http) = agentroot_core::HttpEmbedder::from_env() {
            Box::new(http)
        } else if let Ok(local) = agentroot_core::LlamaEmbedder::from_default() {
            Box::new(local)
        } else {
            // No embedder available, fall back to BM25-only search
            return handle_search(db, args).await;
        };

    let bm25_results = db.search_fts(query, &options)?;
    let vec_results = db.search_vec(query, embedder.as_ref(), &options).await?;

    let fused_results = agentroot_core::search::rrf_fusion(&bm25_results, &vec_results);

    let mut final_results: Vec<_> = fused_results
        .into_iter()
        .filter(|r| r.score >= options.min_score)
        .take(options.limit)
        .collect();

    // Apply metadata filters
    let category_filter = args.get("category").and_then(|v| v.as_str());
    let difficulty_filter = args.get("difficulty").and_then(|v| v.as_str());
    let concept_filter = args.get("concept").and_then(|v| v.as_str());

    if category_filter.is_some() || difficulty_filter.is_some() || concept_filter.is_some() {
        final_results.retain(|r| {
            let matches_category = category_filter.map_or(true, |cat| {
                r.llm_category
                    .as_ref()
                    .map_or(false, |c| c.to_lowercase().contains(&cat.to_lowercase()))
            });
            let matches_difficulty = difficulty_filter.map_or(true, |diff| {
                r.llm_difficulty
                    .as_ref()
                    .map_or(false, |d| d.to_lowercase() == diff.to_lowercase())
            });
            let matches_concept = concept_filter.map_or(true, |concept| {
                r.llm_keywords.as_ref().map_or(false, |kws| {
                    kws.iter()
                        .any(|kw| kw.to_lowercase().contains(&concept.to_lowercase()))
                })
            });
            matches_category && matches_difficulty && matches_concept
        });
    }

    let summary = format!(
        "Found {} results for \"{}\" (hybrid search)",
        final_results.len(),
        query
    );
    let structured: Vec<Value> = final_results
        .iter()
        .map(|r| {
            let mut result_json = serde_json::json!({
                "docid": format!("#{}", r.docid),
                "file": r.display_path,
                "title": r.title,
                "score": (r.score * 100.0).round() / 100.0
            });

            // Include LLM metadata if available
            if let Some(summary) = &r.llm_summary {
                result_json["summary"] = Value::String(summary.clone());
            }
            if let Some(category) = &r.llm_category {
                result_json["category"] = Value::String(category.clone());
            }
            if let Some(difficulty) = &r.llm_difficulty {
                result_json["difficulty"] = Value::String(difficulty.clone());
            }
            if let Some(keywords) = &r.llm_keywords {
                result_json["keywords"] = serde_json::to_value(keywords).unwrap();
            }

            // Include user metadata if available
            if let Some(user_meta) = &r.user_metadata {
                if let Ok(json_str) = user_meta.to_json() {
                    if let Ok(parsed) = serde_json::from_str::<Value>(&json_str) {
                        result_json["userMetadata"] = parsed;
                    }
                }
            }

            result_json
        })
        .collect();

    Ok(ToolResult {
        content: vec![Content::Text { text: summary }],
        structured_content: Some(serde_json::json!({ "results": structured })),
        is_error: None,
    })
}

pub async fn handle_smart_search(db: &Database, args: Value) -> Result<ToolResult> {
    let query = args
        .get("query")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing query"))?;

    let options = SearchOptions {
        limit: args.get("limit").and_then(|v| v.as_u64()).unwrap_or(20) as usize,
        min_score: args.get("minScore").and_then(|v| v.as_f64()).unwrap_or(0.0),
        collection: args
            .get("collection")
            .and_then(|v| v.as_str())
            .map(String::from),
        provider: None,
        full_content: false,
    };

    // Use smart_search which handles parsing and fallbacks
    let results = agentroot_core::smart_search(db, query, &options).await?;

    let summary = format!(
        "Found {} results for \"{}\" (smart search)",
        results.len(),
        query
    );
    let structured: Vec<Value> = results
        .iter()
        .map(|r| {
            let mut result_json = serde_json::json!({
                "docid": format!("#{}", r.docid),
                "file": r.display_path,
                "title": r.title,
                "score": (r.score * 100.0).round() / 100.0
            });

            // Include LLM metadata if available
            if let Some(summary) = &r.llm_summary {
                result_json["summary"] = Value::String(summary.clone());
            }
            if let Some(category) = &r.llm_category {
                result_json["category"] = Value::String(category.clone());
            }
            if let Some(difficulty) = &r.llm_difficulty {
                result_json["difficulty"] = Value::String(difficulty.clone());
            }
            if let Some(keywords) = &r.llm_keywords {
                result_json["keywords"] = serde_json::to_value(keywords).unwrap();
            }

            // Include user metadata if available
            if let Some(user_meta) = &r.user_metadata {
                if let Ok(json_str) = user_meta.to_json() {
                    if let Ok(parsed) = serde_json::from_str::<Value>(&json_str) {
                        result_json["userMetadata"] = parsed;
                    }
                }
            }

            result_json
        })
        .collect();

    Ok(ToolResult {
        content: vec![Content::Text { text: summary }],
        structured_content: Some(serde_json::json!({ "results": structured })),
        is_error: None,
    })
}

pub async fn handle_get(db: &Database, args: Value) -> Result<ToolResult> {
    let file = args
        .get("file")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing file"))?;

    let doc = db
        .find_by_docid(file)?
        .ok_or_else(|| anyhow::anyhow!("Document not found: {}", file))?;

    let body = doc.body.unwrap_or_default();

    Ok(ToolResult {
        content: vec![Content::Resource {
            resource: ResourceContent {
                uri: doc.filepath,
                name: doc.display_path,
                title: Some(doc.title),
                mime_type: "text/markdown".to_string(),
                text: body,
            },
        }],
        structured_content: None,
        is_error: None,
    })
}

pub async fn handle_multi_get(db: &Database, args: Value) -> Result<ToolResult> {
    let pattern = args
        .get("pattern")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing pattern"))?;

    let docs = db.fuzzy_find_documents(pattern, 10)?;

    let contents: Vec<Content> = docs
        .into_iter()
        .map(|doc| Content::Resource {
            resource: ResourceContent {
                uri: doc.filepath,
                name: doc.display_path,
                title: Some(doc.title),
                mime_type: "text/markdown".to_string(),
                text: doc.body.unwrap_or_default(),
            },
        })
        .collect();

    Ok(ToolResult {
        content: contents,
        structured_content: None,
        is_error: None,
    })
}

pub async fn handle_status(db: &Database) -> Result<ToolResult> {
    let collections = db.list_collections()?;
    let total_docs: usize = collections.iter().map(|c| c.document_count).sum();
    let needs_embedding = db.count_hashes_needing_embedding()?;
    let has_vector = db.has_vector_index();

    let mut provider_stats: std::collections::HashMap<String, (usize, usize)> =
        std::collections::HashMap::new();
    for coll in &collections {
        let entry = provider_stats
            .entry(coll.provider_type.clone())
            .or_insert((0, 0));
        entry.0 += 1;
        entry.1 += coll.document_count;
    }

    let mut provider_summary = String::new();
    for (provider, (coll_count, doc_count)) in &provider_stats {
        provider_summary.push_str(&format!(
            "\n  - {}: {} collections, {} documents",
            provider, coll_count, doc_count
        ));
    }

    let summary = format!(
        "Index: {} documents across {} collections\n\
         Embeddings: {}\n\
         Vector index: {}\n\
         \n\
         Providers:{}",
        total_docs,
        collections.len(),
        if needs_embedding > 0 {
            format!("{} documents need embedding", needs_embedding)
        } else {
            "Up to date".to_string()
        },
        if has_vector {
            "Available"
        } else {
            "Not created"
        },
        provider_summary
    );

    let provider_stats_json: Vec<_> = provider_stats
        .iter()
        .map(|(provider, (coll_count, doc_count))| {
            serde_json::json!({
                "provider": provider,
                "collections": coll_count,
                "documents": doc_count
            })
        })
        .collect();

    let structured = serde_json::json!({
        "totalDocuments": total_docs,
        "needsEmbedding": needs_embedding,
        "hasVectorIndex": has_vector,
        "providers": provider_stats_json,
        "collections": collections.iter().map(|c| serde_json::json!({
            "name": c.name,
            "path": c.path,
            "pattern": c.pattern,
            "provider": c.provider_type,
            "documents": c.document_count
        })).collect::<Vec<_>>()
    });

    Ok(ToolResult {
        content: vec![Content::Text { text: summary }],
        structured_content: Some(structured),
        is_error: None,
    })
}

pub async fn handle_collection_add(db: &Database, args: Value) -> Result<ToolResult> {
    let name = args
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing collection name"))?;

    let path = args
        .get("path")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing path"))?;

    let pattern = args
        .get("pattern")
        .and_then(|v| v.as_str())
        .unwrap_or("**/*.md");

    let provider = args
        .get("provider")
        .and_then(|v| v.as_str())
        .unwrap_or("file");

    let config = args.get("config").and_then(|v| v.as_str());

    db.add_collection(name, path, pattern, provider, config)?;

    let summary = format!(
        "Added collection '{}' (provider: {}, path: {})",
        name, provider, path
    );

    Ok(ToolResult {
        content: vec![Content::Text { text: summary }],
        structured_content: Some(serde_json::json!({
            "name": name,
            "path": path,
            "pattern": pattern,
            "provider": provider
        })),
        is_error: None,
    })
}

pub async fn handle_collection_remove(db: &Database, args: Value) -> Result<ToolResult> {
    let name = args
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing collection name"))?;

    let removed = db.remove_collection(name)?;

    if removed {
        Ok(ToolResult {
            content: vec![Content::Text {
                text: format!("Removed collection '{}'", name),
            }],
            structured_content: Some(serde_json::json!({
                "name": name,
                "removed": true
            })),
            is_error: None,
        })
    } else {
        Ok(ToolResult {
            content: vec![Content::Text {
                text: format!("Collection '{}' not found", name),
            }],
            structured_content: Some(serde_json::json!({
                "name": name,
                "removed": false
            })),
            is_error: Some(true),
        })
    }
}

pub async fn handle_collection_update(db: &Database, args: Value) -> Result<ToolResult> {
    let name = args
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing collection name"))?;

    let updated = db.reindex_collection(name).await?;

    let summary = format!("Updated collection '{}': {} files changed", name, updated);

    Ok(ToolResult {
        content: vec![Content::Text { text: summary }],
        structured_content: Some(serde_json::json!({
            "name": name,
            "filesUpdated": updated
        })),
        is_error: None,
    })
}

pub fn metadata_add_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "metadata_add".to_string(),
        description: "Add custom user metadata to a document".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "docid": {
                    "type": "string",
                    "description": "Document ID (#abc123) or path"
                },
                "metadata": {
                    "type": "object",
                    "description": "Metadata fields as key-value pairs. Values can be strings, numbers, booleans, or arrays",
                    "additionalProperties": true
                }
            },
            "required": ["docid", "metadata"]
        }),
    }
}

pub fn metadata_get_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "metadata_get".to_string(),
        description: "Get custom user metadata from a document".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "docid": {
                    "type": "string",
                    "description": "Document ID (#abc123) or path"
                }
            },
            "required": ["docid"]
        }),
    }
}

pub fn metadata_query_tool_definition() -> ToolDefinition {
    ToolDefinition {
        name: "metadata_query".to_string(),
        description: "Query documents by custom user metadata".to_string(),
        input_schema: serde_json::json!({
            "type": "object",
            "properties": {
                "field": {
                    "type": "string",
                    "description": "Metadata field name to query"
                },
                "operator": {
                    "type": "string",
                    "enum": ["eq", "contains", "gt", "lt", "has", "exists"],
                    "description": "Comparison operator"
                },
                "value": {
                    "type": "string",
                    "description": "Value to compare against (not needed for 'exists' operator)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum results (default: 20)",
                    "default": 20
                }
            },
            "required": ["field", "operator"]
        }),
    }
}

pub async fn handle_metadata_add(db: &Database, args: Value) -> Result<ToolResult> {
    use agentroot_core::MetadataBuilder;

    let docid = args
        .get("docid")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing docid"))?;

    let metadata_obj = args
        .get("metadata")
        .and_then(|v| v.as_object())
        .ok_or_else(|| anyhow::anyhow!("Missing or invalid metadata"))?;

    let mut builder = MetadataBuilder::new();

    for (key, value) in metadata_obj {
        match value {
            Value::String(s) => {
                builder = builder.text(key, s.clone());
            }
            Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    builder = builder.integer(key, i);
                } else if let Some(f) = n.as_f64() {
                    builder = builder.float(key, f);
                }
            }
            Value::Bool(b) => {
                builder = builder.boolean(key, *b);
            }
            Value::Array(arr) => {
                let tags: Vec<String> = arr
                    .iter()
                    .filter_map(|v| v.as_str())
                    .map(|s| s.to_string())
                    .collect();
                builder = builder.tags(key, tags);
            }
            _ => {}
        }
    }

    let metadata = builder.build();
    db.add_metadata(docid, &metadata)?;

    let summary = format!("Added metadata to document: {}", docid);

    Ok(ToolResult {
        content: vec![Content::Text { text: summary }],
        structured_content: Some(serde_json::json!({
            "docid": docid,
            "added": true
        })),
        is_error: None,
    })
}

pub async fn handle_metadata_get(db: &Database, args: Value) -> Result<ToolResult> {
    let docid = args
        .get("docid")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing docid"))?;

    match db.get_metadata(docid)? {
        Some(metadata) => {
            let json = metadata.to_json()?;
            let parsed: serde_json::Value = serde_json::from_str(&json)?;

            Ok(ToolResult {
                content: vec![Content::Text {
                    text: format!("User metadata for {}: {}", docid, json),
                }],
                structured_content: Some(serde_json::json!({
                    "docid": docid,
                    "metadata": parsed
                })),
                is_error: None,
            })
        }
        None => Ok(ToolResult {
            content: vec![Content::Text {
                text: format!("No user metadata found for document: {}", docid),
            }],
            structured_content: Some(serde_json::json!({
                "docid": docid,
                "metadata": null
            })),
            is_error: None,
        }),
    }
}

pub async fn handle_metadata_query(db: &Database, args: Value) -> Result<ToolResult> {
    use agentroot_core::MetadataFilter;

    let field = args
        .get("field")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing field"))?
        .to_string();

    let operator = args
        .get("operator")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing operator"))?;

    let limit = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(20) as usize;

    let filter = match operator {
        "exists" => MetadataFilter::Exists(field),
        _ => {
            let value = args
                .get("value")
                .and_then(|v| v.as_str())
                .ok_or_else(|| anyhow::anyhow!("Missing value for operator"))?;

            match operator {
                "eq" => MetadataFilter::TextEq(field, value.to_string()),
                "contains" => MetadataFilter::TextContains(field, value.to_string()),
                "gt" => {
                    if let Ok(num) = value.parse::<i64>() {
                        MetadataFilter::IntegerGt(field, num)
                    } else if let Ok(num) = value.parse::<f64>() {
                        MetadataFilter::FloatGt(field, num)
                    } else {
                        return Err(anyhow::anyhow!("Invalid numeric value for gt"));
                    }
                }
                "lt" => {
                    if let Ok(num) = value.parse::<i64>() {
                        MetadataFilter::IntegerLt(field, num)
                    } else if let Ok(num) = value.parse::<f64>() {
                        MetadataFilter::FloatLt(field, num)
                    } else {
                        return Err(anyhow::anyhow!("Invalid numeric value for lt"));
                    }
                }
                "has" => MetadataFilter::TagsContain(field, value.to_string()),
                _ => return Err(anyhow::anyhow!("Invalid operator")),
            }
        }
    };

    let docids = db.find_by_metadata(&filter, limit)?;

    let summary = if docids.is_empty() {
        "No documents found matching filter".to_string()
    } else {
        format!("Found {} document(s) matching filter", docids.len())
    };

    Ok(ToolResult {
        content: vec![Content::Text {
            text: format!("{}\n{}", summary, docids.join("\n")),
        }],
        structured_content: Some(serde_json::json!({
            "count": docids.len(),
            "documents": docids
        })),
        is_error: None,
    })
}