exfiltrate 0.1.0

An embeddable MCP server for Rust.
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Tool management and invocation system for the Model Context Protocol.
//!
//! This module provides the infrastructure for registering, discovering, and invoking
//! tools within the MCP framework. Tools are functions that can be called remotely
//! through the JSON-RPC protocol, allowing AI agents to interact with external services
//! and perform actions.
//!
//! # Architecture
//!
//! The module manages two collections of tools:
//!
//! - **Target Tools** (`TOOLS`): Tools available only in the target application
//! - **Shared Tools** (`SHARED_TOOLS`): Tools available in both proxy and target applications
//!
//! # Tool Implementation
//!
//! Tools must implement the [`Tool`] trait, which defines:
//! - Metadata (name and description)
//! - Input schema for parameter validation
//! - Execution logic
//!
//! # Examples
//!
//! ## Implementing a custom tool
//!
//! ```
//! use exfiltrate::mcp::tools::{Tool, InputSchema, Argument, ToolCallResponse, ToolCallError};
//! use std::collections::HashMap;
//!
//! struct CalculatorTool;
//!
//! impl Tool for CalculatorTool {
//!     fn name(&self) -> &str {
//!         "calculator"
//!     }
//!
//!     fn description(&self) -> &str {
//!         "Performs basic arithmetic operations"
//!     }
//!
//!     fn input_schema(&self) -> InputSchema {
//!         InputSchema::new(vec![
//!             Argument::new(
//!                 "operation".to_string(),
//!                 "string".to_string(),
//!                 "Operation to perform (add, subtract, multiply, divide)".to_string(),
//!                 true
//!             ),
//!             Argument::new(
//!                 "a".to_string(),
//!                 "number".to_string(),
//!                 "First operand".to_string(),
//!                 true
//!             ),
//!             Argument::new(
//!                 "b".to_string(),
//!                 "number".to_string(),
//!                 "Second operand".to_string(),
//!                 true
//!             ),
//!         ])
//!     }
//!
//!     fn call(&self, params: HashMap<String, serde_json::Value>)
//!         -> Result<ToolCallResponse, ToolCallError> {
//!         let op = params.get("operation")
//!             .and_then(|v| v.as_str())
//!             .ok_or_else(|| ToolCallError::new(vec!["Missing operation".into()]))?;
//!         
//!         let a = params.get("a")
//!             .and_then(|v| v.as_f64())
//!             .ok_or_else(|| ToolCallError::new(vec!["Invalid operand a".into()]))?;
//!         
//!         let b = params.get("b")
//!             .and_then(|v| v.as_f64())
//!             .ok_or_else(|| ToolCallError::new(vec!["Invalid operand b".into()]))?;
//!         
//!         let result = match op {
//!             "add" => a + b,
//!             "subtract" => a - b,
//!             "multiply" => a * b,
//!             "divide" => {
//!                 if b == 0.0 {
//!                     return Err(ToolCallError::new(vec!["Division by zero".into()]));
//!                 }
//!                 a / b
//!             },
//!             _ => return Err(ToolCallError::new(vec!["Unknown operation".into()]))
//!         };
//!         
//!         Ok(ToolCallResponse::new(vec![format!("Result: {}", result).into()]))
//!     }
//! }
//!
//! // Register and use the tool
//! exfiltrate::mcp::tools::add_tool(Box::new(CalculatorTool));
//! ```

use crate::internal_proxy::InternalProxy;
use crate::jrpc::{Error, Notification, Request, Response};
use serde::de::{MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::fmt;
use std::sync::{LazyLock, RwLock};

/// Trait for implementing MCP tools.
///
/// Tools are functions that can be invoked remotely through the MCP protocol.
/// Each tool must provide metadata about itself and implement the execution logic.
///
/// # Thread Safety
///
/// Tools must be `Send + Sync` as they may be called from multiple threads.
///
/// # Examples
///
/// ```
/// use exfiltrate::mcp::tools::{Tool, InputSchema, Argument, ToolCallResponse, ToolCallError};
/// use std::collections::HashMap;
///
/// struct EchoTool;
///
/// impl Tool for EchoTool {
///     fn name(&self) -> &str {
///         "echo"
///     }
///
///     fn description(&self) -> &str {
///         "Echoes back the input message"
///     }
///
///     fn input_schema(&self) -> InputSchema {
///         InputSchema::new(vec![
///             Argument::new(
///                 "message".to_string(),
///                 "string".to_string(),
///                 "Message to echo".to_string(),
///                 true
///             ),
///         ])
///     }
///
///     fn call(&self, params: HashMap<String, serde_json::Value>)
///         -> Result<ToolCallResponse, ToolCallError> {
///         let message = params.get("message")
///             .and_then(|v| v.as_str())
///             .ok_or_else(|| ToolCallError::new(vec!["Missing message".into()]))?;
///         
///         Ok(ToolCallResponse::new(vec![format!("Echo: {}", message).into()]))
///     }
/// }
/// ```
pub trait Tool: Send + Sync {
    /// Returns the unique name of the tool.
    ///
    /// This name is used to identify the tool in MCP requests.
    fn name(&self) -> &str;

    /// Returns a human-readable description of what the tool does.
    ///
    /// This description is shown to users and AI agents to help them
    /// understand the tool's purpose.
    fn description(&self) -> &str;

    /// Returns the schema defining the tool's input parameters.
    ///
    /// The schema specifies what parameters the tool accepts, their types,
    /// and whether they are required.
    fn input_schema(&self) -> InputSchema;

    /// Executes the tool with the provided parameters.
    ///
    /// # Arguments
    ///
    /// * `params` - A map of parameter names to their JSON values
    ///
    /// # Returns
    ///
    /// * `Ok(ToolCallResponse)` - Success response with tool output
    /// * `Err(ToolCallError)` - Error response if the tool execution fails
    fn call(
        &self,
        params: HashMap<String, serde_json::Value>,
    ) -> Result<ToolCallResponse, ToolCallError>;
}

/// Tools available in the target application.
///
/// This collection stores tools that are specific to the target application
/// and should not be accessed directly from the proxy. Tools can be dynamically
/// added at runtime using [`add_tool`].
///
/// # Thread Safety
///
/// The collection is protected by a `RwLock` to allow concurrent reads and
/// exclusive writes.
pub(crate) static TOOLS: LazyLock<RwLock<Vec<Box<dyn Tool>>>> =
    LazyLock::new(|| RwLock::new(vec![]));

/// Tools available in both proxy and target applications.
///
/// These tools provide core functionality that is useful in both contexts,
/// such as dynamic tool discovery.
pub(crate) static SHARED_TOOLS: LazyLock<Vec<Box<dyn Tool>>> = LazyLock::new(|| {
    vec![
        Box::new(crate::mcp::latest_tools::LatestTools),
        Box::new(crate::mcp::latest_tools::RunLatestTool),
    ]
});

/// A collection of tool information.
///
/// Used to return tool metadata in response to `tools/list` requests.
///
/// # Examples
///
/// ```
/// use exfiltrate::mcp::tools::ToolList;
///
/// let empty_list = ToolList::empty();
/// // The list is created empty
/// let json = serde_json::to_string(&empty_list).unwrap();
/// assert!(json.contains("\"tools\":[]"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ToolList {
    /// The list of available tools with their metadata
    pub(crate) tools: Vec<ToolInfo>,
}

impl ToolList {
    /// Creates an empty tool list.
    ///
    /// # Examples
    ///
    /// ```
    /// use exfiltrate::mcp::tools::ToolList;
    ///
    /// let list = ToolList::empty();
    /// // Verify it serializes as an empty list
    /// let json = serde_json::to_string(&list).unwrap();
    /// assert!(json.contains("\"tools\":[]"));
    /// ```
    pub fn empty() -> Self {
        ToolList { tools: Vec::new() }
    }
}

/// Metadata about a tool.
///
/// Contains all the information needed for an agent to understand
/// and invoke a tool.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) struct ToolInfo {
    /// The unique name of the tool
    name: String,
    /// Human-readable description of the tool's purpose
    description: String,
    /// Schema defining the tool's input parameters
    #[serde(rename = "inputSchema")]
    input_schema: InputSchema,
}

impl ToolInfo {
    /// Creates tool info from a Tool trait object.
    ///
    /// Extracts metadata from the tool implementation.
    pub(crate) fn from_tool(tool: &dyn Tool) -> Self {
        ToolInfo {
            name: tool.name().to_string(),
            description: tool.description().to_string(),
            input_schema: tool.input_schema(),
        }
    }
}

/// Schema defining a tool's input parameters.
///
/// Follows JSON Schema format to describe the structure and validation
/// rules for tool parameters.
///
/// # Examples
///
/// ```
/// use exfiltrate::mcp::tools::{InputSchema, Argument};
///
/// let schema = InputSchema::new(vec![
///     Argument::new(
///         "text".to_string(),
///         "string".to_string(),
///         "Input text".to_string(),
///         true
///     ),
///     Argument::new(
///         "count".to_string(),
///         "number".to_string(),
///         "Optional count".to_string(),
///         false
///     ),
/// ]);
/// ```
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
pub struct InputSchema {
    /// The schema type (always "object" for tool parameters)
    r#type: String,
    /// Map of parameter names to their schema definitions
    properties: HashMap<String, HashMap<String, serde_json::Value>>,
    /// List of required parameter names
    required: Vec<String>,
}

/// Represents a single parameter for a tool.
///
/// Used to construct input schemas for tools.
///
/// # Examples
///
/// ```
/// use exfiltrate::mcp::tools::Argument;
///
/// let arg = Argument::new(
///     "filename".to_string(),
///     "string".to_string(),
///     "Path to the file".to_string(),
///     true  // required
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Argument {
    /// The parameter name
    name: String,
    /// The parameter type (e.g., "string", "number", "boolean", "object")
    r#type: String,
    /// Human-readable description of the parameter
    description: String,
    /// Whether this parameter is required
    required: bool,
}

impl Argument {
    /// Creates a new tool argument specification.
    ///
    /// # Arguments
    ///
    /// * `name` - The parameter name
    /// * `type` - The JSON type ("string", "number", "boolean", "object", "array")
    /// * `description` - Human-readable description
    /// * `required` - Whether the parameter is required
    ///
    /// # Examples
    ///
    /// ```
    /// use exfiltrate::mcp::tools::Argument;
    ///
    /// let required_arg = Argument::new(
    ///     "input".to_string(),
    ///     "string".to_string(),
    ///     "The input text to process".to_string(),
    ///     true
    /// );
    ///
    /// let optional_arg = Argument::new(
    ///     "verbose".to_string(),
    ///     "boolean".to_string(),
    ///     "Enable verbose output".to_string(),
    ///     false
    /// );
    /// ```
    pub fn new(name: String, r#type: String, description: String, required: bool) -> Self {
        Self {
            name,
            r#type,
            description,
            required,
        }
    }
}

impl InputSchema {
    /// Creates a new input schema from a collection of arguments.
    ///
    /// Converts the argument specifications into a JSON Schema format
    /// suitable for parameter validation.
    ///
    /// # Arguments
    ///
    /// * `arguments` - An iterator of [`Argument`] specifications
    ///
    /// # Examples
    ///
    /// ```
    /// use exfiltrate::mcp::tools::{InputSchema, Argument};
    ///
    /// let schema = InputSchema::new(vec![
    ///     Argument::new(
    ///         "query".to_string(),
    ///         "string".to_string(),
    ///         "Search query".to_string(),
    ///         true
    ///     ),
    ///     Argument::new(
    ///         "limit".to_string(),
    ///         "number".to_string(),
    ///         "Maximum results".to_string(),
    ///         false
    ///     ),
    /// ]);
    /// ```
    pub fn new<A: IntoIterator<Item = Argument>>(arguments: A) -> Self {
        let mut properties = HashMap::new();
        let mut required = Vec::new();
        for argument in arguments {
            let mut inner_map: HashMap<String, serde_json::Value> = HashMap::new();
            inner_map.insert("type".to_string(), argument.r#type.into());
            inner_map.insert("description".to_string(), argument.description.into());
            if argument.required {
                required.push(argument.name.clone());
            }
            properties.insert(argument.name, inner_map);
        }
        InputSchema {
            r#type: "object".to_string(),
            properties,
            required,
        }
    }
}

/// Internal function to list all available tools.
///
/// Combines tools from both [`TOOLS`] and [`SHARED_TOOLS`] collections.
pub(crate) fn list_int() -> ToolList {
    let tool_infos: Vec<ToolInfo> = TOOLS
        .read()
        .unwrap()
        .iter()
        .chain(SHARED_TOOLS.iter())
        .map(|tool| ToolInfo::from_tool(tool.as_ref()))
        .collect();

    ToolList { tools: tool_infos }
}

/// Processes a `tools/list` request.
///
/// Returns a list of all tools available in the current application
/// (target application context).
///
/// # Arguments
///
/// * `request` - The JSON-RPC request
///
/// # Returns
///
/// A response containing the list of available tools
pub(crate) fn list_process(request: Request) -> Response<ToolList> {
    let tool_list = list_int();

    Response::new(tool_list, request.id)
}

/// Registers a new tool in the target application.
///
/// Adds the tool to the `TOOLS` collection and sends a notification
/// to inform connected clients that the tool list has changed.
///
/// # Arguments
///
/// * `tool` - The tool implementation to register
///
/// # Examples
///
/// ```
/// use exfiltrate::mcp::tools::{Tool, InputSchema, ToolCallResponse, ToolCallError, add_tool};
/// use std::collections::HashMap;
///
/// struct MyTool;
///
/// impl Tool for MyTool {
///     fn name(&self) -> &str { "my_tool" }
///     fn description(&self) -> &str { "A custom tool" }
///     fn input_schema(&self) -> InputSchema { InputSchema::new(vec![]) }
///     fn call(&self, _: HashMap<String, serde_json::Value>)
///         -> Result<ToolCallResponse, ToolCallError> {
///         Ok(ToolCallResponse::new(vec!["Success".into()]))
///     }
/// }
///
/// add_tool(Box::new(MyTool));
/// ```
pub fn add_tool(tool: Box<dyn Tool>) {
    TOOLS.write().unwrap().push(tool);
    //create a tool changed message
    let n = Notification::new("notifications/tools/list_changed".to_string(), None);
    let r = InternalProxy::current().send_notification(n);
    match r {
        Ok(_) => {}
        Err(crate::internal_proxy::Error::NotConnected) => {
            //benign
        }
    }
}

/// Parameters for invoking a tool.
///
/// Used internally to deserialize tool call requests.
#[derive(Debug, serde::Deserialize, Clone)]
pub(crate) struct ToolCallParams {
    /// Name of the tool to invoke
    pub(crate) name: String,
    /// Arguments to pass to the tool
    pub(crate) arguments: HashMap<String, serde_json::Value>,
}

impl ToolCallParams {
    /// Creates new tool call parameters.
    pub(crate) fn new(name: String, arguments: HashMap<String, serde_json::Value>) -> Self {
        ToolCallParams { name, arguments }
    }
}

/// Response from a successful tool invocation.
///
/// Contains the output content from the tool execution.
///
/// # Examples
///
/// ```
/// use exfiltrate::mcp::tools::ToolCallResponse;
///
/// let response = ToolCallResponse::new(vec![
///     "Operation completed successfully".into(),
///     "Result: 42".into(),
/// ]);
/// ```
#[derive(Debug, serde::Serialize, serde::Deserialize, Default)]
pub struct ToolCallResponse {
    /// The content returned by the tool
    pub(crate) content: Vec<ToolContent>,
    /// Whether this response represents an error
    is_error: bool,
}

impl ToolCallResponse {
    /// Creates a new successful tool response.
    ///
    /// # Arguments
    ///
    /// * `content` - The content to return from the tool
    ///
    /// # Examples
    ///
    /// ```
    /// use exfiltrate::mcp::tools::ToolCallResponse;
    ///
    /// let response = ToolCallResponse::new(vec![
    ///     "Task completed".into(),
    /// ]);
    /// ```
    pub fn new(content: Vec<ToolContent>) -> Self {
        ToolCallResponse {
            content,
            is_error: false,
        }
    }
}

/// Error response from a failed tool invocation.
///
/// Contains error messages explaining why the tool execution failed.
///
/// # Examples
///
/// ```
/// use exfiltrate::mcp::tools::ToolCallError;
///
/// let error = ToolCallError::new(vec![
///     "Invalid input: missing required parameter 'filename'".into(),
/// ]);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, thiserror::Error)]
#[error("Tool call failed: {}", format_content(&self.content))]
pub struct ToolCallError {
    /// Error messages
    content: Vec<ToolContent>,
    /// Always true for error responses
    is_error: bool,
}

impl ToolCallError {
    /// Creates a new tool error response.
    ///
    /// # Arguments
    ///
    /// * `content` - Error messages to return
    ///
    /// # Examples
    ///
    /// ```
    /// use exfiltrate::mcp::tools::ToolCallError;
    ///
    /// let error = ToolCallError::new(vec![
    ///     "Database connection failed".into(),
    ///     "Please check your connection settings".into(),
    /// ]);
    /// ```
    pub fn new(content: Vec<ToolContent>) -> Self {
        ToolCallError {
            content,
            is_error: true,
        }
    }

    /// Converts this error into a ToolCallResponse.
    ///
    /// Used internally to unify error and success responses.
    pub(crate) fn into_response(self) -> ToolCallResponse {
        ToolCallResponse {
            content: self.content,
            is_error: true,
        }
    }
}

/// Content returned by a tool.
///
/// Currently supports text content, but marked as `non_exhaustive`
/// to allow for future content types (e.g., images, structured data).
///
/// # Examples
///
/// ```
/// use exfiltrate::mcp::tools::ToolContent;
///
/// let text_content = ToolContent::from("Hello, world!");
/// let string_content = ToolContent::from(String::from("Dynamic content"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ToolContent {
    /// Text content
    Text(String),
}
impl ToolContent {
    /// Returns the content as a string slice if it's text content.
    ///
    /// # Returns
    ///
    /// * `Some(&str)` if the content is text
    /// * `None` for other content types (when added in the future)
    #[cfg(feature = "transit")]
    pub(crate) fn as_str(&self) -> Option<&str> {
        match self {
            ToolContent::Text(text) => Some(text),
        }
    }
}
impl Serialize for ToolContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::SerializeStruct;
        match self {
            ToolContent::Text(text) => {
                let mut s = serializer.serialize_struct("ToolContent", 2)?;

                s.serialize_field("type", "text")?;
                s.serialize_field("text", text)?;
                s.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for ToolContent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de;
        struct ToolContentVisitor;

        impl<'de> Visitor<'de> for ToolContentVisitor {
            type Value = ToolContent;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a tool content object with type and data")
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut content_type: Option<String> = None;
                let mut text: Option<String> = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "type" => {
                            if content_type.is_some() {
                                return Err(de::Error::duplicate_field("type"));
                            }
                            content_type = Some(map.next_value()?);
                        }
                        "text" => {
                            if text.is_some() {
                                return Err(de::Error::duplicate_field("text"));
                            }
                            text = Some(map.next_value()?);
                        }
                        _ => {
                            let _: de::IgnoredAny = map.next_value()?;
                        }
                    }
                }

                match content_type.as_deref() {
                    Some("text") => {
                        let text = text.ok_or_else(|| de::Error::missing_field("text"))?;
                        Ok(ToolContent::Text(text))
                    }
                    Some(other) => Err(de::Error::unknown_variant(other, &["text"])),
                    None => Err(de::Error::missing_field("type")),
                }
            }
        }

        deserializer.deserialize_map(ToolContentVisitor)
    }
}

impl From<String> for ToolContent {
    fn from(value: String) -> Self {
        ToolContent::Text(value)
    }
}

impl From<&str> for ToolContent {
    fn from(value: &str) -> Self {
        ToolContent::Text(value.to_string())
    }
}

/// Internal implementation for calling a tool.
///
/// Looks up the tool by name and invokes it with the provided arguments.
/// Searches both [`TOOLS`] and [`SHARED_TOOLS`] collections.
pub(crate) fn call_imp(params: ToolCallParams) -> Result<ToolCallResponse, crate::jrpc::Error> {
    let tools = TOOLS.read().unwrap();
    let tool = tools
        .iter()
        .chain(SHARED_TOOLS.iter())
        .find(|t| t.name() == params.name)
        .map(|t| t.as_ref());
    match tool {
        Some(tool) => {
            let call = tool.call(params.arguments);
            match call {
                Ok(response) => Ok(response),
                Err(err) => Ok(err.into_response()),
            }
        }
        None => Err(Error::unknown_tool(params.name)),
    }
}

/// Processes a `tools/call` request.
///
/// Parses the request parameters and invokes the specified tool.
///
/// # Arguments
///
/// * `request` - The JSON-RPC request containing tool name and arguments
///
/// # Returns
///
/// A response containing either the tool's output or an error
pub(crate) fn call(request: Request) -> Response<ToolCallResponse> {
    let params = match request.params {
        Some(params) => match serde_json::from_value::<ToolCallParams>(params) {
            Ok(params) => params,
            Err(err) => return Response::err(Error::invalid_params(err.to_string()), request.id),
        },
        None => {
            return Response::err(
                Error::invalid_params("No parameters provided".to_string()),
                request.id,
            );
        }
    };
    let r = call_imp(params);
    match r {
        Ok(r) => Response::new(r, request.id),
        Err(e) => Response::err(e, request.id),
    }
}

// =============================================================================
// Boilerplate implementations
// =============================================================================

/// Helper function to format ToolContent for error messages.
fn format_content(content: &[ToolContent]) -> String {
    content
        .iter()
        .map(|c| match c {
            ToolContent::Text(text) => text.clone(),
        })
        .collect::<Vec<_>>()
        .join("; ")
}

// ToolCallResponse boilerplate - appears in order of definition above

impl Clone for ToolCallResponse {
    fn clone(&self) -> Self {
        Self {
            content: self.content.clone(),
            is_error: self.is_error,
        }
    }
}

impl PartialEq for ToolCallResponse {
    fn eq(&self, other: &Self) -> bool {
        self.content == other.content && self.is_error == other.is_error
    }
}

impl Eq for ToolCallResponse {}

impl std::hash::Hash for ToolCallResponse {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.content.hash(state);
        self.is_error.hash(state);
    }
}

impl fmt::Display for ToolCallResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_error {
            write!(
                f,
                "ToolCallResponse(Error): {}",
                format_content(&self.content)
            )
        } else {
            write!(
                f,
                "ToolCallResponse(Success): {}",
                format_content(&self.content)
            )
        }
    }
}

impl From<Vec<ToolContent>> for ToolCallResponse {
    fn from(content: Vec<ToolContent>) -> Self {
        Self::new(content)
    }
}

impl From<String> for ToolCallResponse {
    fn from(message: String) -> Self {
        Self::new(vec![message.into()])
    }
}

impl From<&str> for ToolCallResponse {
    fn from(message: &str) -> Self {
        Self::new(vec![message.into()])
    }
}

// ToolCallError boilerplate - appears in order of definition above

impl From<String> for ToolCallError {
    /// Creates a ToolCallError from a single error message string.
    fn from(message: String) -> Self {
        ToolCallError::new(vec![message.into()])
    }
}

impl From<&str> for ToolCallError {
    /// Creates a ToolCallError from a single error message string slice.
    fn from(message: &str) -> Self {
        ToolCallError::new(vec![message.into()])
    }
}

impl From<Vec<String>> for ToolCallError {
    /// Creates a ToolCallError from multiple error message strings.
    fn from(messages: Vec<String>) -> Self {
        ToolCallError::new(messages.into_iter().map(|m| m.into()).collect())
    }
}

impl From<ToolContent> for ToolCallError {
    /// Creates a ToolCallError from a single ToolContent.
    fn from(content: ToolContent) -> Self {
        ToolCallError::new(vec![content])
    }
}

impl std::hash::Hash for InputSchema {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.r#type.hash(state);
        // HashMap doesn't implement Hash, so we need to hash entries in a deterministic order
        let mut properties_vec: Vec<_> = self.properties.iter().collect();
        properties_vec.sort_by_key(|(k, _)| *k);
        for (k, v) in properties_vec {
            k.hash(state);
            // serde_json::Value doesn't implement Hash, so we hash the string representation
            format!("{:?}", v).hash(state);
        }
        self.required.hash(state);
    }
}

impl Default for InputSchema {
    fn default() -> Self {
        Self {
            r#type: "object".to_string(),
            properties: HashMap::new(),
            required: Vec::new(),
        }
    }
}

impl fmt::Display for InputSchema {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "InputSchema(type: {}, properties: {}, required: {:?})",
            self.r#type,
            self.properties.len(),
            self.required
        )
    }
}

// Argument boilerplate - appears in order of definition above
impl fmt::Display for Argument {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}: {} ({}) - {}",
            self.name,
            self.r#type,
            if self.required {
                "required"
            } else {
                "optional"
            },
            self.description
        )
    }
}

// ToolContent boilerplate - appears in order of definition above

impl Default for ToolContent {
    fn default() -> Self {
        ToolContent::Text(String::new())
    }
}

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

impl AsRef<str> for ToolContent {
    fn as_ref(&self) -> &str {
        match self {
            ToolContent::Text(text) => text,
        }
    }
}

impl std::ops::Deref for ToolContent {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        match self {
            ToolContent::Text(text) => text,
        }
    }
}

// ToolList boilerplate - appears in order of definition above

impl Default for ToolList {
    fn default() -> Self {
        Self::empty()
    }
}

impl fmt::Display for ToolList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ToolList({} tools)", self.tools.len())
    }
}

impl From<Vec<ToolInfo>> for ToolList {
    fn from(tools: Vec<ToolInfo>) -> Self {
        ToolList { tools }
    }
}

impl From<ToolList> for Vec<ToolInfo> {
    fn from(tool_list: ToolList) -> Self {
        tool_list.tools
    }
}

impl AsRef<Vec<ToolInfo>> for ToolList {
    fn as_ref(&self) -> &Vec<ToolInfo> {
        &self.tools
    }
}