monothink 0.4.2

A totally non-agentic coding assistant
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
/*
* This file is part of monothink.
*
* monothink is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* monothink is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Wavething.
* If not, see <https://www.gnu.org/licenses/>.

*/

use rig::{
    message::ToolResultContent,
    tool::{Tool, ToolContext},
};
use rmcp::{
    RoleClient, ServiceExt,
    model::{
        CallToolRequestParams, ClientCapabilities, ClientInfo, Implementation, Tool as RmcpTool,
    },
    service::{ClientInitializeError, RunningService},
    transport::StreamableHttpClientTransport,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{
    collections::BTreeMap,
    fs::{self, read_to_string},
    io::ErrorKind,
    path::{Path, PathBuf},
};

use crate::{
    config::{self, McpTool, WebSearchProvider},
    llm::compactors::SharedObservations,
};

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub enum DirectoryEntryKind {
    File,
    Directory,
}

impl std::fmt::Display for DirectoryEntryKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DirectoryEntryKind::File => {
                write!(f, "File")
            }
            DirectoryEntryKind::Directory => {
                write!(f, "Directory")
            }
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
struct DirectoryEntry {
    path: String,
    kind: DirectoryEntryKind,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DirectoryListing {
    entries: Vec<DirectoryEntry>,
    total_entries: usize,
    truncated: bool,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
struct Location {
    path: PathBuf,
    line: usize,
    //column: u32,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
struct Range {
    path: PathBuf,
    start: usize,
    end: usize,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
struct SearchMatch {
    location: Location,
    preview: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SearchResults {
    total_entries: usize,
    returned_entries: usize,
    truncated: bool,
    entries: Vec<SearchMatch>,
    // @todo list entries that could not be accessed
    // failed_entries: Vec<String>
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FileContent {
    range: Range,
    content: String,
}

#[derive(Deserialize, Serialize)]
pub struct ListDirArgs {
    path: PathBuf,
    // recursive: Option<bool>,
    start: Option<usize>,
}

#[derive(Deserialize, Serialize)]
pub struct ListDir {
    base_dir: PathBuf,
    #[serde(default)]
    max_results: Option<usize>,
}

// @todo check access rights (i.e. calculated path must be below base_dir)
impl ListDir {
    pub fn new(base_dir: &Path, max_results: Option<usize>) -> Self {
        Self {
            base_dir: base_dir.to_path_buf(),
            max_results,
        }
    }
}
impl Tool for ListDir {
    const NAME: &'static str = "list_dir";

    type Error = ToolError;
    type Args = ListDirArgs;
    type Output = DirectoryListing;

    async fn call(
        &self,
        _context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        let path = allowed_canonical_path(&args.path, &self.base_dir)?;
        // list_dir(&path, args.recursive.unwrap_or(false))
        let mut result = list_dir(&path, false)?;
        // @todo clip long lists but preserve total entries (add actual entries as info)
        // @todo this is brickle, because it also includes permission denied errors, we should log the error and go on
        result.total_entries = result.entries.len();
        if let Some(max_results) = self.max_results
            && result.entries.len() > max_results
        {
            result.entries.truncate(max_results);
            result.truncated = true;
        }

        Ok(result)
    }

    fn description(&self) -> String {
        // "List the files and directory of the given directory (relative to project root) and optionally its subdirectories"
        //
        format!(
            "List the files and directories in the given directory (relative to project root), \
        returning {} entries. Use an empty string \"\" for the project root. \
        Results include both files and subdirectories with their types.",
            match self.max_results {
                Some(val) => format!("at most {}", val),
                None => "all".to_string(),
            }
        )
    }

    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the directory relative to project root directory. \
                     Use an empty string for the root directory."
                },
                "max_results": {
                    "type": "integer",
                    "description": "Optional, limit the number of entries to return to at most the given value."
                },
                // "start": {
                //     "type": "integer",
                //     "description": "Optional, zero-based index of the first result to return. \
                //     Use this to paginate through results if a previous call was truncated."
                // },
            },
            "required": ["path"]
        })
    }

    fn map_error(&self, error: Self::Error) -> rig::tool::ToolExecutionError {
        rig::tool::ToolExecutionError::from_error(error)
    }
}

#[derive(Deserialize, Serialize)]
pub struct ReadFileArgs {
    path: PathBuf,
    #[serde(default)]
    start: Option<usize>,
    #[serde(default)]
    end: Option<usize>,
}

#[derive(Deserialize, Serialize)]
pub struct ReadFile {
    base_dir: PathBuf,
}

impl ReadFile {
    pub fn new(base_dir: &Path) -> Self {
        Self {
            base_dir: base_dir.to_path_buf(),
        }
    }
}

// @todo check access rights (i.e. calculated path must be below base_dir)
impl Tool for ReadFile {
    const NAME: &'static str = "read_file";

    type Error = ToolError;
    type Args = ReadFileArgs;
    type Output = FileContent;

    async fn call(
        &self,
        _context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        let path = allowed_canonical_path(&args.path, &self.base_dir)?;

        if path.is_dir() {
            return Err(ToolError::NotAFile {
                path: args.path.to_string_lossy().to_string(),
                suggestion: "Use list_dir to explore this directory instead.".to_string(),
            });
        }

        let content: Vec<String> = fs::read_to_string(path)
            .map_err(|err| io_error_to_tool_error(err, &args.path))?
            .lines()
            .map(|line| line.to_string())
            .collect();

        let mut start = match args.start {
            Some(v) => v.saturating_sub(1),
            None => 0,
        };
        let mut end = match args.end {
            Some(v) => {
                if v > 0 {
                    v // we do not substract to convert from one-based to zero-based because the line shall be included which it isn't for slicing
                } else {
                    1 // LLMs like to provide 0 or -1 for end of file, we do not support -1 but can support 0
                }
            }
            None => content.len(),
        };
        if end > content.len() {
            end = content.len();
        }
        if start > end {
            start = end;
        };

        let extract = &content[start..end].join("\n");

        // @todo clip large files
        Ok(FileContent {
            range: Range {
                path: args.path,
                start: start + 1,
                end: end + 1,
            },
            content: extract.to_owned(),
        })
    }

    fn description(&self) -> String {
        "Read the content of a file, optionally specifying a line range. \
            Lines are 1-indexed and inclusive. \
            If no range is specified, the entire file is returned."
            .to_string()
    }

    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the file relative to project root directory"
                },
                "start": {
                    "type": "integer",
                    "description": "First line number to read (1-indexed, inclusive). \
                    If not provided, reads from the beginning of the file."
                },
                "end": {
                    "type": "integer",
                    "description": "Last line number to read (1-indexed, inclusive). \
                    If not provided, reads to the end of the file. \
                      If end exceeds the file length, reads until the end."
                }
            },
            "required": ["path"]
        })
    }

    fn map_error(&self, error: Self::Error) -> rig::tool::ToolExecutionError {
        rig::tool::ToolExecutionError::from_error(error)
    }
}

#[derive(Deserialize, Serialize)]
pub struct SearchTextArgs {
    path: PathBuf,
    text: String,
    #[serde(default)]
    start: Option<usize>,
}

#[derive(Deserialize, Serialize)]
pub struct SearchText {
    base_dir: PathBuf,
    max_results: usize,
}

impl SearchText {
    pub fn new(base_dir: &Path, max_results: usize) -> Self {
        Self {
            base_dir: base_dir.to_path_buf(),
            max_results,
        }
    }
}

impl Tool for SearchText {
    const NAME: &'static str = "search_text";

    type Error = ToolError;
    type Args = SearchTextArgs;
    type Output = SearchResults;

    async fn call(
        &self,
        _context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        let path = allowed_canonical_path(&args.path, &self.base_dir)?;
        let entries = list_dir(&path, true)?;
        let matches: Vec<SearchMatch> = entries
            .entries
            .iter()
            // filter files
            .filter_map(|e| match e.kind {
                DirectoryEntryKind::File => {
                    read_to_string(&e.path).ok().map(|v| (e.path.clone(), v))
                }
                DirectoryEntryKind::Directory => None,
            })
            // map to lines that contain the searched text
            .map(|(path, content)| {
                (
                    path,
                    content
                        .lines()
                        .enumerate()
                        .filter(|(_nr, line)| line.contains(&args.text))
                        .map(|(nr, line)| (nr, line.to_owned()))
                        .collect::<Vec<(usize, String)>>(),
                )
            })
            // filter files containing the match
            .filter(|(_path, content)| !content.is_empty())
            // map to search matches
            .flat_map(|(path, content)| {
                content
                    .iter()
                    .map(move |(nr, line)| SearchMatch {
                        location: Location {
                            path: PathBuf::from(path.clone()),
                            line: *nr,
                        },
                        preview: line.clone(),
                    })
                    .collect::<Vec<_>>()
            })
            .collect();

        // clip
        let start = args.start.unwrap_or_default();
        let requested_matches = &matches[start..];
        let final_matches = if requested_matches.len() > 100 {
            &requested_matches[..100]
        } else {
            requested_matches
        };
        Ok(SearchResults {
            total_entries: matches.len(),
            returned_entries: final_matches.len(),
            truncated: final_matches.len() != matches.len(),
            entries: final_matches.to_vec(),
        })
    }

    fn description(&self) -> String {
        format!(
            "Search for text in all files within the given directory and its subdirectories. \
      Returns matches with file paths, line numbers, and content previews. \
      The search is case-sensitive. Results are clipped at {} entries.",
            self.max_results
        )
    }

    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to the directory to search in, \
                    relative to project root directory. \
                    Use an empty string for the root directory. \
                    Search is recursive."
                },
                "text": {
                    "type": "string",
                    "description": "The exact text string to search for. \
                    The search is case-sensitive."
                },
                "start": {
                    "type": "integer",
                    "description": "Optional, zero-based index of the first result to return. \
                    Use this to paginate through results if a previous call was truncated."
                },
            },
            "required": ["path", "text"]
        })
    }

    fn map_error(&self, error: Self::Error) -> rig::tool::ToolExecutionError {
        rig::tool::ToolExecutionError::from_error(error)
    }
}

#[derive(Deserialize, Serialize)]
pub struct RetrieveObservationArgs {
    id: u64,
}

#[derive(Debug)]
pub struct RetrieveObservation {
    pub observations: SharedObservations,
}

impl RetrieveObservation {
    pub fn new(observations: SharedObservations) -> Self {
        Self { observations }
    }
}

impl Tool for RetrieveObservation {
    const NAME: &'static str = "retrieve_observation";

    type Error = ToolError;
    type Args = RetrieveObservationArgs;
    type Output = Vec<ToolResultContent>;

    async fn call(
        &self,
        _context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        self.observations
            .lock()
            .unwrap()
            .get(&args.id)
            .ok_or_else(|| ToolError::ResourceNotFound {
                resource_type: ResourceType::Observation,
                identifier: args.id.to_string(),
            })
            .cloned()
    }

    fn description(&self) -> String {
        "Retrieve the full content of a masked tool result from conversation history. \
     When conversation history is compacted to save context space, older tool results \
     are replaced with placeholders like '[Observation:3 - masked]'. \
     Use this tool when you need to see the full content of a masked result. \
     The number inside the brackets (e.g., 3 in '[Observation:3 - masked]') is the \
     id you should pass to this tool. Each tool result in the history is assigned a \
     unique observation number starting from 1."
            .to_string()
    }

    fn parameters(&self) -> serde_json::Value {
        let id_description = "The numeric identifier of the observation to retrieve. \
        When a tool result is masked in the conversation history, it appears as \
        '[Observation:N - masked]' where N is this identifier. For example, \
        if you see '[Observation:3 - masked]', pass 3 as this parameter. \
        Observation IDs start at 1 and increment sequentially.";

        json!({
            "type": "object",
            "properties": {
                "id": {
                    "type": "integer",
                    "description": id_description
                 },
            },
            "required": ["id"]
        })
    }

    fn map_error(&self, error: Self::Error) -> rig::tool::ToolExecutionError {
        rig::tool::ToolExecutionError::from_error(error)
    }
}

#[derive(Deserialize, Serialize)]
pub struct WebSearchArgs {
    query: String,
    #[serde(default = "web_search_max_results_default")]
    max_results: u64,
    // possible other parameters:
    // search_depth
    // start_date
    // end_date
    // exclude_domains
    // include_domains
    //
}

fn web_search_max_results_default() -> u64 {
    5
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WebSearchResult {
    url: String,
    title: String,
    content: String,
}

#[derive(Debug)]
pub struct WebSearch {
    tool: RmcpTool,
    service: RunningService<RoleClient, ClientInfo>,
    provider: WebSearchProvider,
}

impl WebSearch {
    // @todo take channel to report warning messages in case of errors
    pub async fn new(config: &config::WebSearch) -> Option<Self> {
        // @todo make it independent from tivaly (use provider)
        let tool = get_mcp_tools(&BTreeMap::from([(
            config.provider.display_string(),
            McpTool {
                url: config.url.clone(),
            },
        )]))
        .await;
        // @todo check success

        // @todo is there an easier way to consume the vector?
        if let Some((service, tools)) = tool.into_iter().next() {
            // @todo make it independent from tavily (use provider)
            // @todo validate schema (the parts we are interested in)
            //tool.with_input_schema()
            // tool.output_schema (if present)
            tools
                .iter()
                .find(|tool| tool.name == "tavily_search")
                .map(|tool| Self {
                    tool: tool.to_owned(),
                    service,
                    provider: config.provider,
                })
        } else {
            None
        }
    }
}

impl Tool for WebSearch {
    const NAME: &'static str = "web_search";

    type Error = ToolError;
    type Args = WebSearchArgs;
    type Output = Vec<WebSearchResult>; // url, title, content (from tavily as a vector in "result"

    async fn call(
        &self,
        _context: &mut ToolContext,
        args: Self::Args,
    ) -> Result<Self::Output, Self::Error> {
        let arguments = serde_json::to_value(&args)
            .unwrap()
            .as_object()
            .cloned()
            .unwrap();

        // @todo make independent of tavily
        let params = CallToolRequestParams::new("tavily_search").with_arguments(arguments);
        let results = self
            .service
            .call_tool(params)
            .await
            .map_err(|err| match err {
                rmcp::ServiceError::McpError(error_data) => ToolError::Mcp {
                    kind: "MCP".to_string(),
                    info: error_data.to_string(),
                },
                rmcp::ServiceError::TransportSend(dynamic_transport_error) => ToolError::Mcp {
                    kind: "Transport send".to_string(),
                    info: dynamic_transport_error.to_string(),
                },
                rmcp::ServiceError::TransportClosed => ToolError::Mcp {
                    kind: "Transport closed".to_string(),
                    info: String::new(),
                },
                rmcp::ServiceError::UnexpectedResponse => ToolError::Mcp {
                    kind: "Unexpected response".to_string(),
                    info: String::new(),
                },
                rmcp::ServiceError::Cancelled { reason } => ToolError::Mcp {
                    kind: "Cancelled".to_string(),
                    info: reason.unwrap_or_default(),
                },
                rmcp::ServiceError::Timeout { timeout } => ToolError::Mcp {
                    kind: "Cancelled".to_string(),
                    info: String::new(),
                },
                _ => ToolError::Mcp {
                    kind: "Unknown".to_string(),
                    info: String::new(),
                },
            })?;
        println!("{:?}", results);
        // results.content.iter().filter_map(|c| c.as_text())
        // map result
        Ok(Vec::new())
    }

    fn description(&self) -> String {
        "Search the internet for up-to-date information, recent events, live data, \
        or obscure facts not covered in your training data. \
        Use when the user asks for current news, real-time statuses, \
        or when you need to verify uncertain information. \
        Do not use for common knowledge or questions answerable with local tools."
            .to_string()
    }

    // could be extracted from schema but I don't like their description
    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "A concise, specific search query. Use keywords or short phrases. \
                    Avoid full sentences or overly broad terms for better results."
                },
                "max_results": {
                    "type": "integer",
                    "description": "Maximum number of results to return. Recommended: 3-5. \
                    Higher values increase latency and token usage but may improve coverage. \
                    Defaults to 5 if omitted.",
                    "default": 5
                },
            },
            "required": ["query"]
        })
    }

    fn map_error(&self, error: Self::Error) -> rig::tool::ToolExecutionError {
        rig::tool::ToolExecutionError::from_error(error)
    }
}

// path is absolute
fn list_dir(path: &Path, recursive: bool) -> Result<DirectoryListing, ToolError> {
    let mut result = DirectoryListing {
        entries: Vec::new(),
        total_entries: 0,
        truncated: false,
    };
    let mut backlog = vec![path.to_path_buf()];

    while let Some(dir) = backlog.pop() {
        if !dir.is_dir() {
            return Result::Err(ToolError::DirectoryEntryNotFound {
                path: path.to_string_lossy().to_string(),
                kind: DirectoryEntryKind::Directory,
                suggestion: "Provide a directory to the list_dir tool.".to_string(),
            });
        }

        let paths = match fs::read_dir(dir) {
            Ok(paths) => paths,
            Err(err) if err.kind() == ErrorKind::PermissionDenied => {
                // @todo Log warning and skip this directory
                continue;
            }
            Err(err) => return Err(io_error_to_tool_error(err, path)),
        };

        for entry in paths.flatten() {
            if entry.path().is_dir() {
                if recursive {
                    backlog.push(entry.path());
                }
                result.entries.push(DirectoryEntry {
                    path: entry.path().to_string_lossy().to_string(),
                    kind: DirectoryEntryKind::Directory,
                });
            } else {
                result.entries.push(DirectoryEntry {
                    path: entry.path().to_string_lossy().to_string(),
                    kind: DirectoryEntryKind::File,
                });
            }
        }
    }

    result.total_entries = result.entries.len();

    Ok(result)
}

fn allowed_canonical_path(path_string: &Path, base_dir: &Path) -> Result<PathBuf, ToolError> {
    // let path_string = if path_string.is_empty() {
    //     "."
    // } else {
    //     path_string
    // };

    let canonical_base = base_dir
        .canonicalize()
        .map_err(|err| io_error_to_tool_error(err, path_string))?;
    let path = base_dir
        .join(path_string)
        .canonicalize()
        .map_err(|err| io_error_to_tool_error(err, path_string))?;

    if path.starts_with(canonical_base) {
        Ok(path)
    } else {
        Err(ToolError::PathTraversal {
            requested: path_string.to_string_lossy().to_string(),
            base: base_dir.to_string_lossy().to_string(),
        })
    }
}

fn io_error_to_tool_error(err: std::io::Error, path: &Path) -> ToolError {
    let path_string = path.to_string_lossy().to_string();
    match err.kind() {
        ErrorKind::NotFound => ToolError::DirectoryEntryNotFound {
            path: path_string,
            kind: DirectoryEntryKind::File,
            suggestion: "Use list_dir tool to explore available files.".to_string(),
        },
        ErrorKind::PermissionDenied => ToolError::PermissionDenied { path: path_string },
        _ => ToolError::Io {
            path: Some(path_string),
            source: err,
        },
    }
}

#[derive(Debug)]
pub enum ToolError {
    /// File or directory does not exist
    DirectoryEntryNotFound {
        path: String,
        kind: DirectoryEntryKind,
        suggestion: String,
    },
    /// Invalid arguments provided to the tool
    InvalidArgs {
        argument: &'static str,
        reason: String,
    },
    /// Entry is not a File
    NotAFile { path: String, suggestion: String },
    /// Path is outside the allowed base directory
    PathTraversal { requested: String, base: String },
    /// Permission denied accessing path
    PermissionDenied { path: String },
    /// Resource not found (e.g., observation ID)
    ResourceNotFound {
        resource_type: ResourceType,
        identifier: String,
    },
    /// Other IO error
    Io {
        path: Option<String>,
        source: std::io::Error,
    },
    /// error when communicating with a MCP server
    Mcp { kind: String, info: String }, // @todo better values
}

impl std::fmt::Display for ToolError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ToolError::DirectoryEntryNotFound {
                path,
                kind,
                suggestion,
            } => {
                write!(f, "Error: {} '{}' not found. {}", kind, path, suggestion)
            }
            ToolError::InvalidArgs { argument, reason } => {
                write!(
                    f,
                    "Error: Invalid value for argument '{}': {}",
                    argument, reason
                )
            }
            ToolError::NotAFile { path, suggestion } => {
                write!(f, "Error: '{}' is not a file. {}", path, suggestion)
            }
            ToolError::PathTraversal { requested, base } => {
                write!(
                    f,
                    "Error: Path '{}' is outside the allowed directory '{}'. \
                     Only paths within the project root are accessible.",
                    requested, base
                )
            }
            ToolError::PermissionDenied { path } => {
                write!(
                    f,
                    "Error: Permission denied when accessing '{}'. \
                     This file/directory requires elevated permissions. \
                     You cannot access this resource. Continue with available data \
                     or ask the user to check permissions.",
                    path
                )
            }
            ToolError::ResourceNotFound {
                resource_type,
                identifier,
            } => {
                write!(
                    f,
                    "Error: {} with identifier '{}' not found. \
                     Check the conversation history for valid {} IDs.",
                    resource_type, identifier, resource_type
                )
            }
            ToolError::Io { path, source } => {
                if let Some(p) = path {
                    write!(f, "Error reading '{}': {}", p, source)
                } else {
                    write!(f, "Error: {}", source)
                }
            }
            ToolError::Mcp { kind, info } => {
                write!(f, "Error {} accessing MCP with info '{}'.", kind, info)
            }
        }
    }
}
impl std::error::Error for ToolError {}

#[derive(Debug, Clone)]
pub enum ResourceType {
    Observation,
}

impl std::fmt::Display for ResourceType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResourceType::Observation => {
                write!(f, "Observation")
            }
        }
    }
}

// @todo also take sender to send system messages
pub async fn get_mcp_tools(
    tools: &BTreeMap<String, config::McpTool>,
) -> Vec<(RunningService<RoleClient, ClientInfo>, Vec<RmcpTool>)> {
    let mut result = Vec::new();

    for (name, mcp_tool) in tools {
        // println!("Tool name: {}", name);
        // println!("Tool config: {}", mcp_tool.url);
        if let Ok((peer, tools)) = connect_and_fetch_tools(mcp_tool).await {
            result.push((peer, tools));
            // @todo send system message
        } else {
            // @todo send system message about failure
        }
    }

    result
}

async fn connect_and_fetch_tools(
    mcp_tool: &config::McpTool,
) -> Result<(RunningService<RoleClient, ClientInfo>, Vec<RmcpTool>), anyhow::Error> {
    let client = create_client(mcp_tool).await?;
    let tools = client.list_tools(Default::default()).await?.tools;
    Ok((client, tools))
}

async fn create_client(
    mcp_tool: &config::McpTool,
) -> Result<RunningService<RoleClient, ClientInfo>, ClientInitializeError> {
    let transport = StreamableHttpClientTransport::from_uri(mcp_tool.url.clone());
    let client_info_impl = Implementation::new(
        env!("CARGO_PKG_NAME").to_string(),
        env!("CARGO_PKG_VERSION").to_string(),
    );
    let client_info = ClientInfo::new(ClientCapabilities::default(), client_info_impl);

    client_info.serve(transport).await.inspect_err(|_e| {
        // @todo tracing::error!("client error: {e:?}");
    })
    // @note: This is for rmcp 3.x which rig does not yet support
    // it is left here because I expect rig to migrate soon
    // client_info.serve_with_lifecycle(
    //     transport,
    //     rmcp::ClientLifecycleMode::Auto {
    //         preferred_versions: vec![rmcp::model::ProtocolVersion::V_2026_07_28],
    //         legacy_version: Some(rmcp::model::ProtocolVersion::V_2025_11_25),
    //     },
    // )
    // .await
}

#[tokio::test]
async fn test_list_dir() {
    // fake test to just read the current dir
    let base_dir = std::env::current_dir().expect("Cannot get current directory");
    let ld = ListDir::new(&base_dir, Some(100));
    let result = ld
        .call(
            &mut ToolContext::default(),
            ListDirArgs {
                path: PathBuf::from(""),
                // recursive: Some(true),
                start: None,
            },
        )
        .await
        .unwrap();
    println!("Result: {:?}", result.total_entries);
}

#[tokio::test]
async fn test_read_file() {
    // fake test to just see the output
    // Should output the GPLv3 license header of main.rs
    let base_dir = std::env::current_dir().expect("Cannot get current directory");
    let ld = ReadFile::new(&base_dir);
    let result = ld
        .call(
            &mut ToolContext::default(),
            ReadFileArgs {
                path: PathBuf::from("src/main.rs"),
                start: Some(1),
                end: Some(14),
            },
        )
        .await
        .unwrap();
    println!("Result: {:?}", result);
}

#[tokio::test]
async fn test_search_text() {
    // fake test to just see the serch results
    let base_dir = std::env::current_dir().expect("Cannot get current directory");
    let st = SearchText::new(&base_dir, 100);
    let result = st
        .call(
            &mut ToolContext::default(),
            SearchTextArgs {
                path: PathBuf::from("src"),
                text: "unwrap()".to_string(),
                start: None,
            },
        )
        .await
        .unwrap();
    println!("Result: {:?}", result);
}

#[tokio::test]
async fn test_web_search() {
    // fake test to just see the serch results
    let config = config::load_config().expect("Should be able to load config.");
    let ws = WebSearch::new(&config::WebSearch {
        provider: WebSearchProvider::Tavily,
        url: config
            .tools
            .web_search
            .expect("Should have websearch configured for tests")
            .url,
    })
    .await
    .expect("Should be able to instantiate web search");
    let result = ws
        .call(
            &mut ToolContext::default(),
            WebSearchArgs {
                query: "Rust latest version".to_string(),
                max_results: 5,
            },
        )
        .await
        .unwrap();
    println!("Result: {:?}", result);
}